text
stringlengths
54
60.6k
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 * * (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ // Author: Hadrien Courtecuisse // // Copyright: See COPYING file that comes with this distribution #include <sofa/core/objectmodel/BaseContext.h> #include <sofa/core/componentmodel/behavior/LinearSolver.h> #include <sofa/component/linearsolver/ShewchukPCGLinearSolver.h> #include <sofa/component/linearsolver/NewMatMatrix.h> #include <sofa/component/linearsolver/FullMatrix.h> #include <sofa/component/linearsolver/SparseMatrix.h> #include <sofa/simulation/common/MechanicalVisitor.h> #include <sofa/helper/system/thread/CTime.h> #include <sofa/helper/AdvancedTimer.h> #include <sofa/core/ObjectFactory.h> #include <iostream> namespace sofa { namespace component { namespace linearsolver { using namespace sofa::defaulttype; using namespace sofa::core::componentmodel::behavior; using namespace sofa::simulation; using namespace sofa::core::objectmodel; using sofa::helper::system::thread::CTime; using sofa::helper::system::thread::ctime_t; using std::cerr; using std::endl; template<class TMatrix, class TVector> ShewchukPCGLinearSolver<TMatrix,TVector>::ShewchukPCGLinearSolver() : f_maxIter( initData(&f_maxIter,(unsigned)25,"iterations","maximum number of iterations of the Conjugate Gradient solution") ) , f_tolerance( initData(&f_tolerance,1e-5,"tolerance","desired precision of the Conjugate Gradient Solution (ratio of current residual norm over initial residual norm)") ) , f_verbose( initData(&f_verbose,false,"verbose","Dump system state at each iteration") ) , f_refresh( initData(&f_refresh,0,"refresh","Refresh iterations") ) , use_precond( initData(&use_precond,true,"use_precond","Use preconditioners") ) , f_preconditioners( initData(&f_preconditioners, "preconditioners", "If not empty: path to the solvers to use as preconditioners") ) , f_graph( initData(&f_graph,"graph","Graph of residuals at each iteration") ) { f_graph.setWidget("graph"); f_graph.setReadOnly(true); iteration = 0; usePrecond = true; } template<class TMatrix, class TVector> void ShewchukPCGLinearSolver<TMatrix,TVector>::init() { std::vector<sofa::core::componentmodel::behavior::LinearSolver*> solvers; BaseContext * c = this->getContext(); const helper::vector<std::string>& precondNames = f_preconditioners.getValue(); if (precondNames.empty() || !use_precond.getValue()) { c->get<sofa::core::componentmodel::behavior::LinearSolver>(&solvers,BaseContext::SearchDown); } else { for (unsigned int i=0; i<precondNames.size(); ++i) { sofa::core::componentmodel::behavior::LinearSolver* s = NULL; c->get(s, precondNames[i]); if (s) solvers.push_back(s); else serr << "Solver \"" << precondNames[i] << "\" not found." << sendl; } } for (unsigned int i=0; i<solvers.size(); ++i) { if (solvers[i] && solvers[i] != this) { this->preconditioners.push_back(solvers[i]); } } sout<<"Found " << this->preconditioners.size() << " preconditioners"<<sendl; first = true; } template<class TMatrix, class TVector> void ShewchukPCGLinearSolver<TMatrix,TVector>::setSystemMBKMatrix(double mFact, double bFact, double kFact) { sofa::helper::AdvancedTimer::valSet("PCG::buildMBK", 1); sofa::helper::AdvancedTimer::stepBegin("PCG::setSystemMBKMatrix"); Inherit::setSystemMBKMatrix(mFact,bFact,kFact); sofa::helper::AdvancedTimer::stepEnd("PCG::setSystemMBKMatrix(Precond)"); usePrecond = use_precond.getValue(); if (preconditioners.size()==0) return; if (first) //We initialize all the preconditioners for the first step { first = false; if (iteration<=0) { for (unsigned int i=0; i<this->preconditioners.size(); ++i) { preconditioners[i]->setSystemMBKMatrix(mFact,bFact,kFact); } iteration = f_refresh.getValue(); } else { iteration--; } } else if (usePrecond ) // We use only the first precond in the list { sofa::helper::AdvancedTimer::valSet("PCG::PrecondBuildMBK", 1); sofa::helper::AdvancedTimer::stepBegin("PCG::PrecondSetSystemMBKMatrix"); if (iteration<=0) { preconditioners[0]->setSystemMBKMatrix(mFact,bFact,kFact); iteration = f_refresh.getValue(); } else { iteration--; } sofa::helper::AdvancedTimer::stepEnd("PCG::PrecondSetSystemMBKMatrix"); } } template<> inline void ShewchukPCGLinearSolver<component::linearsolver::GraphScatteredMatrix,component::linearsolver::GraphScatteredVector>::cgstep_beta(Vector& p, Vector& r, double beta) { this->v_op(p,r,p,beta); // p = p*beta + r } template<> inline void ShewchukPCGLinearSolver<component::linearsolver::GraphScatteredMatrix,component::linearsolver::GraphScatteredVector>::cgstep_alpha(Vector& x, Vector& p, double alpha) { x.peq(p,alpha); // x = x + alpha p } /* template<class TMatrix, class TVector> void ShewchukPCGLinearSolver<TMatrix,TVector>::solve (Matrix& M, Vector& x, Vector& b) { using std::cerr; using std::endl; Vector& p = *this->createVector(); Vector& q = *this->createVector(); Vector& r = *this->createVector(); Vector& z = *this->createVector(); const bool printLog = this->f_printLog.getValue(); const bool verbose = f_verbose.getValue(); // -- solve the system using a conjugate gradient solution double rho, rho_1=0, alpha, beta; if( verbose ) cerr<<"PCGLinearSolver, b = "<< b <<endl; x.clear(); r = b; // initial residual double normb2 = b.dot(b); double normb = sqrt(normb2); std::map < std::string, sofa::helper::vector<double> >& graph = *f_graph.beginEdit(); sofa::helper::vector<double>& graph_error = graph["Error"]; graph_error.clear(); sofa::helper::vector<double>& graph_den = graph["Denominator"]; graph_den.clear(); graph_error.push_back(1); unsigned nb_iter; const char* endcond = "iterations"; for( nb_iter=1; nb_iter<=f_maxIter.getValue(); nb_iter++ ) { if (this->preconditioners.size()>0 && usePrecond) { sofa::helper::AdvancedTimer::stepBegin("PCGLinearSolver::apply Precond"); // for (unsigned int i=0;i<this->preconditioners.size();i++) { // preconditioners[i]->setSystemLHVector(z); // preconditioners[i]->setSystemRHVector(r); // preconditioners[i]->solveSystem(); // } preconditioners[0]->setSystemLHVector(z); preconditioners[0]->setSystemRHVector(r); preconditioners[0]->solveSystem(); sofa::helper::AdvancedTimer::stepEnd("PCGLinearSolver::apply Precond"); } else { z = r; } sofa::helper::AdvancedTimer::stepBegin("PCGLinearSolver::solve"); rho = r.dot(z); if (nb_iter>1) { double normr = sqrt(r.dot(r)); double err = normr/normb; graph_error.push_back(err); if (err <= f_tolerance.getValue()) { endcond = "tolerance"; break; } } if( nb_iter==1 ) p = z; else { beta = rho / rho_1; //p = p*beta + z; cgstep_beta(p,z,beta); } if( verbose ) cerr<<"p : "<<p<<endl; // matrix-vector product q = M*p; if( verbose ) cerr<<"q = M p : "<<q<<endl; double den = p.dot(q); graph_den.push_back(den); alpha = rho/den; //x.peq(p,alpha); // x = x + alpha p //r.peq(q,-alpha); // r = r - alpha q cgstep_alpha(x,p,alpha); cgstep_alpha(r,q,-alpha); if( verbose ) { cerr<<"den = "<<den<<", alpha = "<<alpha<<endl; cerr<<"x : "<<x<<endl; cerr<<"r : "<<r<<endl; } rho_1 = rho; sofa::helper::AdvancedTimer::stepEnd("PCGLinearSolver::solve"); } sofa::helper::AdvancedTimer::valSet("PCG iterations", nb_iter); f_graph.endEdit(); // x is the solution of the system if( printLog ) cerr<<"PCGLinearSolver::solve, nbiter = "<<nb_iter<<" stop because of "<<endcond<<endl; if( verbose ) cerr<<"PCGLinearSolver::solve, solution = "<<x<<endl; this->deleteVector(&p); this->deleteVector(&q); this->deleteVector(&r); this->deleteVector(&z); } */ template<class TMatrix, class TVector> void ShewchukPCGLinearSolver<TMatrix,TVector>::solve (Matrix& M, Vector& x, Vector& b) { Vector& r = *this->createVector(); Vector& d = *this->createVector(); Vector& q = *this->createVector(); Vector& s = *this->createVector(); const bool verbose = f_verbose.getValue(); unsigned iter=1; r = M*x; cgstep_beta(r,b,-1);//for (int i=0; i<n; i++) r[i] = b[i] - r[i]; if (this->preconditioners.size()>0 && usePrecond) { preconditioners[0]->setSystemLHVector(d); preconditioners[0]->setSystemRHVector(r); preconditioners[0]->solveSystem(); } else { d = r; } double deltaNew = r.dot(d); double delta0 = deltaNew; double eps = f_tolerance.getValue() * f_tolerance.getValue() * delta0; std::map < std::string, sofa::helper::vector<double> >& graph = * f_graph.beginEdit(); sofa::helper::vector<double>& graph_error = graph["Error"]; graph_error.clear(); while ((iter <= f_maxIter.getValue()) && (deltaNew > eps)) { if (verbose) printf("CG iteration %d: current L2 error vs initial error=%G\n", iter, sqrt(deltaNew/delta0)); graph_error.push_back(deltaNew); q = M * d; double dtq = d.dot(q); double alpha = deltaNew / dtq; cgstep_alpha(x,d,alpha);//for(int i=0; i<n; i++) x[i] += alpha * d[i]; if (iter % 50 == 0) // periodically compute the exact residual { r = M * x; cgstep_beta(r,b,-1);//for (int i=0; i<n; i++) r[i] = b[i] - r[i]; } else { cgstep_alpha(r,q,-alpha);//for (int i=0; i<n; i++) r[i] = r[i] - alpha * q[i]; } if (this->preconditioners.size()>0 && usePrecond) { preconditioners[0]->setSystemLHVector(s); preconditioners[0]->setSystemRHVector(r); preconditioners[0]->solveSystem(); } else { s = r; } double deltaOld = deltaNew; deltaNew = r.dot(s); double beta = deltaNew / deltaOld; cgstep_beta(d,s,beta);//for (int i=0; i<n; i++) d[i] = r[i] + beta * d[i]; iter++; } f_graph.endEdit(); this->deleteVector(&r); this->deleteVector(&q); this->deleteVector(&d); this->deleteVector(&s); } SOFA_DECL_CLASS(ShewchukPCGLinearSolver) int ShewchukPCGLinearSolverClass = core::RegisterObject("Linear system solver using the conjugate gradient iterative algorithm") .add< ShewchukPCGLinearSolver<GraphScatteredMatrix,GraphScatteredVector> >(true) ; } // namespace linearsolver } // namespace component } // namespace sofa <commit_msg>r7214/sofa-dev : add timer in ShewchukPCGLinearSolver + begin bench for rasterizer<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 * * (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ // Author: Hadrien Courtecuisse // // Copyright: See COPYING file that comes with this distribution #include <sofa/core/objectmodel/BaseContext.h> #include <sofa/core/componentmodel/behavior/LinearSolver.h> #include <sofa/component/linearsolver/ShewchukPCGLinearSolver.h> #include <sofa/component/linearsolver/NewMatMatrix.h> #include <sofa/component/linearsolver/FullMatrix.h> #include <sofa/component/linearsolver/SparseMatrix.h> #include <sofa/simulation/common/MechanicalVisitor.h> #include <sofa/helper/system/thread/CTime.h> #include <sofa/helper/AdvancedTimer.h> #include <sofa/core/ObjectFactory.h> #include <iostream> namespace sofa { namespace component { namespace linearsolver { using namespace sofa::defaulttype; using namespace sofa::core::componentmodel::behavior; using namespace sofa::simulation; using namespace sofa::core::objectmodel; using sofa::helper::system::thread::CTime; using sofa::helper::system::thread::ctime_t; using std::cerr; using std::endl; template<class TMatrix, class TVector> ShewchukPCGLinearSolver<TMatrix,TVector>::ShewchukPCGLinearSolver() : f_maxIter( initData(&f_maxIter,(unsigned)25,"iterations","maximum number of iterations of the Conjugate Gradient solution") ) , f_tolerance( initData(&f_tolerance,1e-5,"tolerance","desired precision of the Conjugate Gradient Solution (ratio of current residual norm over initial residual norm)") ) , f_verbose( initData(&f_verbose,false,"verbose","Dump system state at each iteration") ) , f_refresh( initData(&f_refresh,0,"refresh","Refresh iterations") ) , use_precond( initData(&use_precond,true,"use_precond","Use preconditioners") ) , f_preconditioners( initData(&f_preconditioners, "preconditioners", "If not empty: path to the solvers to use as preconditioners") ) , f_graph( initData(&f_graph,"graph","Graph of residuals at each iteration") ) { f_graph.setWidget("graph"); f_graph.setReadOnly(true); iteration = 0; usePrecond = true; } template<class TMatrix, class TVector> void ShewchukPCGLinearSolver<TMatrix,TVector>::init() { std::vector<sofa::core::componentmodel::behavior::LinearSolver*> solvers; BaseContext * c = this->getContext(); const helper::vector<std::string>& precondNames = f_preconditioners.getValue(); if (precondNames.empty() || !use_precond.getValue()) { c->get<sofa::core::componentmodel::behavior::LinearSolver>(&solvers,BaseContext::SearchDown); } else { for (unsigned int i=0; i<precondNames.size(); ++i) { sofa::core::componentmodel::behavior::LinearSolver* s = NULL; c->get(s, precondNames[i]); if (s) solvers.push_back(s); else serr << "Solver \"" << precondNames[i] << "\" not found." << sendl; } } for (unsigned int i=0; i<solvers.size(); ++i) { if (solvers[i] && solvers[i] != this) { this->preconditioners.push_back(solvers[i]); } } sout<<"Found " << this->preconditioners.size() << " preconditioners"<<sendl; first = true; } template<class TMatrix, class TVector> void ShewchukPCGLinearSolver<TMatrix,TVector>::setSystemMBKMatrix(double mFact, double bFact, double kFact) { sofa::helper::AdvancedTimer::valSet("PCG::buildMBK", 1); sofa::helper::AdvancedTimer::stepBegin("PCG::setSystemMBKMatrix"); Inherit::setSystemMBKMatrix(mFact,bFact,kFact); sofa::helper::AdvancedTimer::stepEnd("PCG::setSystemMBKMatrix(Precond)"); usePrecond = use_precond.getValue(); if (preconditioners.size()==0) return; if (first) //We initialize all the preconditioners for the first step { first = false; if (iteration<=0) { for (unsigned int i=0; i<this->preconditioners.size(); ++i) { preconditioners[i]->setSystemMBKMatrix(mFact,bFact,kFact); } iteration = f_refresh.getValue(); } else { iteration--; } } else if (usePrecond ) // We use only the first precond in the list { sofa::helper::AdvancedTimer::valSet("PCG::PrecondBuildMBK", 1); sofa::helper::AdvancedTimer::stepBegin("PCG::PrecondSetSystemMBKMatrix"); if (iteration<=0) { preconditioners[0]->setSystemMBKMatrix(mFact,bFact,kFact); iteration = f_refresh.getValue(); } else { iteration--; } sofa::helper::AdvancedTimer::stepEnd("PCG::PrecondSetSystemMBKMatrix"); } } template<> inline void ShewchukPCGLinearSolver<component::linearsolver::GraphScatteredMatrix,component::linearsolver::GraphScatteredVector>::cgstep_beta(Vector& p, Vector& r, double beta) { this->v_op(p,r,p,beta); // p = p*beta + r } template<> inline void ShewchukPCGLinearSolver<component::linearsolver::GraphScatteredMatrix,component::linearsolver::GraphScatteredVector>::cgstep_alpha(Vector& x, Vector& p, double alpha) { x.peq(p,alpha); // x = x + alpha p } /* template<class TMatrix, class TVector> void ShewchukPCGLinearSolver<TMatrix,TVector>::solve (Matrix& M, Vector& x, Vector& b) { using std::cerr; using std::endl; Vector& p = *this->createVector(); Vector& q = *this->createVector(); Vector& r = *this->createVector(); Vector& z = *this->createVector(); const bool printLog = this->f_printLog.getValue(); const bool verbose = f_verbose.getValue(); // -- solve the system using a conjugate gradient solution double rho, rho_1=0, alpha, beta; if( verbose ) cerr<<"PCGLinearSolver, b = "<< b <<endl; x.clear(); r = b; // initial residual double normb2 = b.dot(b); double normb = sqrt(normb2); std::map < std::string, sofa::helper::vector<double> >& graph = *f_graph.beginEdit(); sofa::helper::vector<double>& graph_error = graph["Error"]; graph_error.clear(); sofa::helper::vector<double>& graph_den = graph["Denominator"]; graph_den.clear(); graph_error.push_back(1); unsigned nb_iter; const char* endcond = "iterations"; for( nb_iter=1; nb_iter<=f_maxIter.getValue(); nb_iter++ ) { if (this->preconditioners.size()>0 && usePrecond) { sofa::helper::AdvancedTimer::stepBegin("PCGLinearSolver::apply Precond"); // for (unsigned int i=0;i<this->preconditioners.size();i++) { // preconditioners[i]->setSystemLHVector(z); // preconditioners[i]->setSystemRHVector(r); // preconditioners[i]->solveSystem(); // } preconditioners[0]->setSystemLHVector(z); preconditioners[0]->setSystemRHVector(r); preconditioners[0]->solveSystem(); sofa::helper::AdvancedTimer::stepEnd("PCGLinearSolver::apply Precond"); } else { z = r; } sofa::helper::AdvancedTimer::stepBegin("PCGLinearSolver::solve"); rho = r.dot(z); if (nb_iter>1) { double normr = sqrt(r.dot(r)); double err = normr/normb; graph_error.push_back(err); if (err <= f_tolerance.getValue()) { endcond = "tolerance"; break; } } if( nb_iter==1 ) p = z; else { beta = rho / rho_1; //p = p*beta + z; cgstep_beta(p,z,beta); } if( verbose ) cerr<<"p : "<<p<<endl; // matrix-vector product q = M*p; if( verbose ) cerr<<"q = M p : "<<q<<endl; double den = p.dot(q); graph_den.push_back(den); alpha = rho/den; //x.peq(p,alpha); // x = x + alpha p //r.peq(q,-alpha); // r = r - alpha q cgstep_alpha(x,p,alpha); cgstep_alpha(r,q,-alpha); if( verbose ) { cerr<<"den = "<<den<<", alpha = "<<alpha<<endl; cerr<<"x : "<<x<<endl; cerr<<"r : "<<r<<endl; } rho_1 = rho; sofa::helper::AdvancedTimer::stepEnd("PCGLinearSolver::solve"); } sofa::helper::AdvancedTimer::valSet("PCG iterations", nb_iter); f_graph.endEdit(); // x is the solution of the system if( printLog ) cerr<<"PCGLinearSolver::solve, nbiter = "<<nb_iter<<" stop because of "<<endcond<<endl; if( verbose ) cerr<<"PCGLinearSolver::solve, solution = "<<x<<endl; this->deleteVector(&p); this->deleteVector(&q); this->deleteVector(&r); this->deleteVector(&z); } */ template<class TMatrix, class TVector> void ShewchukPCGLinearSolver<TMatrix,TVector>::solve (Matrix& M, Vector& x, Vector& b) { sofa::helper::AdvancedTimer::stepBegin("PCGLinearSolver::solve"); Vector& r = *this->createVector(); Vector& d = *this->createVector(); Vector& q = *this->createVector(); Vector& s = *this->createVector(); const bool verbose = f_verbose.getValue(); unsigned iter=1; r = M*x; cgstep_beta(r,b,-1);//for (int i=0; i<n; i++) r[i] = b[i] - r[i]; if (this->preconditioners.size()>0 && usePrecond) { sofa::helper::AdvancedTimer::stepEnd("PCGLinearSolver::solve"); sofa::helper::AdvancedTimer::stepBegin("PCGLinearSolver::apply Precond"); preconditioners[0]->setSystemLHVector(d); preconditioners[0]->setSystemRHVector(r); preconditioners[0]->solveSystem(); sofa::helper::AdvancedTimer::stepEnd("PCGLinearSolver::apply Precond"); sofa::helper::AdvancedTimer::stepBegin("PCGLinearSolver::solve"); } else { d = r; } double deltaNew = r.dot(d); double delta0 = deltaNew; double eps = f_tolerance.getValue() * f_tolerance.getValue() * delta0; std::map < std::string, sofa::helper::vector<double> >& graph = * f_graph.beginEdit(); sofa::helper::vector<double>& graph_error = graph["Error"]; graph_error.clear(); while ((iter <= f_maxIter.getValue()) && (deltaNew > eps)) { if (verbose) printf("CG iteration %d: current L2 error vs initial error=%G\n", iter, sqrt(deltaNew/delta0)); graph_error.push_back(deltaNew); q = M * d; double dtq = d.dot(q); double alpha = deltaNew / dtq; cgstep_alpha(x,d,alpha);//for(int i=0; i<n; i++) x[i] += alpha * d[i]; if (iter % 50 == 0) // periodically compute the exact residual { r = M * x; cgstep_beta(r,b,-1);//for (int i=0; i<n; i++) r[i] = b[i] - r[i]; } else { cgstep_alpha(r,q,-alpha);//for (int i=0; i<n; i++) r[i] = r[i] - alpha * q[i]; } if (this->preconditioners.size()>0 && usePrecond) { sofa::helper::AdvancedTimer::stepEnd("PCGLinearSolver::solve"); sofa::helper::AdvancedTimer::stepBegin("PCGLinearSolver::apply Precond"); preconditioners[0]->setSystemLHVector(s); preconditioners[0]->setSystemRHVector(r); preconditioners[0]->solveSystem(); sofa::helper::AdvancedTimer::stepEnd("PCGLinearSolver::apply Precond"); sofa::helper::AdvancedTimer::stepBegin("PCGLinearSolver::solve"); } else { s = r; } double deltaOld = deltaNew; deltaNew = r.dot(s); double beta = deltaNew / deltaOld; cgstep_beta(d,s,beta);//for (int i=0; i<n; i++) d[i] = r[i] + beta * d[i]; iter++; } f_graph.endEdit(); this->deleteVector(&r); this->deleteVector(&q); this->deleteVector(&d); this->deleteVector(&s); sofa::helper::AdvancedTimer::stepEnd("PCGLinearSolver::solve"); } SOFA_DECL_CLASS(ShewchukPCGLinearSolver) int ShewchukPCGLinearSolverClass = core::RegisterObject("Linear system solver using the conjugate gradient iterative algorithm") .add< ShewchukPCGLinearSolver<GraphScatteredMatrix,GraphScatteredVector> >(true) ; } // namespace linearsolver } // namespace component } // namespace sofa <|endoftext|>
<commit_before>/* ofxTableGestures (formerly OF-TangibleFramework) Developed for Taller de Sistemes Interactius I Universitat Pompeu Fabra Copyright (c) 2010 Carles F. Julià <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef KEEPFEEDBACK_HPP_INCLUDED #define KEEPFEEDBACK_HPP_INCLUDED #include "InputGestureLongPush.hpp" #include "Graphic.hpp" class LongPushFeedback : public CanLongPush < Graphic > { float & lifetime; float & maxradius; public: class CircleTap : public Graphic { float born; float lifetime; float maxradius; DirectPoint p; public: CircleTap(const DirectPoint & dp, float r, float lt): born(ofGetElapsedTimef()), lifetime(lt), maxradius(r), p(dp){} void update() { float now = ofGetElapsedTimef(); if(now - born > lifetime) delete this; } void draw() { float now = ofGetElapsedTimef(); float alpha = ((now - born) / lifetime); float radius = alpha * maxradius ; int alpha255 = (int)((1.0f-alpha)*255); ofPushStyle(); ofNoFill(); ofSetLineWidth(4); ofSetColor(255,0,0,alpha255); ofEnableAlphaBlending(); ofCircle(p.getX(),p.getY(),radius); ofDisableAlphaBlending(); ofPopStyle(); } }; LongPushFeedback(): lifetime(ofxGlobalConfig::getRef("FEEDBACK:TAP:DURATION",1.0f)), maxradius(ofxGlobalConfig::getRef("FEEDBACK:TAP:MAXRADIUS",0.1f)) { // Register(a); } void LongPushTriger(float x, float y) { new CircleTap(DirectPoint(x,y),maxradius,lifetime); } }; #endif // KEEPFEEDBACK_HPP_INCLUDED <commit_msg>Bugfix: priority in tab/push feedback<commit_after>/* ofxTableGestures (formerly OF-TangibleFramework) Developed for Taller de Sistemes Interactius I Universitat Pompeu Fabra Copyright (c) 2010 Carles F. Julià <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef KEEPFEEDBACK_HPP_INCLUDED #define KEEPFEEDBACK_HPP_INCLUDED #include "InputGestureLongPush.hpp" #include "Graphic.hpp" class LongPushFeedback : public CanLongPush < Graphic > { float & lifetime; float & maxradius; public: class CircleTap : public NotificationGraphic { float born; float lifetime; float maxradius; DirectPoint p; public: CircleTap(const DirectPoint & dp, float r, float lt): born(ofGetElapsedTimef()), lifetime(lt), maxradius(r), p(dp){} void update() { float now = ofGetElapsedTimef(); if(now - born > lifetime) delete this; } void draw() { float now = ofGetElapsedTimef(); float alpha = ((now - born) / lifetime); float radius = alpha * maxradius ; int alpha255 = (int)((1.0f-alpha)*255); ofPushStyle(); ofNoFill(); ofSetLineWidth(4); ofSetColor(255,0,0,alpha255); ofEnableAlphaBlending(); ofCircle(p.getX(),p.getY(),radius); ofDisableAlphaBlending(); ofPopStyle(); } }; LongPushFeedback(): lifetime(ofxGlobalConfig::getRef("FEEDBACK:TAP:DURATION",1.0f)), maxradius(ofxGlobalConfig::getRef("FEEDBACK:TAP:MAXRADIUS",0.1f)) { // Register(a); } void LongPushTriger(float x, float y) { new CircleTap(DirectPoint(x,y),maxradius,lifetime); } }; #endif // KEEPFEEDBACK_HPP_INCLUDED <|endoftext|>
<commit_before>#include "IndividualEventStatistics.hpp" #include <iostream> #include <memory> #include <string> #include <utility> #include "json/json.h" #include "Event.hpp" #include "EventStatistics.hpp" namespace { // Return a string properly escaped for csv. If the input contains \r or \n, // the result will be incorrect. std::string csvEscape(std::string in) { if (in.find_first_of(",\"") == std::string::npos) { return in; } std::string out = "\""; for (const auto& c : in) { if (c == '"') { out += "\"\""; } else { out += c; } } out += "\""; return out; } } // namespace namespace warped { IndividualEventStatistics::IndividualEventStatistics(std::string filename, OutputType output_type) : EventStatistics(std::move(filename)), output_type_(output_type), entries_() {} void IndividualEventStatistics::record(const std::string& source, unsigned int send_time, Event* event) { entries_.emplace_back( source, event->receiverName(), send_time, event->timestamp(), event->size() + event->base_size() ); } std::ostream& IndividualEventStatistics::printStats(std::ostream& stream) const { if (output_type_ == OutputType::Json) { return printJson(stream); } return printCsv(stream); } std::ostream& IndividualEventStatistics::printJson(std::ostream& stream) const { Json::Value root {Json::ValueType::arrayValue}; root.resize(entries_.size()); for (unsigned int i = 0; i < entries_.size(); ++i) { root[i]["source"] = entries_[i].source; root[i]["dest"] = entries_[i].dest; root[i]["send_time"] = entries_[i].send_time; root[i]["receive_time"] = entries_[i].receive_time; root[i]["event_size"] = entries_[i].event_size; } return stream << root; } std::ostream& IndividualEventStatistics::printCsv(std::ostream& stream) const { stream << "Source,Destination,Send Time,Receive Time,Event Size\n"; for (const auto& entry : entries_) { stream << csvEscape(entry.source) << ',' << csvEscape(entry.dest) << ',' << std::to_string(entry.send_time) << ',' << std::to_string(entry.receive_time) << ',' << std::to_string(entry.event_size) << '\n'; } return stream; } } // namespace warped <commit_msg>added "#" comment character to the top line of the csv trace file so the desMetrics tools will skip it.<commit_after>#include "IndividualEventStatistics.hpp" #include <iostream> #include <memory> #include <string> #include <utility> #include "json/json.h" #include "Event.hpp" #include "EventStatistics.hpp" namespace { // Return a string properly escaped for csv. If the input contains \r or \n, // the result will be incorrect. std::string csvEscape(std::string in) { if (in.find_first_of(",\"") == std::string::npos) { return in; } std::string out = "\""; for (const auto& c : in) { if (c == '"') { out += "\"\""; } else { out += c; } } out += "\""; return out; } } // namespace namespace warped { IndividualEventStatistics::IndividualEventStatistics(std::string filename, OutputType output_type) : EventStatistics(std::move(filename)), output_type_(output_type), entries_() {} void IndividualEventStatistics::record(const std::string& source, unsigned int send_time, Event* event) { entries_.emplace_back( source, event->receiverName(), send_time, event->timestamp(), event->size() + event->base_size() ); } std::ostream& IndividualEventStatistics::printStats(std::ostream& stream) const { if (output_type_ == OutputType::Json) { return printJson(stream); } return printCsv(stream); } std::ostream& IndividualEventStatistics::printJson(std::ostream& stream) const { Json::Value root {Json::ValueType::arrayValue}; root.resize(entries_.size()); for (unsigned int i = 0; i < entries_.size(); ++i) { root[i]["source"] = entries_[i].source; root[i]["dest"] = entries_[i].dest; root[i]["send_time"] = entries_[i].send_time; root[i]["receive_time"] = entries_[i].receive_time; root[i]["event_size"] = entries_[i].event_size; } return stream << root; } std::ostream& IndividualEventStatistics::printCsv(std::ostream& stream) const { stream << "# Source,Destination,Send Time,Receive Time,Event Size\n"; for (const auto& entry : entries_) { stream << csvEscape(entry.source) << ',' << csvEscape(entry.dest) << ',' << std::to_string(entry.send_time) << ',' << std::to_string(entry.receive_time) << ',' << std::to_string(entry.event_size) << '\n'; } return stream; } } // namespace warped <|endoftext|>
<commit_before>/** * The MIT License (MIT) * * Copyright (c) 2014 wisol technologie GmbH * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * \author Michael Egli * \copyright wisol technologie GmbH * \date 18-Dec-2014 * * \file fsm_test.cpp * Test definitions for the state machine implementation. */ #define CATCH_CONFIG_MAIN #include "catch.hpp" #include <array> #include <vector> #include "../fsm.h" TEST_CASE("Test initial and final pseudo states") { enum class States { Initial, Final }; using F = FSM::Fsm<States, States::Initial>; F fsm; std::array<F::Trans, 1> transitions = {{ {States::Initial, States::Final, 'a', nullptr, nullptr}, }}; fsm.add_transitions(transitions.begin(), transitions.end()); SECTION("Test initial pseudo state") { REQUIRE(fsm.state() == States::Initial); REQUIRE(fsm.is_initial() == true); } SECTION("Test final state") { fsm.execute('a'); REQUIRE(fsm.state() == States::Final); REQUIRE(fsm.is_initial() == false); } } TEST_CASE("Test missing trigger") { enum class States { Initial, Final }; using F = FSM::Fsm<States, States::Initial>; F fsm; std::array<F::Trans, 1> transitions = {{ {States::Initial, States::Final, 'b', nullptr, nullptr}, }}; fsm.add_transitions(transitions.begin(), transitions.end()); REQUIRE(fsm.execute('a') == FSM::Fsm_NoMatchingTrigger); } TEST_CASE("Test guards") { SECTION("Test false guard") { enum class States { Initial, Final }; using F = FSM::Fsm<States, States::Initial>; F fsm; std::array<F::Trans, 1> transitions = {{ {States::Initial, States::Final, 'a', [] { return false; }, nullptr}, }}; fsm.add_transitions(transitions.begin(), transitions.end()); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); // ensure that the transition to final is not taken (because of the guard). REQUIRE(fsm.state() == States::Initial); } SECTION("Test true guard") { enum class States { Initial, Final }; using F = FSM::Fsm<States, States::Initial>; F fsm; std::array<F::Trans, 1> transitions = {{ {States::Initial, States::Final, 'a', [] { return true; }, nullptr}, }}; fsm.add_transitions(transitions.begin(), transitions.end()); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); // ensure that the transition to final is taken (because of the guard). REQUIRE(fsm.state() == States::Final); } SECTION("Test same action with different guards") { int count = 0; enum class States { Initial, Final }; using F = FSM::Fsm<States, States::Initial>; F fsm; std::array<F::Trans, 2> transitions = {{ {States::Initial, States::Final, 'a', [] { return false; }, [&count] { count++; }}, {States::Initial, States::Final, 'a', [] { return true; }, [&count] { count = 10; }}, }}; fsm.add_transitions(transitions.begin(), transitions.end()); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); // ensure that action2 was taken (because of the guard). REQUIRE(count == 10); } } TEST_CASE("Test Transitions") { SECTION("Test multiple matching transitions") { int count = 0; enum class States { Initial, A, Final }; using F = FSM::Fsm<States, States::Initial>; F fsm; std::array<F::Trans, 3> transitions = {{ {States::Initial, States::A, 'a', nullptr, [&count] { count++; }}, {States::A, States::A, 'a', nullptr, [&count] { count++; }}, {States::A, States::Final, 'a', nullptr, [&count] { count++; }}, }}; fsm.add_transitions(transitions.begin(), transitions.end()); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); // Ensure that only one action has executed. REQUIRE(count == 1); } } TEST_CASE("Test state machine reset") { int action_count = 0; enum class States { Initial, A, Final }; using F = FSM::Fsm<States, States::Initial>; F fsm; std::array<F::Trans, 2> transitions = {{ {States::Initial, States::A, 'a', nullptr, nullptr}, {States::A, States::Final, 'b', nullptr, nullptr}, }}; fsm.add_transitions(transitions.begin(), transitions.end()); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); REQUIRE(fsm.state() == States::A); fsm.reset(); REQUIRE(fsm.state() == States::Initial); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); REQUIRE(fsm.execute('b') == FSM::Fsm_Success); } TEST_CASE("Test debug function") { int action_count = 0; enum class States { Initial, A, Final }; using F = FSM::Fsm<States, States::Initial>; F fsm; std::array<F::Trans, 2> transitions = {{ {States::Initial, States::A, 'a', nullptr, nullptr}, {States::A, States::Final, 'b', nullptr, nullptr}, }}; fsm.add_transitions(transitions.begin(), transitions.end()); SECTION("Test enable debugging function.") { States dbg_from; States dbg_to; char dbg_tr = 0; fsm.add_debug_fn([&](States from, States to, char tr) { dbg_from = from; dbg_to = to; dbg_tr = tr; }); fsm.execute('a'); REQUIRE(dbg_from == States::Initial); REQUIRE(dbg_to == States::A); REQUIRE(dbg_tr == 'a'); } SECTION("Test disable debugging function.") { int dbg_from = 0; int dbg_to = 0; char dbg_tr = 0; fsm.reset(); fsm.add_debug_fn(nullptr); REQUIRE(dbg_from == 0); REQUIRE(dbg_to == 0); REQUIRE(dbg_tr == 0); } } TEST_CASE("Test single argument add_transitions function") { enum class States { Initial, A, Final }; using F = FSM::Fsm<States, States::Initial>; F fsm; SECTION("Test raw array") { F::Trans v[] = { {States::Initial, States::A, 'a', nullptr, nullptr}, {States::A, States::Final, 'b', nullptr, nullptr}, }; fsm.add_transitions(&v[0], &v[2]); fsm.execute('a'); fsm.execute('b'); REQUIRE(fsm.state() == States::Final); } SECTION("Test vector") { std::vector<F::Trans> v = { {States::Initial, States::A, 'a', nullptr, nullptr}, {States::A, States::Final, 'b', nullptr, nullptr}, }; fsm.add_transitions(v); fsm.execute('a'); fsm.execute('b'); REQUIRE(fsm.state() == States::Final); } SECTION("Test initializer list") { fsm.add_transitions({ {States::Initial, States::A, 'a', nullptr, nullptr}, {States::A, States::Final, 'b', nullptr, nullptr}, }); fsm.execute('a'); fsm.execute('b'); REQUIRE(fsm.state() == States::Final); } } TEST_CASE("Test int as type for states") { int INITIAL = 1; int A = 2; int FINAL = 3; using F = FSM::Fsm<int, 1>; F fsm; fsm.add_transitions({ {INITIAL, A, 'a', nullptr, nullptr}, {A, A, 'b', nullptr, nullptr}, {A, FINAL, 'c', nullptr, nullptr}, }); REQUIRE(fsm.state() == INITIAL); fsm.execute('a'); REQUIRE(fsm.state() == A); fsm.execute('b'); REQUIRE(fsm.state() == A); fsm.execute('c'); REQUIRE(fsm.state() == FINAL); } <commit_msg>Update tests to use initializer lists for adding transitions.<commit_after>/** * The MIT License (MIT) * * Copyright (c) 2014 wisol technologie GmbH * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * \author Michael Egli * \copyright wisol technologie GmbH * \date 18-Dec-2014 * * \file fsm_test.cpp * Test definitions for the state machine implementation. */ #define CATCH_CONFIG_MAIN #include "catch.hpp" #include <array> #include <vector> #include "../fsm.h" TEST_CASE("Test initial and final pseudo states") { enum class States { Initial, Final }; using F = FSM::Fsm<States, States::Initial>; F fsm; fsm.add_transitions({ {States::Initial, States::Final, 'a', nullptr, nullptr}, }); SECTION("Test initial pseudo state") { REQUIRE(fsm.state() == States::Initial); REQUIRE(fsm.is_initial() == true); } SECTION("Test final state") { fsm.execute('a'); REQUIRE(fsm.state() == States::Final); REQUIRE(fsm.is_initial() == false); } } TEST_CASE("Test missing trigger") { enum class States { Initial, Final }; using F = FSM::Fsm<States, States::Initial>; F fsm; fsm.add_transitions({ {States::Initial, States::Final, 'b', nullptr, nullptr}, }); REQUIRE(fsm.execute('a') == FSM::Fsm_NoMatchingTrigger); } TEST_CASE("Test guards") { SECTION("Test false guard") { enum class States { Initial, Final }; using F = FSM::Fsm<States, States::Initial>; F fsm; fsm.add_transitions({ {States::Initial, States::Final, 'a', [] { return false; }, nullptr}, }); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); // ensure that the transition to final is not taken (because of the guard). REQUIRE(fsm.state() == States::Initial); } SECTION("Test true guard") { enum class States { Initial, Final }; using F = FSM::Fsm<States, States::Initial>; F fsm; fsm.add_transitions({ {States::Initial, States::Final, 'a', [] { return true; }, nullptr}, }); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); // ensure that the transition to final is taken (because of the guard). REQUIRE(fsm.state() == States::Final); } SECTION("Test same action with different guards") { int count = 0; enum class States { Initial, Final }; using F = FSM::Fsm<States, States::Initial>; F fsm; fsm.add_transitions({ {States::Initial, States::Final, 'a', [] { return false; }, [&count] { count++; }}, {States::Initial, States::Final, 'a', [] { return true; }, [&count] { count = 10; }}, }); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); // ensure that action2 was taken (because of the guard). REQUIRE(count == 10); } } TEST_CASE("Test Transitions") { SECTION("Test multiple matching transitions") { int count = 0; enum class States { Initial, A, Final }; using F = FSM::Fsm<States, States::Initial>; F fsm; fsm.add_transitions({ {States::Initial, States::A, 'a', nullptr, [&count] { count++; }}, {States::A, States::A, 'a', nullptr, [&count] { count++; }}, {States::A, States::Final, 'a', nullptr, [&count] { count++; }}, }); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); // Ensure that only one action has executed. REQUIRE(count == 1); } } TEST_CASE("Test state machine reset") { int action_count = 0; enum class States { Initial, A, Final }; using F = FSM::Fsm<States, States::Initial>; F fsm; fsm.add_transitions({ {States::Initial, States::A, 'a', nullptr, nullptr}, {States::A, States::Final, 'b', nullptr, nullptr}, }); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); REQUIRE(fsm.state() == States::A); fsm.reset(); REQUIRE(fsm.state() == States::Initial); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); REQUIRE(fsm.execute('b') == FSM::Fsm_Success); } TEST_CASE("Test debug function") { int action_count = 0; enum class States { Initial, A, Final }; using F = FSM::Fsm<States, States::Initial>; F fsm; fsm.add_transitions({ {States::Initial, States::A, 'a', nullptr, nullptr}, {States::A, States::Final, 'b', nullptr, nullptr}, }); SECTION("Test enable debugging function.") { States dbg_from; States dbg_to; char dbg_tr = 0; fsm.add_debug_fn([&](States from, States to, char tr) { dbg_from = from; dbg_to = to; dbg_tr = tr; }); fsm.execute('a'); REQUIRE(dbg_from == States::Initial); REQUIRE(dbg_to == States::A); REQUIRE(dbg_tr == 'a'); } SECTION("Test disable debugging function.") { int dbg_from = 0; int dbg_to = 0; char dbg_tr = 0; fsm.reset(); fsm.add_debug_fn(nullptr); REQUIRE(dbg_from == 0); REQUIRE(dbg_to == 0); REQUIRE(dbg_tr == 0); } } TEST_CASE("Test single argument add_transitions function") { enum class States { Initial, A, Final }; using F = FSM::Fsm<States, States::Initial>; F fsm; SECTION("Test raw array") { F::Trans v[] = { {States::Initial, States::A, 'a', nullptr, nullptr}, {States::A, States::Final, 'b', nullptr, nullptr}, }; fsm.add_transitions(&v[0], &v[2]); fsm.execute('a'); fsm.execute('b'); REQUIRE(fsm.state() == States::Final); } SECTION("Test vector") { std::vector<F::Trans> v = { {States::Initial, States::A, 'a', nullptr, nullptr}, {States::A, States::Final, 'b', nullptr, nullptr}, }; fsm.add_transitions(v); fsm.execute('a'); fsm.execute('b'); REQUIRE(fsm.state() == States::Final); } SECTION("Test initializer list") { fsm.add_transitions({ {States::Initial, States::A, 'a', nullptr, nullptr}, {States::A, States::Final, 'b', nullptr, nullptr}, }); fsm.execute('a'); fsm.execute('b'); REQUIRE(fsm.state() == States::Final); } } TEST_CASE("Test int as type for states") { int INITIAL = 1; int A = 2; int FINAL = 3; using F = FSM::Fsm<int, 1>; F fsm; fsm.add_transitions({ {INITIAL, A, 'a', nullptr, nullptr}, {A, A, 'b', nullptr, nullptr}, {A, FINAL, 'c', nullptr, nullptr}, }); REQUIRE(fsm.state() == INITIAL); fsm.execute('a'); REQUIRE(fsm.state() == A); fsm.execute('b'); REQUIRE(fsm.state() == A); fsm.execute('c'); REQUIRE(fsm.state() == FINAL); } <|endoftext|>
<commit_before>#include <vector> using std::vector; #include <string> using std::string; #include <SofaTest/Sofa_test.h> using sofa::Sofa_test; #include<sofa/core/objectmodel/BaseObject.h> using sofa::core::objectmodel::BaseObject ; #include <SofaSimulationGraph/DAGSimulation.h> using sofa::simulation::Simulation ; using sofa::simulation::graph::DAGSimulation ; using sofa::simulation::Node ; #include <SofaSimulationCommon/SceneLoaderXML.h> using sofa::simulation::SceneLoaderXML ; using sofa::core::ExecParams ; #include <sofa/helper/BackTrace.h> using sofa::helper::BackTrace ; namespace cliplane_test { int initMessage(){ /// Install the backtrace so that we have more information in case of test segfault. BackTrace::autodump() ; return 0; } int messageInited = initMessage(); class TestClipPlane : public Sofa_test<> { public: void checkClipPlaneValidAttributes(); void checkClipPlaneAttributesValues(const std::string& dataname, const std::string& value); }; void TestClipPlane::checkClipPlaneValidAttributes() { EXPECT_MSG_NOEMIT(Warning, Error) ; std::stringstream scene ; scene << "<?xml version='1.0'?> \n" "<Node name='Root' gravity='0 -9.81 0' time='0' animate='0' > \n" " <Node name='Level 1'> \n" " <MechanicalObject/> \n" " <ClipPlane name='clipplane'/> \n" " </Node> \n" "</Node> \n" ; Node::SPtr root = SceneLoaderXML::loadFromMemory ("testscene", scene.str().c_str(), scene.str().size()) ; ASSERT_NE(root.get(), nullptr) ; root->init(ExecParams::defaultInstance()) ; BaseObject* clp = root->getTreeNode("Level 1")->getObject("clipplane") ; ASSERT_NE(clp, nullptr) ; /// List of the supported attributes the user expect to find /// This list needs to be updated if you add an attribute. vector<string> attrnames = {"position", "normal", "id", "active"}; for(auto& attrname : attrnames) EXPECT_NE( clp->findData(attrname), nullptr ) << "Missing attribute with name '" << attrname << "'." ; clearSceneGraph(); } void TestClipPlane::checkClipPlaneAttributesValues(const std::string& dataname, const std::string& value) { std::stringstream scene ; scene << "<?xml version='1.0'?> \n" "<Node name='Root' gravity='0 -9.81 0' time='0' animate='0' > \n" " <Node name='Level 1'> \n" " <MechanicalObject/> \n" " <ClipPlane name='clipplane'" << dataname << "='" << value << "'/> \n" " </Node> \n" "</Node> \n" ; Node::SPtr root = SceneLoaderXML::loadFromMemory ("testscene", scene.str().c_str(), scene.str().size()) ; ASSERT_NE(root.get(), nullptr) ; root->init(ExecParams::defaultInstance()) ; BaseObject* clp = root->getTreeNode("Level 1")->getObject("clipplane") ; ASSERT_NE(clp, nullptr) ; clearSceneGraph(); } TEST_F(TestClipPlane, checkClipPlaneIdInValidValues) { EXPECT_MSG_EMIT(Error) ; checkClipPlaneAttributesValues("id", "-1"); } TEST_F(TestClipPlane, checkClipPlaneNormalInvalidNormalValue) { EXPECT_MSG_EMIT(Warning) ; checkClipPlaneAttributesValues("normal", "1 0"); } } // cliplane_test <commit_msg>[SofaOpenglVisual] fix test, this is an error to fill a vec3 with 2 values<commit_after>#include <vector> using std::vector; #include <string> using std::string; #include <SofaTest/Sofa_test.h> using sofa::Sofa_test; #include<sofa/core/objectmodel/BaseObject.h> using sofa::core::objectmodel::BaseObject ; #include <SofaSimulationGraph/DAGSimulation.h> using sofa::simulation::Simulation ; using sofa::simulation::graph::DAGSimulation ; using sofa::simulation::Node ; #include <SofaSimulationCommon/SceneLoaderXML.h> using sofa::simulation::SceneLoaderXML ; using sofa::core::ExecParams ; #include <sofa/helper/BackTrace.h> using sofa::helper::BackTrace ; namespace cliplane_test { int initMessage(){ /// Install the backtrace so that we have more information in case of test segfault. BackTrace::autodump() ; return 0; } int messageInited = initMessage(); class TestClipPlane : public Sofa_test<> { public: void checkClipPlaneValidAttributes(); void checkClipPlaneAttributesValues(const std::string& dataname, const std::string& value); }; void TestClipPlane::checkClipPlaneValidAttributes() { EXPECT_MSG_NOEMIT(Warning, Error) ; std::stringstream scene ; scene << "<?xml version='1.0'?> \n" "<Node name='Root' gravity='0 -9.81 0' time='0' animate='0' > \n" " <Node name='Level 1'> \n" " <MechanicalObject/> \n" " <ClipPlane name='clipplane'/> \n" " </Node> \n" "</Node> \n" ; Node::SPtr root = SceneLoaderXML::loadFromMemory ("testscene", scene.str().c_str(), scene.str().size()) ; ASSERT_NE(root.get(), nullptr) ; root->init(ExecParams::defaultInstance()) ; BaseObject* clp = root->getTreeNode("Level 1")->getObject("clipplane") ; ASSERT_NE(clp, nullptr) ; /// List of the supported attributes the user expect to find /// This list needs to be updated if you add an attribute. vector<string> attrnames = {"position", "normal", "id", "active"}; for(auto& attrname : attrnames) EXPECT_NE( clp->findData(attrname), nullptr ) << "Missing attribute with name '" << attrname << "'." ; clearSceneGraph(); } void TestClipPlane::checkClipPlaneAttributesValues(const std::string& dataname, const std::string& value) { std::stringstream scene ; scene << "<?xml version='1.0'?> \n" "<Node name='Root' gravity='0 -9.81 0' time='0' animate='0' > \n" " <Node name='Level 1'> \n" " <MechanicalObject/> \n" " <ClipPlane name='clipplane'" << dataname << "='" << value << "'/> \n" " </Node> \n" "</Node> \n" ; Node::SPtr root = SceneLoaderXML::loadFromMemory ("testscene", scene.str().c_str(), scene.str().size()) ; ASSERT_NE(root.get(), nullptr) ; root->init(ExecParams::defaultInstance()) ; BaseObject* clp = root->getTreeNode("Level 1")->getObject("clipplane") ; ASSERT_NE(clp, nullptr) ; clearSceneGraph(); } TEST_F(TestClipPlane, checkClipPlaneIdInValidValues) { EXPECT_MSG_EMIT(Error) ; checkClipPlaneAttributesValues("id", "-1"); } TEST_F(TestClipPlane, checkClipPlaneNormalInvalidNormalValue) { EXPECT_MSG_EMIT(Error) ; checkClipPlaneAttributesValues("normal", "1 0"); } } // cliplane_test <|endoftext|>
<commit_before>//===- ProfileInfoLoad.cpp - Load profile information from disk -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // The ProfileInfoLoader class is used to load and represent profiling // information read in from the dump file. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/ProfileInfoLoader.h" #include "llvm/Analysis/ProfileInfoTypes.h" #include "llvm/Module.h" #include "llvm/InstrTypes.h" #include "llvm/Support/raw_ostream.h" #include <cstdio> #include <cstdlib> #include <map> using namespace llvm; // ByteSwap - Byteswap 'Var' if 'Really' is true. // static inline unsigned ByteSwap(unsigned Var, bool Really) { if (!Really) return Var; return ((Var & (255<< 0)) << 24) | ((Var & (255<< 8)) << 8) | ((Var & (255<<16)) >> 8) | ((Var & (255<<24)) >> 24); } static void ReadProfilingBlock(const char *ToolName, FILE *F, bool ShouldByteSwap, std::vector<unsigned> &Data) { // Read the number of entries... unsigned NumEntries; if (fread(&NumEntries, sizeof(unsigned), 1, F) != 1) { errs() << ToolName << ": data packet truncated!\n"; perror(0); exit(1); } NumEntries = ByteSwap(NumEntries, ShouldByteSwap); // Read the counts... std::vector<unsigned> TempSpace(NumEntries); // Read in the block of data... if (fread(&TempSpace[0], sizeof(unsigned)*NumEntries, 1, F) != 1) { errs() << ToolName << ": data packet truncated!\n"; perror(0); exit(1); } // Make sure we have enough space... The space is initialised to -1 to // facitiltate the loading of missing values for OptimalEdgeProfiling. if (Data.size() < NumEntries) Data.resize(NumEntries, ~0U); // Accumulate the data we just read into the data. if (!ShouldByteSwap) { for (unsigned i = 0; i != NumEntries; ++i) { unsigned data = TempSpace[i]; if (data != (unsigned)-1) { // only load data if its not MissingVal if (Data[i] == (unsigned)-1) { Data[i] = data; // if data is still initialised } else { Data[i] += data; } } } } else { for (unsigned i = 0; i != NumEntries; ++i) { unsigned data = ByteSwap(TempSpace[i], true); if (data != (unsigned)-1) { // only load data if its not MissingVal if (Data[i] == (unsigned)-1) { Data[i] = data; } else { Data[i] += data; } } } } } // ProfileInfoLoader ctor - Read the specified profiling data file, exiting the // program if the file is invalid or broken. // ProfileInfoLoader::ProfileInfoLoader(const char *ToolName, const std::string &Filename, Module &TheModule) : Filename(Filename), M(TheModule), Warned(false) { FILE *F = fopen(Filename.c_str(), "rb"); if (F == 0) { errs() << ToolName << ": Error opening '" << Filename << "': "; perror(0); exit(1); } // Keep reading packets until we run out of them. unsigned PacketType; while (fread(&PacketType, sizeof(unsigned), 1, F) == 1) { // If the low eight bits of the packet are zero, we must be dealing with an // endianness mismatch. Byteswap all words read from the profiling // information. bool ShouldByteSwap = (char)PacketType == 0; PacketType = ByteSwap(PacketType, ShouldByteSwap); switch (PacketType) { case ArgumentInfo: { unsigned ArgLength; if (fread(&ArgLength, sizeof(unsigned), 1, F) != 1) { errs() << ToolName << ": arguments packet truncated!\n"; perror(0); exit(1); } ArgLength = ByteSwap(ArgLength, ShouldByteSwap); // Read in the arguments... std::vector<char> Chars(ArgLength+4); if (ArgLength) if (fread(&Chars[0], (ArgLength+3) & ~3, 1, F) != 1) { errs() << ToolName << ": arguments packet truncated!\n"; perror(0); exit(1); } CommandLines.push_back(std::string(&Chars[0], &Chars[ArgLength])); break; } case FunctionInfo: ReadProfilingBlock(ToolName, F, ShouldByteSwap, FunctionCounts); break; case BlockInfo: ReadProfilingBlock(ToolName, F, ShouldByteSwap, BlockCounts); break; case EdgeInfo: ReadProfilingBlock(ToolName, F, ShouldByteSwap, EdgeCounts); break; case OptEdgeInfo: ReadProfilingBlock(ToolName, F, ShouldByteSwap, OptimalEdgeCounts); break; case BBTraceInfo: ReadProfilingBlock(ToolName, F, ShouldByteSwap, BBTrace); break; default: errs() << ToolName << ": Unknown packet type #" << PacketType << "!\n"; exit(1); } } fclose(F); } <commit_msg>Code Cleanup. (See http://lists.cs.uiuc.edu/pipermail/llvm-commits/Week-of-Mon-20090831/086139.html)<commit_after>//===- ProfileInfoLoad.cpp - Load profile information from disk -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // The ProfileInfoLoader class is used to load and represent profiling // information read in from the dump file. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/ProfileInfoLoader.h" #include "llvm/Analysis/ProfileInfoTypes.h" #include "llvm/Module.h" #include "llvm/InstrTypes.h" #include "llvm/Support/raw_ostream.h" #include <cstdio> #include <cstdlib> #include <map> using namespace llvm; // ByteSwap - Byteswap 'Var' if 'Really' is true. // static inline unsigned ByteSwap(unsigned Var, bool Really) { if (!Really) return Var; return ((Var & (255<< 0)) << 24) | ((Var & (255<< 8)) << 8) | ((Var & (255<<16)) >> 8) | ((Var & (255<<24)) >> 24); } static const unsigned AddCounts(unsigned A, unsigned B) { // If either value is undefined, use the other. if (A == ~0U) return B; if (B == ~0U) return A; return A + B; } static void ReadProfilingBlock(const char *ToolName, FILE *F, bool ShouldByteSwap, std::vector<unsigned> &Data) { // Read the number of entries... unsigned NumEntries; if (fread(&NumEntries, sizeof(unsigned), 1, F) != 1) { errs() << ToolName << ": data packet truncated!\n"; perror(0); exit(1); } NumEntries = ByteSwap(NumEntries, ShouldByteSwap); // Read the counts... std::vector<unsigned> TempSpace(NumEntries); // Read in the block of data... if (fread(&TempSpace[0], sizeof(unsigned)*NumEntries, 1, F) != 1) { errs() << ToolName << ": data packet truncated!\n"; perror(0); exit(1); } // Make sure we have enough space... The space is initialised to -1 to // facitiltate the loading of missing values for OptimalEdgeProfiling. if (Data.size() < NumEntries) Data.resize(NumEntries, ~0U); // Accumulate the data we just read into the data. if (!ShouldByteSwap) { for (unsigned i = 0; i != NumEntries; ++i) { Data[i] = AddCounts(TempSpace[i], Data[i]); } } else { for (unsigned i = 0; i != NumEntries; ++i) { Data[i] = AddCounts(ByteSwap(TempSpace[i], true), Data[i]); } } } // ProfileInfoLoader ctor - Read the specified profiling data file, exiting the // program if the file is invalid or broken. // ProfileInfoLoader::ProfileInfoLoader(const char *ToolName, const std::string &Filename, Module &TheModule) : Filename(Filename), M(TheModule), Warned(false) { FILE *F = fopen(Filename.c_str(), "rb"); if (F == 0) { errs() << ToolName << ": Error opening '" << Filename << "': "; perror(0); exit(1); } // Keep reading packets until we run out of them. unsigned PacketType; while (fread(&PacketType, sizeof(unsigned), 1, F) == 1) { // If the low eight bits of the packet are zero, we must be dealing with an // endianness mismatch. Byteswap all words read from the profiling // information. bool ShouldByteSwap = (char)PacketType == 0; PacketType = ByteSwap(PacketType, ShouldByteSwap); switch (PacketType) { case ArgumentInfo: { unsigned ArgLength; if (fread(&ArgLength, sizeof(unsigned), 1, F) != 1) { errs() << ToolName << ": arguments packet truncated!\n"; perror(0); exit(1); } ArgLength = ByteSwap(ArgLength, ShouldByteSwap); // Read in the arguments... std::vector<char> Chars(ArgLength+4); if (ArgLength) if (fread(&Chars[0], (ArgLength+3) & ~3, 1, F) != 1) { errs() << ToolName << ": arguments packet truncated!\n"; perror(0); exit(1); } CommandLines.push_back(std::string(&Chars[0], &Chars[ArgLength])); break; } case FunctionInfo: ReadProfilingBlock(ToolName, F, ShouldByteSwap, FunctionCounts); break; case BlockInfo: ReadProfilingBlock(ToolName, F, ShouldByteSwap, BlockCounts); break; case EdgeInfo: ReadProfilingBlock(ToolName, F, ShouldByteSwap, EdgeCounts); break; case OptEdgeInfo: ReadProfilingBlock(ToolName, F, ShouldByteSwap, OptimalEdgeCounts); break; case BBTraceInfo: ReadProfilingBlock(ToolName, F, ShouldByteSwap, BBTrace); break; default: errs() << ToolName << ": Unknown packet type #" << PacketType << "!\n"; exit(1); } } fclose(F); } <|endoftext|>
<commit_before>#include "logger.h" #include "text/table.h" #include "task_mem_csv.h" using namespace nano; static void scale(const string_t& task_name, tensor3ds_t& samples) { const auto dims = samples.begin()->size(); vector_t maximums(dims); for (const auto& sample : samples) { maximums.array() = maximums.array().max(sample.array().abs()); } const vector_t scale = 1 / maximums.array(); for (auto& sample : samples) { sample.array() *= scale.array(); } log_info() << task_name << ": scaling using [" << maximums.transpose() << "]"; } static bool load_csv(const string_t& path, const string_t& task_name, const size_t expected_samples, const size_t expected_features, table_t& table) { const auto csv_delim = ","; const auto csv_header = false; log_info() << task_name << ": loading file <" << path << "> ..."; if (!table.load(path, csv_delim, csv_header)) { log_error() << task_name << ": failed to load file <" << path << ">!"; return false; } if (table.rows() != expected_samples) { log_error() << task_name << ": invalid number of samples!"; return false; } if (table.cols() != expected_features + 1) { log_error() << task_name << ": invalid number of columns!"; return false; } return true; } bool mem_csv_task_t::load_classification(const string_t& path, const string_t& task_name, const size_t expected_samples, const strings_t& labels, const size_t label_col) { const auto expected_features = static_cast<size_t>(nano::size(idims())); // load CSV table_t table; for (size_t col = 0, f = 0; col < expected_features + 1; ++ col) { table.header() << (col == label_col ? "class" : ("f" + to_string(++ f))); } if (!load_csv(path, task_name, expected_samples, expected_features, table)) { return false; } // load samples tensor3ds_t samples; std::vector<tensor_size_t> class_indices; for (size_t i = 0; i < table.rows(); ++ i) { const auto& row = table.row(i); const auto cc = row.cell(label_col).m_data; const auto itc = std::find(labels.begin(),labels.end(), cc); if (itc == labels.end()) { log_error() << task_name << ": invalid class <" << cc << ">!"; return false; } const auto make_sample = [this, &row = row, label_col = label_col] () { tensor3d_t sample(idims()); size_t col = 0; for (auto k = 0; k < sample.size(); ++ k, ++ col) { if (col == label_col) { ++ col; } sample(k, 0, 0) = from_string<scalar_t>(row.cell(col).m_data); } return sample; }; samples.push_back(make_sample()); class_indices.push_back(itc - labels.begin()); } // scale inputs to improve numerical robustness scale(task_name, samples); // setup task for (size_t i = 0; i < samples.size(); ++ i) { const auto hash = i; const auto fold = make_fold(0); const auto target = class_target(class_indices[i], nano::size(odims())); add_chunk(samples[i], hash); add_sample(fold, i, target, labels[static_cast<size_t>(class_indices[i])]); } // OK log_info() << task_name << ": loaded " << expected_samples << " samples."; return true; } <commit_msg>fix lambda capture<commit_after>#include "logger.h" #include "text/table.h" #include "task_mem_csv.h" using namespace nano; static void scale(const string_t& task_name, tensor3ds_t& samples) { const auto dims = samples.begin()->size(); vector_t maximums(dims); for (const auto& sample : samples) { maximums.array() = maximums.array().max(sample.array().abs()); } const vector_t scale = 1 / maximums.array(); for (auto& sample : samples) { sample.array() *= scale.array(); } log_info() << task_name << ": scaling using [" << maximums.transpose() << "]"; } static bool load_csv(const string_t& path, const string_t& task_name, const size_t expected_samples, const size_t expected_features, table_t& table) { const auto csv_delim = ","; const auto csv_header = false; log_info() << task_name << ": loading file <" << path << "> ..."; if (!table.load(path, csv_delim, csv_header)) { log_error() << task_name << ": failed to load file <" << path << ">!"; return false; } if (table.rows() != expected_samples) { log_error() << task_name << ": invalid number of samples!"; return false; } if (table.cols() != expected_features + 1) { log_error() << task_name << ": invalid number of columns!"; return false; } return true; } bool mem_csv_task_t::load_classification(const string_t& path, const string_t& task_name, const size_t expected_samples, const strings_t& labels, const size_t label_col) { const auto expected_features = static_cast<size_t>(nano::size(idims())); // load CSV table_t table; for (size_t col = 0, f = 0; col < expected_features + 1; ++ col) { table.header() << (col == label_col ? "class" : ("f" + to_string(++ f))); } if (!load_csv(path, task_name, expected_samples, expected_features, table)) { return false; } // load samples tensor3ds_t samples; std::vector<tensor_size_t> class_indices; for (size_t i = 0; i < table.rows(); ++ i) { const auto& row = table.row(i); const auto cc = row.cell(label_col).m_data; const auto itc = std::find(labels.begin(),labels.end(), cc); if (itc == labels.end()) { log_error() << task_name << ": invalid class <" << cc << ">!"; return false; } const auto make_sample = [&row, this, label_col] () { tensor3d_t sample(idims()); size_t col = 0; for (auto k = 0; k < sample.size(); ++ k, ++ col) { if (col == label_col) { ++ col; } sample(k, 0, 0) = from_string<scalar_t>(row.cell(col).m_data); } return sample; }; samples.push_back(make_sample()); class_indices.push_back(itc - labels.begin()); } // scale inputs to improve numerical robustness scale(task_name, samples); // setup task for (size_t i = 0; i < samples.size(); ++ i) { const auto hash = i; const auto fold = make_fold(0); const auto target = class_target(class_indices[i], nano::size(odims())); add_chunk(samples[i], hash); add_sample(fold, i, target, labels[static_cast<size_t>(class_indices[i])]); } // OK log_info() << task_name << ": loaded " << expected_samples << " samples."; return true; } <|endoftext|>
<commit_before>//===-- RegisterScavenging.cpp - Machine register scavenging --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the machine register scavenger. It can provide // information, such as unused registers, at any point in a machine basic block. // It also provides a mechanism to make registers available by evicting them to // spill slots. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "reg-scavenging" #include "llvm/CodeGen/RegisterScavenging.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/STLExtras.h" using namespace llvm; /// setUsed - Set the register and its sub-registers as being used. void RegScavenger::setUsed(unsigned Reg) { RegsAvailable.reset(Reg); for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) RegsAvailable.reset(*SubRegs); } bool RegScavenger::isAliasUsed(unsigned Reg) const { for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) if (isUsed(*AI, *AI == Reg)) return true; return false; } void RegScavenger::initRegState() { ScavengedReg = 0; ScavengedRC = NULL; ScavengeRestore = NULL; // All registers started out unused. RegsAvailable.set(); if (!MBB) return; // Live-in registers are in use. for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(), E = MBB->livein_end(); I != E; ++I) setUsed(*I); // Pristine CSRs are also unavailable. BitVector PR = MBB->getParent()->getFrameInfo()->getPristineRegs(MBB); for (int I = PR.find_first(); I>0; I = PR.find_next(I)) setUsed(I); } void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) { MachineFunction &MF = *mbb->getParent(); const TargetMachine &TM = MF.getTarget(); TII = TM.getInstrInfo(); TRI = TM.getRegisterInfo(); MRI = &MF.getRegInfo(); assert((NumPhysRegs == 0 || NumPhysRegs == TRI->getNumRegs()) && "Target changed?"); // It is not possible to use the register scavenger after late optimization // passes that don't preserve accurate liveness information. assert(MRI->tracksLiveness() && "Cannot use register scavenger with inaccurate liveness"); // Self-initialize. if (!MBB) { NumPhysRegs = TRI->getNumRegs(); RegsAvailable.resize(NumPhysRegs); KillRegs.resize(NumPhysRegs); DefRegs.resize(NumPhysRegs); // Create callee-saved registers bitvector. CalleeSavedRegs.resize(NumPhysRegs); const uint16_t *CSRegs = TRI->getCalleeSavedRegs(&MF); if (CSRegs != NULL) for (unsigned i = 0; CSRegs[i]; ++i) CalleeSavedRegs.set(CSRegs[i]); } MBB = mbb; initRegState(); Tracking = false; } void RegScavenger::addRegWithSubRegs(BitVector &BV, unsigned Reg) { BV.set(Reg); for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) BV.set(*SubRegs); } void RegScavenger::forward() { // Move ptr forward. if (!Tracking) { MBBI = MBB->begin(); Tracking = true; } else { assert(MBBI != MBB->end() && "Already past the end of the basic block!"); MBBI = llvm::next(MBBI); } assert(MBBI != MBB->end() && "Already at the end of the basic block!"); MachineInstr *MI = MBBI; if (MI == ScavengeRestore) { ScavengedReg = 0; ScavengedRC = NULL; ScavengeRestore = NULL; } if (MI->isDebugValue()) return; // Find out which registers are early clobbered, killed, defined, and marked // def-dead in this instruction. // FIXME: The scavenger is not predication aware. If the instruction is // predicated, conservatively assume "kill" markers do not actually kill the // register. Similarly ignores "dead" markers. bool isPred = TII->isPredicated(MI); KillRegs.reset(); DefRegs.reset(); for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { const MachineOperand &MO = MI->getOperand(i); if (MO.isRegMask()) (isPred ? DefRegs : KillRegs).setBitsNotInMask(MO.getRegMask()); if (!MO.isReg()) continue; unsigned Reg = MO.getReg(); if (!Reg || isReserved(Reg)) continue; if (MO.isUse()) { // Ignore undef uses. if (MO.isUndef()) continue; if (!isPred && MO.isKill()) addRegWithSubRegs(KillRegs, Reg); } else { assert(MO.isDef()); if (!isPred && MO.isDead()) addRegWithSubRegs(KillRegs, Reg); else addRegWithSubRegs(DefRegs, Reg); } } // Verify uses and defs. #ifndef NDEBUG for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { const MachineOperand &MO = MI->getOperand(i); if (!MO.isReg()) continue; unsigned Reg = MO.getReg(); if (!Reg || isReserved(Reg)) continue; if (MO.isUse()) { if (MO.isUndef()) continue; if (!isUsed(Reg)) { // Check if it's partial live: e.g. // D0 = insert_subreg D0<undef>, S0 // ... D0 // The problem is the insert_subreg could be eliminated. The use of // D0 is using a partially undef value. This is not *incorrect* since // S1 is can be freely clobbered. // Ideally we would like a way to model this, but leaving the // insert_subreg around causes both correctness and performance issues. bool SubUsed = false; for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) if (isUsed(*SubRegs)) { SubUsed = true; break; } if (!SubUsed) { MBB->getParent()->verify(NULL, "In Register Scavenger"); llvm_unreachable("Using an undefined register!"); } (void)SubUsed; } } else { assert(MO.isDef()); #if 0 // FIXME: Enable this once we've figured out how to correctly transfer // implicit kills during codegen passes like the coalescer. assert((KillRegs.test(Reg) || isUnused(Reg) || isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) && "Re-defining a live register!"); #endif } } #endif // NDEBUG // Commit the changes. setUnused(KillRegs); setUsed(DefRegs); } void RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) { used = RegsAvailable; used.flip(); if (includeReserved) used |= MRI->getReservedRegs(); else used.reset(MRI->getReservedRegs()); } unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const { for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I != E; ++I) if (!isAliasUsed(*I)) { DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(*I) << "\n"); return *I; } return 0; } /// getRegsAvailable - Return all available registers in the register class /// in Mask. BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) { BitVector Mask(TRI->getNumRegs()); for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I != E; ++I) if (!isAliasUsed(*I)) Mask.set(*I); return Mask; } /// findSurvivorReg - Return the candidate register that is unused for the /// longest after StargMII. UseMI is set to the instruction where the search /// stopped. /// /// No more than InstrLimit instructions are inspected. /// unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI, BitVector &Candidates, unsigned InstrLimit, MachineBasicBlock::iterator &UseMI) { int Survivor = Candidates.find_first(); assert(Survivor > 0 && "No candidates for scavenging"); MachineBasicBlock::iterator ME = MBB->getFirstTerminator(); assert(StartMI != ME && "MI already at terminator"); MachineBasicBlock::iterator RestorePointMI = StartMI; MachineBasicBlock::iterator MI = StartMI; bool inVirtLiveRange = false; for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) { if (MI->isDebugValue()) { ++InstrLimit; // Don't count debug instructions continue; } bool isVirtKillInsn = false; bool isVirtDefInsn = false; // Remove any candidates touched by instruction. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { const MachineOperand &MO = MI->getOperand(i); if (MO.isRegMask()) Candidates.clearBitsNotInMask(MO.getRegMask()); if (!MO.isReg() || MO.isUndef() || !MO.getReg()) continue; if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) { if (MO.isDef()) isVirtDefInsn = true; else if (MO.isKill()) isVirtKillInsn = true; continue; } for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI) Candidates.reset(*AI); } // If we're not in a virtual reg's live range, this is a valid // restore point. if (!inVirtLiveRange) RestorePointMI = MI; // Update whether we're in the live range of a virtual register if (isVirtKillInsn) inVirtLiveRange = false; if (isVirtDefInsn) inVirtLiveRange = true; // Was our survivor untouched by this instruction? if (Candidates.test(Survivor)) continue; // All candidates gone? if (Candidates.none()) break; Survivor = Candidates.find_first(); } // If we ran off the end, that's where we want to restore. if (MI == ME) RestorePointMI = ME; assert (RestorePointMI != StartMI && "No available scavenger restore location!"); // We ran out of candidates, so stop the search. UseMI = RestorePointMI; return Survivor; } unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC, MachineBasicBlock::iterator I, int SPAdj) { // Consider all allocatable registers in the register class initially BitVector Candidates = TRI->getAllocatableSet(*I->getParent()->getParent(), RC); // Exclude all the registers being used by the instruction. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { MachineOperand &MO = I->getOperand(i); if (MO.isReg() && MO.getReg() != 0 && !TargetRegisterInfo::isVirtualRegister(MO.getReg())) Candidates.reset(MO.getReg()); } // Try to find a register that's unused if there is one, as then we won't // have to spill. Search explicitly rather than masking out based on // RegsAvailable, as RegsAvailable does not take aliases into account. // That's what getRegsAvailable() is for. BitVector Available = getRegsAvailable(RC); Available &= Candidates; if (Available.any()) Candidates = Available; // Find the register whose use is furthest away. MachineBasicBlock::iterator UseMI; unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI); // If we found an unused register there is no reason to spill it. if (!isAliasUsed(SReg)) { DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n"); return SReg; } assert(ScavengedReg == 0 && "Scavenger slot is live, unable to scavenge another register!"); // Avoid infinite regress ScavengedReg = SReg; // If the target knows how to save/restore the register, let it do so; // otherwise, use the emergency stack spill slot. if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) { // Spill the scavenged register before I. assert(ScavengingFrameIndex >= 0 && "Cannot scavenge register without an emergency spill slot!"); TII->storeRegToStackSlot(*MBB, I, SReg, true, ScavengingFrameIndex, RC,TRI); MachineBasicBlock::iterator II = prior(I); TRI->eliminateFrameIndex(II, SPAdj, this); // Restore the scavenged register before its use (or first terminator). TII->loadRegFromStackSlot(*MBB, UseMI, SReg, ScavengingFrameIndex, RC, TRI); II = prior(UseMI); TRI->eliminateFrameIndex(II, SPAdj, this); } ScavengeRestore = prior(UseMI); // Doing this here leads to infinite regress. // ScavengedReg = SReg; ScavengedRC = RC; DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) << "\n"); return SReg; } <commit_msg>Remove unneeded #includes.<commit_after>//===-- RegisterScavenging.cpp - Machine register scavenging --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the machine register scavenger. It can provide // information, such as unused registers, at any point in a machine basic block. // It also provides a mechanism to make registers available by evicting them to // spill slots. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "reg-scavenging" #include "llvm/CodeGen/RegisterScavenging.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" using namespace llvm; /// setUsed - Set the register and its sub-registers as being used. void RegScavenger::setUsed(unsigned Reg) { RegsAvailable.reset(Reg); for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) RegsAvailable.reset(*SubRegs); } bool RegScavenger::isAliasUsed(unsigned Reg) const { for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) if (isUsed(*AI, *AI == Reg)) return true; return false; } void RegScavenger::initRegState() { ScavengedReg = 0; ScavengedRC = NULL; ScavengeRestore = NULL; // All registers started out unused. RegsAvailable.set(); if (!MBB) return; // Live-in registers are in use. for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(), E = MBB->livein_end(); I != E; ++I) setUsed(*I); // Pristine CSRs are also unavailable. BitVector PR = MBB->getParent()->getFrameInfo()->getPristineRegs(MBB); for (int I = PR.find_first(); I>0; I = PR.find_next(I)) setUsed(I); } void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) { MachineFunction &MF = *mbb->getParent(); const TargetMachine &TM = MF.getTarget(); TII = TM.getInstrInfo(); TRI = TM.getRegisterInfo(); MRI = &MF.getRegInfo(); assert((NumPhysRegs == 0 || NumPhysRegs == TRI->getNumRegs()) && "Target changed?"); // It is not possible to use the register scavenger after late optimization // passes that don't preserve accurate liveness information. assert(MRI->tracksLiveness() && "Cannot use register scavenger with inaccurate liveness"); // Self-initialize. if (!MBB) { NumPhysRegs = TRI->getNumRegs(); RegsAvailable.resize(NumPhysRegs); KillRegs.resize(NumPhysRegs); DefRegs.resize(NumPhysRegs); // Create callee-saved registers bitvector. CalleeSavedRegs.resize(NumPhysRegs); const uint16_t *CSRegs = TRI->getCalleeSavedRegs(&MF); if (CSRegs != NULL) for (unsigned i = 0; CSRegs[i]; ++i) CalleeSavedRegs.set(CSRegs[i]); } MBB = mbb; initRegState(); Tracking = false; } void RegScavenger::addRegWithSubRegs(BitVector &BV, unsigned Reg) { BV.set(Reg); for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) BV.set(*SubRegs); } void RegScavenger::forward() { // Move ptr forward. if (!Tracking) { MBBI = MBB->begin(); Tracking = true; } else { assert(MBBI != MBB->end() && "Already past the end of the basic block!"); MBBI = llvm::next(MBBI); } assert(MBBI != MBB->end() && "Already at the end of the basic block!"); MachineInstr *MI = MBBI; if (MI == ScavengeRestore) { ScavengedReg = 0; ScavengedRC = NULL; ScavengeRestore = NULL; } if (MI->isDebugValue()) return; // Find out which registers are early clobbered, killed, defined, and marked // def-dead in this instruction. // FIXME: The scavenger is not predication aware. If the instruction is // predicated, conservatively assume "kill" markers do not actually kill the // register. Similarly ignores "dead" markers. bool isPred = TII->isPredicated(MI); KillRegs.reset(); DefRegs.reset(); for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { const MachineOperand &MO = MI->getOperand(i); if (MO.isRegMask()) (isPred ? DefRegs : KillRegs).setBitsNotInMask(MO.getRegMask()); if (!MO.isReg()) continue; unsigned Reg = MO.getReg(); if (!Reg || isReserved(Reg)) continue; if (MO.isUse()) { // Ignore undef uses. if (MO.isUndef()) continue; if (!isPred && MO.isKill()) addRegWithSubRegs(KillRegs, Reg); } else { assert(MO.isDef()); if (!isPred && MO.isDead()) addRegWithSubRegs(KillRegs, Reg); else addRegWithSubRegs(DefRegs, Reg); } } // Verify uses and defs. #ifndef NDEBUG for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { const MachineOperand &MO = MI->getOperand(i); if (!MO.isReg()) continue; unsigned Reg = MO.getReg(); if (!Reg || isReserved(Reg)) continue; if (MO.isUse()) { if (MO.isUndef()) continue; if (!isUsed(Reg)) { // Check if it's partial live: e.g. // D0 = insert_subreg D0<undef>, S0 // ... D0 // The problem is the insert_subreg could be eliminated. The use of // D0 is using a partially undef value. This is not *incorrect* since // S1 is can be freely clobbered. // Ideally we would like a way to model this, but leaving the // insert_subreg around causes both correctness and performance issues. bool SubUsed = false; for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) if (isUsed(*SubRegs)) { SubUsed = true; break; } if (!SubUsed) { MBB->getParent()->verify(NULL, "In Register Scavenger"); llvm_unreachable("Using an undefined register!"); } (void)SubUsed; } } else { assert(MO.isDef()); #if 0 // FIXME: Enable this once we've figured out how to correctly transfer // implicit kills during codegen passes like the coalescer. assert((KillRegs.test(Reg) || isUnused(Reg) || isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) && "Re-defining a live register!"); #endif } } #endif // NDEBUG // Commit the changes. setUnused(KillRegs); setUsed(DefRegs); } void RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) { used = RegsAvailable; used.flip(); if (includeReserved) used |= MRI->getReservedRegs(); else used.reset(MRI->getReservedRegs()); } unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const { for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I != E; ++I) if (!isAliasUsed(*I)) { DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(*I) << "\n"); return *I; } return 0; } /// getRegsAvailable - Return all available registers in the register class /// in Mask. BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) { BitVector Mask(TRI->getNumRegs()); for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I != E; ++I) if (!isAliasUsed(*I)) Mask.set(*I); return Mask; } /// findSurvivorReg - Return the candidate register that is unused for the /// longest after StargMII. UseMI is set to the instruction where the search /// stopped. /// /// No more than InstrLimit instructions are inspected. /// unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI, BitVector &Candidates, unsigned InstrLimit, MachineBasicBlock::iterator &UseMI) { int Survivor = Candidates.find_first(); assert(Survivor > 0 && "No candidates for scavenging"); MachineBasicBlock::iterator ME = MBB->getFirstTerminator(); assert(StartMI != ME && "MI already at terminator"); MachineBasicBlock::iterator RestorePointMI = StartMI; MachineBasicBlock::iterator MI = StartMI; bool inVirtLiveRange = false; for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) { if (MI->isDebugValue()) { ++InstrLimit; // Don't count debug instructions continue; } bool isVirtKillInsn = false; bool isVirtDefInsn = false; // Remove any candidates touched by instruction. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { const MachineOperand &MO = MI->getOperand(i); if (MO.isRegMask()) Candidates.clearBitsNotInMask(MO.getRegMask()); if (!MO.isReg() || MO.isUndef() || !MO.getReg()) continue; if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) { if (MO.isDef()) isVirtDefInsn = true; else if (MO.isKill()) isVirtKillInsn = true; continue; } for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI) Candidates.reset(*AI); } // If we're not in a virtual reg's live range, this is a valid // restore point. if (!inVirtLiveRange) RestorePointMI = MI; // Update whether we're in the live range of a virtual register if (isVirtKillInsn) inVirtLiveRange = false; if (isVirtDefInsn) inVirtLiveRange = true; // Was our survivor untouched by this instruction? if (Candidates.test(Survivor)) continue; // All candidates gone? if (Candidates.none()) break; Survivor = Candidates.find_first(); } // If we ran off the end, that's where we want to restore. if (MI == ME) RestorePointMI = ME; assert (RestorePointMI != StartMI && "No available scavenger restore location!"); // We ran out of candidates, so stop the search. UseMI = RestorePointMI; return Survivor; } unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC, MachineBasicBlock::iterator I, int SPAdj) { // Consider all allocatable registers in the register class initially BitVector Candidates = TRI->getAllocatableSet(*I->getParent()->getParent(), RC); // Exclude all the registers being used by the instruction. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { MachineOperand &MO = I->getOperand(i); if (MO.isReg() && MO.getReg() != 0 && !TargetRegisterInfo::isVirtualRegister(MO.getReg())) Candidates.reset(MO.getReg()); } // Try to find a register that's unused if there is one, as then we won't // have to spill. Search explicitly rather than masking out based on // RegsAvailable, as RegsAvailable does not take aliases into account. // That's what getRegsAvailable() is for. BitVector Available = getRegsAvailable(RC); Available &= Candidates; if (Available.any()) Candidates = Available; // Find the register whose use is furthest away. MachineBasicBlock::iterator UseMI; unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI); // If we found an unused register there is no reason to spill it. if (!isAliasUsed(SReg)) { DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n"); return SReg; } assert(ScavengedReg == 0 && "Scavenger slot is live, unable to scavenge another register!"); // Avoid infinite regress ScavengedReg = SReg; // If the target knows how to save/restore the register, let it do so; // otherwise, use the emergency stack spill slot. if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) { // Spill the scavenged register before I. assert(ScavengingFrameIndex >= 0 && "Cannot scavenge register without an emergency spill slot!"); TII->storeRegToStackSlot(*MBB, I, SReg, true, ScavengingFrameIndex, RC,TRI); MachineBasicBlock::iterator II = prior(I); TRI->eliminateFrameIndex(II, SPAdj, this); // Restore the scavenged register before its use (or first terminator). TII->loadRegFromStackSlot(*MBB, UseMI, SReg, ScavengingFrameIndex, RC, TRI); II = prior(UseMI); TRI->eliminateFrameIndex(II, SPAdj, this); } ScavengeRestore = prior(UseMI); // Doing this here leads to infinite regress. // ScavengedReg = SReg; ScavengedRC = RC; DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) << "\n"); return SReg; } <|endoftext|>
<commit_before>// Copyright (c) 2012-2014 The Bitcoin Core developers // Copyright (c) 2014-2015 The Dash Core developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "netbase.h" #include <string> #include <boost/test/unit_test.hpp> using namespace std; BOOST_AUTO_TEST_SUITE(netbase_tests) BOOST_AUTO_TEST_CASE(netbase_networks) { BOOST_CHECK(CNetAddr("127.0.0.1").GetNetwork() == NET_UNROUTABLE); BOOST_CHECK(CNetAddr("::1").GetNetwork() == NET_UNROUTABLE); BOOST_CHECK(CNetAddr("8.8.8.8").GetNetwork() == NET_IPV4); BOOST_CHECK(CNetAddr("2001::8888").GetNetwork() == NET_IPV6); BOOST_CHECK(CNetAddr("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").GetNetwork() == NET_TOR); } BOOST_AUTO_TEST_CASE(netbase_properties) { BOOST_CHECK(CNetAddr("127.0.0.1").IsIPv4()); BOOST_CHECK(CNetAddr("::FFFF:192.168.1.1").IsIPv4()); BOOST_CHECK(CNetAddr("::1").IsIPv6()); BOOST_CHECK(CNetAddr("10.0.0.1").IsRFC1918()); BOOST_CHECK(CNetAddr("192.168.1.1").IsRFC1918()); BOOST_CHECK(CNetAddr("172.31.255.255").IsRFC1918()); BOOST_CHECK(CNetAddr("2001:0DB8::").IsRFC3849()); BOOST_CHECK(CNetAddr("169.254.1.1").IsRFC3927()); BOOST_CHECK(CNetAddr("2002::1").IsRFC3964()); BOOST_CHECK(CNetAddr("FC00::").IsRFC4193()); BOOST_CHECK(CNetAddr("2001::2").IsRFC4380()); BOOST_CHECK(CNetAddr("2001:10::").IsRFC4843()); BOOST_CHECK(CNetAddr("FE80::").IsRFC4862()); BOOST_CHECK(CNetAddr("64:FF9B::").IsRFC6052()); BOOST_CHECK(CNetAddr("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").IsTor()); BOOST_CHECK(CNetAddr("127.0.0.1").IsLocal()); BOOST_CHECK(CNetAddr("::1").IsLocal()); BOOST_CHECK(CNetAddr("8.8.8.8").IsRoutable()); BOOST_CHECK(CNetAddr("2001::1").IsRoutable()); BOOST_CHECK(CNetAddr("127.0.0.1").IsValid()); } bool static TestSplitHost(string test, string host, int port) { string hostOut; int portOut = -1; SplitHostPort(test, portOut, hostOut); return hostOut == host && port == portOut; } BOOST_AUTO_TEST_CASE(netbase_splithost) { BOOST_CHECK(TestSplitHost("www.bitcoin.org", "www.bitcoin.org", -1)); BOOST_CHECK(TestSplitHost("[www.bitcoin.org]", "www.bitcoin.org", -1)); BOOST_CHECK(TestSplitHost("www.bitcoin.org:80", "www.bitcoin.org", 80)); BOOST_CHECK(TestSplitHost("[www.bitcoin.org]:80", "www.bitcoin.org", 80)); BOOST_CHECK(TestSplitHost("127.0.0.1", "127.0.0.1", -1)); BOOST_CHECK(TestSplitHost("127.0.0.1:51472", "127.0.0.1", 51472)); BOOST_CHECK(TestSplitHost("[127.0.0.1]", "127.0.0.1", -1)); BOOST_CHECK(TestSplitHost("[127.0.0.1]:51472", "127.0.0.1", 51472)); BOOST_CHECK(TestSplitHost("::ffff:127.0.0.1", "::ffff:127.0.0.1", -1)); BOOST_CHECK(TestSplitHost("[::ffff:127.0.0.1]:51472", "::ffff:127.0.0.1", 51472)); BOOST_CHECK(TestSplitHost("[::]:51472", "::", 51472)); BOOST_CHECK(TestSplitHost("::51472", "::51472", -1)); BOOST_CHECK(TestSplitHost(":51472", "", 51472)); BOOST_CHECK(TestSplitHost("[]:51472", "", 51472)); BOOST_CHECK(TestSplitHost("", "", -1)); } bool static TestParse(string src, string canon) { CService addr; if (!LookupNumeric(src.c_str(), addr, 65535)) return canon == ""; return canon == addr.ToString(); } BOOST_AUTO_TEST_CASE(netbase_lookupnumeric) { BOOST_CHECK(TestParse("127.0.0.1", "127.0.0.1:65535")); BOOST_CHECK(TestParse("127.0.0.1:51472", "127.0.0.1:51472")); BOOST_CHECK(TestParse("::ffff:127.0.0.1", "127.0.0.1:65535")); BOOST_CHECK(TestParse("::", "[::]:65535")); BOOST_CHECK(TestParse("[::]:51472", "[::]:51472")); BOOST_CHECK(TestParse("[127.0.0.1]", "127.0.0.1:65535")); BOOST_CHECK(TestParse(":::", "")); } BOOST_AUTO_TEST_CASE(onioncat_test) { // values from https://web.archive.org/web/20121122003543/http://www.cypherpunk.at/onioncat/wiki/OnionCat CNetAddr addr1("5wyqrzbvrdsumnok.onion"); CNetAddr addr2("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca"); BOOST_CHECK(addr1 == addr2); BOOST_CHECK(addr1.IsTor()); BOOST_CHECK(addr1.ToStringIP() == "5wyqrzbvrdsumnok.onion"); BOOST_CHECK(addr1.IsRoutable()); } BOOST_AUTO_TEST_CASE(subnet_test) { BOOST_CHECK(CSubNet("1.2.3.0/24") == CSubNet("1.2.3.0/255.255.255.0")); BOOST_CHECK(CSubNet("1.2.3.0/24") != CSubNet("1.2.4.0/255.255.255.0")); BOOST_CHECK(CSubNet("1.2.3.0/24").Match(CNetAddr("1.2.3.4"))); BOOST_CHECK(!CSubNet("1.2.2.0/24").Match(CNetAddr("1.2.3.4"))); BOOST_CHECK(CSubNet("1.2.3.4").Match(CNetAddr("1.2.3.4"))); BOOST_CHECK(CSubNet("1.2.3.4/32").Match(CNetAddr("1.2.3.4"))); BOOST_CHECK(!CSubNet("1.2.3.4").Match(CNetAddr("5.6.7.8"))); BOOST_CHECK(!CSubNet("1.2.3.4/32").Match(CNetAddr("5.6.7.8"))); BOOST_CHECK(CSubNet("::ffff:127.0.0.1").Match(CNetAddr("127.0.0.1"))); BOOST_CHECK(CSubNet("1:2:3:4:5:6:7:8").Match(CNetAddr("1:2:3:4:5:6:7:8"))); BOOST_CHECK(!CSubNet("1:2:3:4:5:6:7:8").Match(CNetAddr("1:2:3:4:5:6:7:9"))); BOOST_CHECK(CSubNet("1:2:3:4:5:6:7:0/112").Match(CNetAddr("1:2:3:4:5:6:7:1234"))); BOOST_CHECK(CSubNet("192.168.0.1/24").Match(CNetAddr("192.168.0.2"))); BOOST_CHECK(CSubNet("192.168.0.20/29").Match(CNetAddr("192.168.0.18"))); BOOST_CHECK(CSubNet("1.2.2.1/24").Match(CNetAddr("1.2.2.4"))); BOOST_CHECK(CSubNet("1.2.2.110/31").Match(CNetAddr("1.2.2.111"))); BOOST_CHECK(CSubNet("1.2.2.20/26").Match(CNetAddr("1.2.2.63"))); // All-Matching IPv6 Matches arbitrary IPv4 and IPv6 BOOST_CHECK(CSubNet("::/0").Match(CNetAddr("1:2:3:4:5:6:7:1234"))); BOOST_CHECK(CSubNet("::/0").Match(CNetAddr("1.2.3.4"))); // All-Matching IPv4 does not Match IPv6 BOOST_CHECK(!CSubNet("0.0.0.0/0").Match(CNetAddr("1:2:3:4:5:6:7:1234"))); // Invalid subnets Match nothing (not even invalid addresses) BOOST_CHECK(!CSubNet().Match(CNetAddr("1.2.3.4"))); BOOST_CHECK(!CSubNet("").Match(CNetAddr("4.5.6.7"))); BOOST_CHECK(!CSubNet("bloop").Match(CNetAddr("0.0.0.0"))); BOOST_CHECK(!CSubNet("bloop").Match(CNetAddr("hab"))); // Check valid/invalid BOOST_CHECK(CSubNet("1.2.3.0/0").IsValid()); BOOST_CHECK(!CSubNet("1.2.3.0/-1").IsValid()); BOOST_CHECK(CSubNet("1.2.3.0/32").IsValid()); BOOST_CHECK(!CSubNet("1.2.3.0/33").IsValid()); BOOST_CHECK(CSubNet("1:2:3:4:5:6:7:8/0").IsValid()); BOOST_CHECK(CSubNet("1:2:3:4:5:6:7:8/33").IsValid()); BOOST_CHECK(!CSubNet("1:2:3:4:5:6:7:8/-1").IsValid()); BOOST_CHECK(CSubNet("1:2:3:4:5:6:7:8/128").IsValid()); BOOST_CHECK(!CSubNet("1:2:3:4:5:6:7:8/129").IsValid()); BOOST_CHECK(!CSubNet("fuzzy").IsValid()); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Update netbase_tests.cpp<commit_after>// Copyright (c) 2012-2014 The Bitcoin Core developers // Copyright (c) 2014-2015 The Dash Core developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017 The Phore developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "netbase.h" #include <string> #include <boost/test/unit_test.hpp> using namespace std; BOOST_AUTO_TEST_SUITE(netbase_tests) BOOST_AUTO_TEST_CASE(netbase_networks) { BOOST_CHECK(CNetAddr("127.0.0.1").GetNetwork() == NET_UNROUTABLE); BOOST_CHECK(CNetAddr("::1").GetNetwork() == NET_UNROUTABLE); BOOST_CHECK(CNetAddr("8.8.8.8").GetNetwork() == NET_IPV4); BOOST_CHECK(CNetAddr("2001::8888").GetNetwork() == NET_IPV6); BOOST_CHECK(CNetAddr("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").GetNetwork() == NET_TOR); } BOOST_AUTO_TEST_CASE(netbase_properties) { BOOST_CHECK(CNetAddr("127.0.0.1").IsIPv4()); BOOST_CHECK(CNetAddr("::FFFF:192.168.1.1").IsIPv4()); BOOST_CHECK(CNetAddr("::1").IsIPv6()); BOOST_CHECK(CNetAddr("10.0.0.1").IsRFC1918()); BOOST_CHECK(CNetAddr("192.168.1.1").IsRFC1918()); BOOST_CHECK(CNetAddr("172.31.255.255").IsRFC1918()); BOOST_CHECK(CNetAddr("2001:0DB8::").IsRFC3849()); BOOST_CHECK(CNetAddr("169.254.1.1").IsRFC3927()); BOOST_CHECK(CNetAddr("2002::1").IsRFC3964()); BOOST_CHECK(CNetAddr("FC00::").IsRFC4193()); BOOST_CHECK(CNetAddr("2001::2").IsRFC4380()); BOOST_CHECK(CNetAddr("2001:10::").IsRFC4843()); BOOST_CHECK(CNetAddr("FE80::").IsRFC4862()); BOOST_CHECK(CNetAddr("64:FF9B::").IsRFC6052()); BOOST_CHECK(CNetAddr("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").IsTor()); BOOST_CHECK(CNetAddr("127.0.0.1").IsLocal()); BOOST_CHECK(CNetAddr("::1").IsLocal()); BOOST_CHECK(CNetAddr("8.8.8.8").IsRoutable()); BOOST_CHECK(CNetAddr("2001::1").IsRoutable()); BOOST_CHECK(CNetAddr("127.0.0.1").IsValid()); } bool static TestSplitHost(string test, string host, int port) { string hostOut; int portOut = -1; SplitHostPort(test, portOut, hostOut); return hostOut == host && port == portOut; } BOOST_AUTO_TEST_CASE(netbase_splithost) { BOOST_CHECK(TestSplitHost("www.bitcoin.org", "www.bitcoin.org", -1)); BOOST_CHECK(TestSplitHost("[www.bitcoin.org]", "www.bitcoin.org", -1)); BOOST_CHECK(TestSplitHost("www.bitcoin.org:80", "www.bitcoin.org", 80)); BOOST_CHECK(TestSplitHost("[www.bitcoin.org]:80", "www.bitcoin.org", 80)); BOOST_CHECK(TestSplitHost("127.0.0.1", "127.0.0.1", -1)); BOOST_CHECK(TestSplitHost("127.0.0.1:51472", "127.0.0.1", 51472)); BOOST_CHECK(TestSplitHost("[127.0.0.1]", "127.0.0.1", -1)); BOOST_CHECK(TestSplitHost("[127.0.0.1]:51472", "127.0.0.1", 51472)); BOOST_CHECK(TestSplitHost("::ffff:127.0.0.1", "::ffff:127.0.0.1", -1)); BOOST_CHECK(TestSplitHost("[::ffff:127.0.0.1]:51472", "::ffff:127.0.0.1", 51472)); BOOST_CHECK(TestSplitHost("[::]:51472", "::", 51472)); BOOST_CHECK(TestSplitHost("::51472", "::51472", -1)); BOOST_CHECK(TestSplitHost(":51472", "", 51472)); BOOST_CHECK(TestSplitHost("[]:51472", "", 51472)); BOOST_CHECK(TestSplitHost("", "", -1)); } bool static TestParse(string src, string canon) { CService addr; if (!LookupNumeric(src.c_str(), addr, 65535)) return canon == ""; return canon == addr.ToString(); } BOOST_AUTO_TEST_CASE(netbase_lookupnumeric) { BOOST_CHECK(TestParse("127.0.0.1", "127.0.0.1:65535")); BOOST_CHECK(TestParse("127.0.0.1:51472", "127.0.0.1:51472")); BOOST_CHECK(TestParse("::ffff:127.0.0.1", "127.0.0.1:65535")); BOOST_CHECK(TestParse("::", "[::]:65535")); BOOST_CHECK(TestParse("[::]:51472", "[::]:51472")); BOOST_CHECK(TestParse("[127.0.0.1]", "127.0.0.1:65535")); BOOST_CHECK(TestParse(":::", "")); } BOOST_AUTO_TEST_CASE(onioncat_test) { // values from https://web.archive.org/web/20121122003543/http://www.cypherpunk.at/onioncat/wiki/OnionCat CNetAddr addr1("5wyqrzbvrdsumnok.onion"); CNetAddr addr2("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca"); BOOST_CHECK(addr1 == addr2); BOOST_CHECK(addr1.IsTor()); BOOST_CHECK(addr1.ToStringIP() == "5wyqrzbvrdsumnok.onion"); BOOST_CHECK(addr1.IsRoutable()); } BOOST_AUTO_TEST_CASE(subnet_test) { BOOST_CHECK(CSubNet("1.2.3.0/24") == CSubNet("1.2.3.0/255.255.255.0")); BOOST_CHECK(CSubNet("1.2.3.0/24") != CSubNet("1.2.4.0/255.255.255.0")); BOOST_CHECK(CSubNet("1.2.3.0/24").Match(CNetAddr("1.2.3.4"))); BOOST_CHECK(!CSubNet("1.2.2.0/24").Match(CNetAddr("1.2.3.4"))); BOOST_CHECK(CSubNet("1.2.3.4").Match(CNetAddr("1.2.3.4"))); BOOST_CHECK(CSubNet("1.2.3.4/32").Match(CNetAddr("1.2.3.4"))); BOOST_CHECK(!CSubNet("1.2.3.4").Match(CNetAddr("5.6.7.8"))); BOOST_CHECK(!CSubNet("1.2.3.4/32").Match(CNetAddr("5.6.7.8"))); BOOST_CHECK(CSubNet("::ffff:127.0.0.1").Match(CNetAddr("127.0.0.1"))); BOOST_CHECK(CSubNet("1:2:3:4:5:6:7:8").Match(CNetAddr("1:2:3:4:5:6:7:8"))); BOOST_CHECK(!CSubNet("1:2:3:4:5:6:7:8").Match(CNetAddr("1:2:3:4:5:6:7:9"))); BOOST_CHECK(CSubNet("1:2:3:4:5:6:7:0/112").Match(CNetAddr("1:2:3:4:5:6:7:1234"))); BOOST_CHECK(CSubNet("192.168.0.1/24").Match(CNetAddr("192.168.0.2"))); BOOST_CHECK(CSubNet("192.168.0.20/29").Match(CNetAddr("192.168.0.18"))); BOOST_CHECK(CSubNet("1.2.2.1/24").Match(CNetAddr("1.2.2.4"))); BOOST_CHECK(CSubNet("1.2.2.110/31").Match(CNetAddr("1.2.2.111"))); BOOST_CHECK(CSubNet("1.2.2.20/26").Match(CNetAddr("1.2.2.63"))); // All-Matching IPv6 Matches arbitrary IPv4 and IPv6 BOOST_CHECK(CSubNet("::/0").Match(CNetAddr("1:2:3:4:5:6:7:1234"))); BOOST_CHECK(CSubNet("::/0").Match(CNetAddr("1.2.3.4"))); // All-Matching IPv4 does not Match IPv6 BOOST_CHECK(!CSubNet("0.0.0.0/0").Match(CNetAddr("1:2:3:4:5:6:7:1234"))); // Invalid subnets Match nothing (not even invalid addresses) BOOST_CHECK(!CSubNet().Match(CNetAddr("1.2.3.4"))); BOOST_CHECK(!CSubNet("").Match(CNetAddr("4.5.6.7"))); BOOST_CHECK(!CSubNet("bloop").Match(CNetAddr("0.0.0.0"))); BOOST_CHECK(!CSubNet("bloop").Match(CNetAddr("hab"))); // Check valid/invalid BOOST_CHECK(CSubNet("1.2.3.0/0").IsValid()); BOOST_CHECK(!CSubNet("1.2.3.0/-1").IsValid()); BOOST_CHECK(CSubNet("1.2.3.0/32").IsValid()); BOOST_CHECK(!CSubNet("1.2.3.0/33").IsValid()); BOOST_CHECK(CSubNet("1:2:3:4:5:6:7:8/0").IsValid()); BOOST_CHECK(CSubNet("1:2:3:4:5:6:7:8/33").IsValid()); BOOST_CHECK(!CSubNet("1:2:3:4:5:6:7:8/-1").IsValid()); BOOST_CHECK(CSubNet("1:2:3:4:5:6:7:8/128").IsValid()); BOOST_CHECK(!CSubNet("1:2:3:4:5:6:7:8/129").IsValid()); BOOST_CHECK(!CSubNet("fuzzy").IsValid()); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2014, Robert Bosch LLC. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Robert Bosch nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * *********************************************************************/ #include "modules/perception/traffic_light/util/color_space.h" #include <cassert> #include <cstdint> #include "modules/common/log.h" namespace apollo { namespace perception { namespace traffic_light { #ifdef __USE_AVX__ template <bool align> SIMD_INLINE void YuvSeperateAvx2(uint8_t *y, __m256i *y0, __m256i *y1, __m256i *u0, __m256i *v0) { DCHECK_NOTNULL(y0); DCHECK_NOTNULL(y1); DCHECK_NOTNULL(u0); DCHECK_NOTNULL(v0); __m256i yuv_m256[4]; if (align) { yuv_m256[0] = Load<true>(reinterpret_cast<__m256i *>(y)); yuv_m256[1] = Load<true>(reinterpret_cast<__m256i *>(y) + 1); yuv_m256[2] = Load<true>(reinterpret_cast<__m256i *>(y) + 2); yuv_m256[3] = Load<true>(reinterpret_cast<__m256i *>(y) + 3); } else { yuv_m256[0] = Load<false>(reinterpret_cast<__m256i *>(y)); yuv_m256[1] = Load<false>(reinterpret_cast<__m256i *>(y) + 1); yuv_m256[2] = Load<false>(reinterpret_cast<__m256i *>(y) + 2); yuv_m256[3] = Load<false>(reinterpret_cast<__m256i *>(y) + 3); } *y0 = _mm256_or_si256(_mm256_permute4x64_epi64( _mm256_shuffle_epi8(yuv_m256[0], Y_SHUFFLE0), 0xD8), _mm256_permute4x64_epi64( _mm256_shuffle_epi8(yuv_m256[1], Y_SHUFFLE1), 0xD8)); *y1 = _mm256_or_si256(_mm256_permute4x64_epi64( _mm256_shuffle_epi8(yuv_m256[2], Y_SHUFFLE0), 0xD8), _mm256_permute4x64_epi64( _mm256_shuffle_epi8(yuv_m256[3], Y_SHUFFLE1), 0xD8)); *u0 = _mm256_permutevar8x32_epi32( _mm256_or_si256( _mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[0], U_SHUFFLE0), _mm256_shuffle_epi8(yuv_m256[1], U_SHUFFLE1)), _mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[2], U_SHUFFLE2), _mm256_shuffle_epi8(yuv_m256[3], U_SHUFFLE3))), U_SHUFFLE4); *v0 = _mm256_permutevar8x32_epi32( _mm256_or_si256( _mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[0], V_SHUFFLE0), _mm256_shuffle_epi8(yuv_m256[1], V_SHUFFLE1)), _mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[2], V_SHUFFLE2), _mm256_shuffle_epi8(yuv_m256[3], V_SHUFFLE3))), U_SHUFFLE4); } template <bool align> void Yuv2rgbAvx2(__m256i y0, __m256i u0, __m256i v0, uint8_t *rgb) { __m256i r0 = YuvToRed(y0, v0); __m256i g0 = YuvToGreen(y0, u0, v0); __m256i b0 = YuvToBlue(y0, u0); Store<align>(reinterpret_cast<__m256i *>(rgb) + 0, InterleaveBgr<0>(r0, g0, b0)); Store<align>(reinterpret_cast<__m256i *>(rgb) + 1, InterleaveBgr<1>(r0, g0, b0)); Store<align>(reinterpret_cast<__m256i *>(rgb) + 2, InterleaveBgr<2>(r0, g0, b0)); } template <bool align> void Yuv2rgbAvx2(uint8_t *yuv, uint8_t *rgb) { __m256i y0, y1, u0, v0; YuvSeperateAvx2<align>(yuv, &y0, &y1, &u0, &v0); __m256i u0_u0 = _mm256_permute4x64_epi64(u0, 0xD8); __m256i v0_v0 = _mm256_permute4x64_epi64(v0, 0xD8); Yuv2rgbAvx2<align>(y0, _mm256_unpacklo_epi8(u0_u0, u0_u0), _mm256_unpacklo_epi8(v0_v0, v0_v0), rgb); Yuv2rgbAvx2<align>(y1, _mm256_unpackhi_epi8(u0_u0, u0_u0), _mm256_unpackhi_epi8(v0_v0, v0_v0), rgb + 3 * sizeof(__m256i)); } void Yuyv2rgb(unsigned char *YUV, unsigned char *RGB, int NumPixels) { bool align = Aligned(YUV) & Aligned(RGB); uint8_t *yuv_offset = YUV; uint8_t *rgb_offset = RGB; if (align) { for (int i = 0; i < NumPixels; i = i + (2 * sizeof(__m256i)), yuv_offset += 4 * sizeof(__m256i), rgb_offset += 6 * sizeof(__m256i)) { Yuv2rgbAvx2<true>(yuv_offset, rgb_offset); } } else { for (int i = 0; i < NumPixels; i = i + (2 * sizeof(__m256i)), yuv_offset += 4 * sizeof(__m256i), rgb_offset += 6 * sizeof(__m256i)) { Yuv2rgbAvx2<false>(yuv_offset, rgb_offset); } } } #else unsigned char CLIPVALUE(int val) { // Old method (if) val = val < 0 ? 0 : val; return val > 255 ? 255 : val; // New method (array) // return uchar_clipping_table[val + clipping_table_offset]; } void YUV2RGB(const unsigned char y, const unsigned char u, const unsigned char v, unsigned char* r, unsigned char* g, unsigned char* b) { const int y2 = static_cast<int>(y); const int u2 = static_cast<int>(u) - 128; const int v2 = static_cast<int>(v) - 128; double r2 = y2 + (1.4065 * v2); double g2 = y2 - (0.3455 * u2) - (0.7169 * v2); double b2 = y2 + (2.041 * u2); *r = CLIPVALUE(r2); *g = CLIPVALUE(g2); *b = CLIPVALUE(b2); } void Yuyv2rgb(unsigned char* YUV, unsigned char* RGB, int NumPixels) { for (int i = 0, j = 0; i < (NumPixels << 1); i += 4, j += 6) { unsigned char u = (unsigned char)YUV[i + 0]; unsigned char y0 = (unsigned char)YUV[i + 1]; unsigned char v = (unsigned char)YUV[i + 2]; unsigned char y1 = (unsigned char)YUV[i + 3]; unsigned char r, g, b; YUV2RGB(y0, u, v, &r, &g, &b); RGB[j + 0] = r; RGB[j + 1] = g; RGB[j + 2] = b; YUV2RGB(y1, u, v, &r, &g, &b); RGB[j + 3] = r; RGB[j + 4] = g; RGB[j + 5] = b; } } #endif } // namespace traffic_light } // namespace perception } // namespace apollo <commit_msg>Perception: fixed bug in Yuyv2rgb conversion for AVX non-compliant CPUs.<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2014, Robert Bosch LLC. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Robert Bosch nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * *********************************************************************/ #include "modules/perception/traffic_light/util/color_space.h" #include <cassert> #include <cstdint> #include "modules/common/log.h" namespace apollo { namespace perception { namespace traffic_light { #ifdef __USE_AVX__ template <bool align> SIMD_INLINE void YuvSeperateAvx2(uint8_t *y, __m256i *y0, __m256i *y1, __m256i *u0, __m256i *v0) { DCHECK_NOTNULL(y0); DCHECK_NOTNULL(y1); DCHECK_NOTNULL(u0); DCHECK_NOTNULL(v0); __m256i yuv_m256[4]; if (align) { yuv_m256[0] = Load<true>(reinterpret_cast<__m256i *>(y)); yuv_m256[1] = Load<true>(reinterpret_cast<__m256i *>(y) + 1); yuv_m256[2] = Load<true>(reinterpret_cast<__m256i *>(y) + 2); yuv_m256[3] = Load<true>(reinterpret_cast<__m256i *>(y) + 3); } else { yuv_m256[0] = Load<false>(reinterpret_cast<__m256i *>(y)); yuv_m256[1] = Load<false>(reinterpret_cast<__m256i *>(y) + 1); yuv_m256[2] = Load<false>(reinterpret_cast<__m256i *>(y) + 2); yuv_m256[3] = Load<false>(reinterpret_cast<__m256i *>(y) + 3); } *y0 = _mm256_or_si256(_mm256_permute4x64_epi64( _mm256_shuffle_epi8(yuv_m256[0], Y_SHUFFLE0), 0xD8), _mm256_permute4x64_epi64( _mm256_shuffle_epi8(yuv_m256[1], Y_SHUFFLE1), 0xD8)); *y1 = _mm256_or_si256(_mm256_permute4x64_epi64( _mm256_shuffle_epi8(yuv_m256[2], Y_SHUFFLE0), 0xD8), _mm256_permute4x64_epi64( _mm256_shuffle_epi8(yuv_m256[3], Y_SHUFFLE1), 0xD8)); *u0 = _mm256_permutevar8x32_epi32( _mm256_or_si256( _mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[0], U_SHUFFLE0), _mm256_shuffle_epi8(yuv_m256[1], U_SHUFFLE1)), _mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[2], U_SHUFFLE2), _mm256_shuffle_epi8(yuv_m256[3], U_SHUFFLE3))), U_SHUFFLE4); *v0 = _mm256_permutevar8x32_epi32( _mm256_or_si256( _mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[0], V_SHUFFLE0), _mm256_shuffle_epi8(yuv_m256[1], V_SHUFFLE1)), _mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[2], V_SHUFFLE2), _mm256_shuffle_epi8(yuv_m256[3], V_SHUFFLE3))), U_SHUFFLE4); } template <bool align> void Yuv2rgbAvx2(__m256i y0, __m256i u0, __m256i v0, uint8_t *rgb) { __m256i r0 = YuvToRed(y0, v0); __m256i g0 = YuvToGreen(y0, u0, v0); __m256i b0 = YuvToBlue(y0, u0); Store<align>(reinterpret_cast<__m256i *>(rgb) + 0, InterleaveBgr<0>(r0, g0, b0)); Store<align>(reinterpret_cast<__m256i *>(rgb) + 1, InterleaveBgr<1>(r0, g0, b0)); Store<align>(reinterpret_cast<__m256i *>(rgb) + 2, InterleaveBgr<2>(r0, g0, b0)); } template <bool align> void Yuv2rgbAvx2(uint8_t *yuv, uint8_t *rgb) { __m256i y0, y1, u0, v0; YuvSeperateAvx2<align>(yuv, &y0, &y1, &u0, &v0); __m256i u0_u0 = _mm256_permute4x64_epi64(u0, 0xD8); __m256i v0_v0 = _mm256_permute4x64_epi64(v0, 0xD8); Yuv2rgbAvx2<align>(y0, _mm256_unpacklo_epi8(u0_u0, u0_u0), _mm256_unpacklo_epi8(v0_v0, v0_v0), rgb); Yuv2rgbAvx2<align>(y1, _mm256_unpackhi_epi8(u0_u0, u0_u0), _mm256_unpackhi_epi8(v0_v0, v0_v0), rgb + 3 * sizeof(__m256i)); } void Yuyv2rgb(unsigned char *YUV, unsigned char *RGB, int NumPixels) { bool align = Aligned(YUV) & Aligned(RGB); uint8_t *yuv_offset = YUV; uint8_t *rgb_offset = RGB; if (align) { for (int i = 0; i < NumPixels; i = i + (2 * sizeof(__m256i)), yuv_offset += 4 * sizeof(__m256i), rgb_offset += 6 * sizeof(__m256i)) { Yuv2rgbAvx2<true>(yuv_offset, rgb_offset); } } else { for (int i = 0; i < NumPixels; i = i + (2 * sizeof(__m256i)), yuv_offset += 4 * sizeof(__m256i), rgb_offset += 6 * sizeof(__m256i)) { Yuv2rgbAvx2<false>(yuv_offset, rgb_offset); } } } #else unsigned char CLIPVALUE(int val) { // Old method (if) val = val < 0 ? 0 : val; return val > 255 ? 255 : val; // New method (array) // return uchar_clipping_table[val + clipping_table_offset]; } void YUV2RGB(const unsigned char y, const unsigned char u, const unsigned char v, unsigned char* r, unsigned char* g, unsigned char* b) { const int y2 = static_cast<int>(y); const int u2 = static_cast<int>(u) - 128; const int v2 = static_cast<int>(v) - 128; double r2 = y2 + (1.4065 * v2); double g2 = y2 - (0.3455 * u2) - (0.7169 * v2); double b2 = y2 + (2.041 * u2); *r = CLIPVALUE(r2); *g = CLIPVALUE(g2); *b = CLIPVALUE(b2); } void Yuyv2rgb(unsigned char* YUV, unsigned char* RGB, int NumPixels) { for (int i = 0, j = 0; i < (NumPixels << 1); i += 4, j += 6) { unsigned char y0 = (unsigned char)YUV[i + 0]; unsigned char u = (unsigned char)YUV[i + 1]; unsigned char y1 = (unsigned char)YUV[i + 2]; unsigned char v = (unsigned char)YUV[i + 3]; unsigned char r, g, b; YUV2RGB(y0, u, v, &r, &g, &b); RGB[j + 0] = r; RGB[j + 1] = g; RGB[j + 2] = b; YUV2RGB(y1, u, v, &r, &g, &b); RGB[j + 3] = r; RGB[j + 4] = g; RGB[j + 5] = b; } } #endif } // namespace traffic_light } // namespace perception } // namespace apollo <|endoftext|>
<commit_before>#include "RTSPluginPrivatePCH.h" #include "RTSPlayerController.h" #include "RTSSelectableComponent.h" #include "RTSCameraBoundsVolume.h" #include "Components/InputComponent.h" #include "Engine/LocalPlayer.h" #include "Kismet/GameplayStatics.h" #include "Engine/Engine.h" #include "EngineUtils.h" void ARTSPlayerController::BeginPlay() { APlayerController::BeginPlay(); // Enable mouse input. APlayerController::bShowMouseCursor = true; APlayerController::bEnableClickEvents = true; APlayerController::bEnableMouseOverEvents = true; // Bind actions. InputComponent->BindAction("Select", IE_Released, this, &ARTSPlayerController::OnLeftMouseButtonReleased); InputComponent->BindAxis("MoveCameraLeftRight", this, &ARTSPlayerController::OnMoveCameraLeftRight); InputComponent->BindAxis("MoveCameraUpDown", this, &ARTSPlayerController::OnMoveCameraUpDown); // Get camera bounds. for (TActorIterator<ARTSCameraBoundsVolume> ActorItr(GetWorld()); ActorItr; ++ActorItr) { CameraBoundsVolume = *ActorItr; break; } } void ARTSPlayerController::OnLeftMouseButtonReleased() { UWorld* World = GetWorld(); if (!World) { return; } // Get local player viewport. ULocalPlayer* LocalPlayer = Cast<ULocalPlayer>(Player); if (!LocalPlayer || !LocalPlayer->ViewportClient) { return; } // Get mouse position. FVector2D MousePosition; if (!LocalPlayer->ViewportClient->GetMousePosition(MousePosition)) { return; } // Get ray. FVector WorldOrigin; FVector WorldDirection; if (!UGameplayStatics::DeprojectScreenToWorld(this, MousePosition, WorldOrigin, WorldDirection)) { return; } // Cast ray. FCollisionObjectQueryParams Params(FCollisionObjectQueryParams::InitType::AllObjects); TArray<FHitResult> HitResults; World->LineTraceMultiByObjectType( HitResults, WorldOrigin, WorldOrigin + WorldDirection * HitResultTraceDistance, Params); // Check results. SelectedActors.Empty(); for (auto& HitResult : HitResults) { // Check if hit any actor. if (HitResult.Actor == nullptr) { continue; } // Check if hit selectable actor. auto SelectableComponent = HitResult.Actor->FindComponentByClass<URTSSelectableComponent>(); if (!SelectableComponent) { continue; } // Select single actor. SelectedActors.Add(HitResult.Actor.Get()); break; } // Notify listeners. NotifyOnSelectionChanged(SelectedActors); } void ARTSPlayerController::OnMoveCameraLeftRight(float Value) { CameraLeftRightAxisValue = Value; } void ARTSPlayerController::OnMoveCameraUpDown(float Value) { CameraUpDownAxisValue = Value; } void ARTSPlayerController::NotifyOnSelectionChanged(const TArray<AActor*>& Selection) { ReceiveOnSelectionChanged(Selection); } void ARTSPlayerController::PlayerTick(float DeltaTime) { APlayerController::PlayerTick(DeltaTime); APawn* PlayerPawn = GetPawn(); if (!PlayerPawn) { return; } // Get mouse input. float MouseX; float MouseY; const FVector2D ViewportSize = FVector2D(GEngine->GameViewport->Viewport->GetSizeXY()); const float ScrollBorderRight = ViewportSize.X - CameraScrollThreshold; const float ScrollBorderTop = ViewportSize.Y - CameraScrollThreshold; if (GetMousePosition(MouseX, MouseY)) { if (MouseX <= CameraScrollThreshold) { CameraLeftRightAxisValue -= 1 - (MouseX / CameraScrollThreshold); } else if (MouseX >= ScrollBorderRight) { CameraLeftRightAxisValue += (MouseX - ScrollBorderRight) / CameraScrollThreshold; } if (MouseY <= CameraScrollThreshold) { CameraUpDownAxisValue += 1 - (MouseY / CameraScrollThreshold); } else if (MouseY >= ScrollBorderTop) { CameraUpDownAxisValue -= (MouseY - ScrollBorderTop) / CameraScrollThreshold; } } // Apply input. CameraLeftRightAxisValue = FMath::Clamp(CameraLeftRightAxisValue, -1.0f, +1.0f); CameraUpDownAxisValue = FMath::Clamp(CameraUpDownAxisValue, -1.0f, +1.0f); FVector Location = PlayerPawn->GetActorLocation(); Location += FVector::RightVector * CameraSpeed * CameraLeftRightAxisValue; Location += FVector::ForwardVector * CameraSpeed * CameraUpDownAxisValue; // Enforce camera bounds. if (!CameraBoundsVolume || CameraBoundsVolume->EncompassesPoint(Location)) { PlayerPawn->SetActorLocation(Location); } } <commit_msg>Add log output.<commit_after>#include "RTSPluginPrivatePCH.h" #include "RTSPlayerController.h" #include "RTSSelectableComponent.h" #include "RTSCameraBoundsVolume.h" #include "Components/InputComponent.h" #include "Engine/LocalPlayer.h" #include "Kismet/GameplayStatics.h" #include "Engine/Engine.h" #include "EngineUtils.h" void ARTSPlayerController::BeginPlay() { APlayerController::BeginPlay(); // Enable mouse input. APlayerController::bShowMouseCursor = true; APlayerController::bEnableClickEvents = true; APlayerController::bEnableMouseOverEvents = true; // Bind actions. InputComponent->BindAction("Select", IE_Released, this, &ARTSPlayerController::OnLeftMouseButtonReleased); InputComponent->BindAxis("MoveCameraLeftRight", this, &ARTSPlayerController::OnMoveCameraLeftRight); InputComponent->BindAxis("MoveCameraUpDown", this, &ARTSPlayerController::OnMoveCameraUpDown); // Get camera bounds. for (TActorIterator<ARTSCameraBoundsVolume> ActorItr(GetWorld()); ActorItr; ++ActorItr) { CameraBoundsVolume = *ActorItr; break; } if (!CameraBoundsVolume) { UE_LOG(RTSLog, Warning, TEXT("No RTSCameraBoundsVolume found. Camera will be able to move anywhere.")); } } void ARTSPlayerController::OnLeftMouseButtonReleased() { UWorld* World = GetWorld(); if (!World) { return; } // Get local player viewport. ULocalPlayer* LocalPlayer = Cast<ULocalPlayer>(Player); if (!LocalPlayer || !LocalPlayer->ViewportClient) { return; } // Get mouse position. FVector2D MousePosition; if (!LocalPlayer->ViewportClient->GetMousePosition(MousePosition)) { return; } // Get ray. FVector WorldOrigin; FVector WorldDirection; if (!UGameplayStatics::DeprojectScreenToWorld(this, MousePosition, WorldOrigin, WorldDirection)) { return; } // Cast ray. FCollisionObjectQueryParams Params(FCollisionObjectQueryParams::InitType::AllObjects); TArray<FHitResult> HitResults; World->LineTraceMultiByObjectType( HitResults, WorldOrigin, WorldOrigin + WorldDirection * HitResultTraceDistance, Params); // Check results. SelectedActors.Empty(); for (auto& HitResult : HitResults) { // Check if hit any actor. if (HitResult.Actor == nullptr) { continue; } // Check if hit selectable actor. auto SelectableComponent = HitResult.Actor->FindComponentByClass<URTSSelectableComponent>(); if (!SelectableComponent) { continue; } // Select single actor. SelectedActors.Add(HitResult.Actor.Get()); UE_LOG(RTSLog, Log, TEXT("Selected actor%s."), *HitResult.Actor->GetName()); break; } // Notify listeners. NotifyOnSelectionChanged(SelectedActors); } void ARTSPlayerController::OnMoveCameraLeftRight(float Value) { CameraLeftRightAxisValue = Value; } void ARTSPlayerController::OnMoveCameraUpDown(float Value) { CameraUpDownAxisValue = Value; } void ARTSPlayerController::NotifyOnSelectionChanged(const TArray<AActor*>& Selection) { ReceiveOnSelectionChanged(Selection); } void ARTSPlayerController::PlayerTick(float DeltaTime) { APlayerController::PlayerTick(DeltaTime); APawn* PlayerPawn = GetPawn(); if (!PlayerPawn) { return; } // Get mouse input. float MouseX; float MouseY; const FVector2D ViewportSize = FVector2D(GEngine->GameViewport->Viewport->GetSizeXY()); const float ScrollBorderRight = ViewportSize.X - CameraScrollThreshold; const float ScrollBorderTop = ViewportSize.Y - CameraScrollThreshold; if (GetMousePosition(MouseX, MouseY)) { if (MouseX <= CameraScrollThreshold) { CameraLeftRightAxisValue -= 1 - (MouseX / CameraScrollThreshold); } else if (MouseX >= ScrollBorderRight) { CameraLeftRightAxisValue += (MouseX - ScrollBorderRight) / CameraScrollThreshold; } if (MouseY <= CameraScrollThreshold) { CameraUpDownAxisValue += 1 - (MouseY / CameraScrollThreshold); } else if (MouseY >= ScrollBorderTop) { CameraUpDownAxisValue -= (MouseY - ScrollBorderTop) / CameraScrollThreshold; } } // Apply input. CameraLeftRightAxisValue = FMath::Clamp(CameraLeftRightAxisValue, -1.0f, +1.0f); CameraUpDownAxisValue = FMath::Clamp(CameraUpDownAxisValue, -1.0f, +1.0f); FVector Location = PlayerPawn->GetActorLocation(); Location += FVector::RightVector * CameraSpeed * CameraLeftRightAxisValue; Location += FVector::ForwardVector * CameraSpeed * CameraUpDownAxisValue; // Enforce camera bounds. if (!CameraBoundsVolume || CameraBoundsVolume->EncompassesPoint(Location)) { PlayerPawn->SetActorLocation(Location); } } <|endoftext|>
<commit_before>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Core/ParameterList.hpp> #include <Nazara/Core/Error.hpp> #include <Nazara/Core/MemoryHelper.hpp> #include <cstring> #include <limits> #include <new> #include <Nazara/Core/Debug.hpp> NzParameterList::NzParameterList(const NzParameterList& list) { operator=(list); } NzParameterList::NzParameterList(NzParameterList&& list) : m_parameters(std::move(list.m_parameters)) { } NzParameterList::~NzParameterList() { Clear(); } void NzParameterList::Clear() { for (auto it = m_parameters.begin(); it != m_parameters.end(); ++it) DestroyValue(it->second); m_parameters.clear(); } bool NzParameterList::GetBooleanParameter(const NzString& name, bool* value) const { auto it = m_parameters.find(name); if (it == m_parameters.end()) { NazaraError("Parameter \"" + name + "\" is not present"); return false; } switch (it->second.type) { case nzParameterType_Boolean: *value = it->second.value.boolVal; return true; case nzParameterType_Integer: *value = (it->second.value.intVal != 0); return true; case nzParameterType_String: { bool converted; if (it->second.value.stringVal.ToBool(&converted, NzString::CaseInsensitive)) { *value = converted; return true; } break; } case nzParameterType_Float: case nzParameterType_None: case nzParameterType_Pointer: case nzParameterType_Userdata: break; } NazaraError("Parameter value is not representable as a boolean"); return false; } bool NzParameterList::GetFloatParameter(const NzString& name, float* value) const { auto it = m_parameters.find(name); if (it == m_parameters.end()) { NazaraError("Parameter \"" + name + "\" is not present"); return false; } switch (it->second.type) { case nzParameterType_Float: *value = it->second.value.floatVal; return true; case nzParameterType_Integer: *value = static_cast<float>(it->second.value.intVal); return true; case nzParameterType_String: { double converted; if (it->second.value.stringVal.ToDouble(&converted)) { *value = static_cast<float>(converted); return true; } break; } case nzParameterType_Boolean: case nzParameterType_None: case nzParameterType_Pointer: case nzParameterType_Userdata: break; } NazaraError("Parameter value is not representable as a float"); return false; } bool NzParameterList::GetIntegerParameter(const NzString& name, int* value) const { auto it = m_parameters.find(name); if (it == m_parameters.end()) { NazaraError("Parameter \"" + name + "\" is not present"); return false; } switch (it->second.type) { case nzParameterType_Boolean: *value = (it->second.value.boolVal) ? 1 : 0; return true; case nzParameterType_Float: *value = static_cast<int>(it->second.value.floatVal); return true; case nzParameterType_Integer: *value = it->second.value.intVal; return false; case nzParameterType_String: { long long converted; if (it->second.value.stringVal.ToInteger(&converted)) { if (converted <= std::numeric_limits<int>::max() && converted >= std::numeric_limits<int>::min()) { *value = static_cast<int>(converted); return true; } } break; } case nzParameterType_None: case nzParameterType_Pointer: case nzParameterType_Userdata: break; } NazaraError("Parameter value is not representable as a integer"); return false; } bool NzParameterList::GetParameterType(const NzString& name, nzParameterType* type) const { auto it = m_parameters.find(name); if (it == m_parameters.end()) return false; *type = it->second.type; return true; } bool NzParameterList::GetPointerParameter(const NzString& name, void** value) const { auto it = m_parameters.find(name); if (it == m_parameters.end()) { NazaraError("Parameter \"" + name + "\" is not present"); return false; } switch (it->second.type) { case nzParameterType_Pointer: *value = it->second.value.ptrVal; return true; case nzParameterType_Userdata: *value = it->second.value.userdataVal->ptr; return true; case nzParameterType_Boolean: case nzParameterType_Float: case nzParameterType_Integer: case nzParameterType_None: case nzParameterType_String: break; } NazaraError("Parameter value is not a pointer"); return false; } bool NzParameterList::GetStringParameter(const NzString& name, NzString* value) const { auto it = m_parameters.find(name); if (it == m_parameters.end()) { NazaraError("Parameter \"" + name + "\" is not present"); return false; } switch (it->second.type) { case nzParameterType_Boolean: *value = NzString::Boolean(it->second.value.boolVal); return true; case nzParameterType_Float: *value = NzString::Number(it->second.value.floatVal); return true; case nzParameterType_Integer: *value = NzString::Number(it->second.value.intVal); return true; case nzParameterType_String: *value = it->second.value.stringVal; return true; case nzParameterType_Pointer: *value = NzString::Pointer(it->second.value.ptrVal); return true; case nzParameterType_Userdata: *value = NzString::Pointer(it->second.value.userdataVal->ptr); return true; case nzParameterType_None: *value = NzString(); return true; } NazaraInternalError("Parameter value is not valid"); return false; } bool NzParameterList::GetUserdataParameter(const NzString& name, void** value) const { auto it = m_parameters.find(name); if (it == m_parameters.end()) { NazaraError("Parameter \"" + name + "\" is not present"); return false; } if (it->second.type == nzParameterType_Userdata) { *value = it->second.value.userdataVal->ptr; return true; } else { NazaraError("Parameter value is not an userdata"); return false; } } bool NzParameterList::HasParameter(const NzString& name) const { return m_parameters.find(name) != m_parameters.end(); } void NzParameterList::RemoveParameter(const NzString& name) { auto it = m_parameters.find(name); if (it != m_parameters.end()) { DestroyValue(it->second); m_parameters.erase(it); } } void NzParameterList::SetParameter(const NzString& name) { std::pair<ParameterMap::iterator, bool> pair = m_parameters.insert(std::make_pair(name, Parameter())); Parameter& parameter = pair.first->second; if (!pair.second) DestroyValue(parameter); parameter.type = nzParameterType_None; } void NzParameterList::SetParameter(const NzString& name, const NzString& value) { std::pair<ParameterMap::iterator, bool> pair = m_parameters.insert(std::make_pair(name, Parameter())); Parameter& parameter = pair.first->second; if (!pair.second) DestroyValue(parameter); parameter.type = nzParameterType_String; NzPlacementNew<NzString>(&parameter.value.stringVal, value); } void NzParameterList::SetParameter(const NzString& name, const char* value) { std::pair<ParameterMap::iterator, bool> pair = m_parameters.insert(std::make_pair(name, Parameter())); Parameter& parameter = pair.first->second; if (!pair.second) DestroyValue(parameter); parameter.type = nzParameterType_String; NzPlacementNew<NzString>(&parameter.value.stringVal, value); } void NzParameterList::SetParameter(const NzString& name, void* value) { std::pair<ParameterMap::iterator, bool> pair = m_parameters.insert(std::make_pair(name, Parameter())); Parameter& parameter = pair.first->second; if (!pair.second) DestroyValue(parameter); parameter.type = nzParameterType_Pointer; parameter.value.ptrVal = value; } void NzParameterList::SetParameter(const NzString& name, void* value, Destructor destructor) { std::pair<ParameterMap::iterator, bool> pair = m_parameters.insert(std::make_pair(name, Parameter())); Parameter& parameter = pair.first->second; if (!pair.second) DestroyValue(parameter); parameter.type = nzParameterType_Userdata; parameter.value.userdataVal = new Parameter::UserdataValue(destructor, value); } void NzParameterList::SetParameter(const NzString& name, bool value) { std::pair<ParameterMap::iterator, bool> pair = m_parameters.insert(std::make_pair(name, Parameter())); Parameter& parameter = pair.first->second; if (!pair.second) DestroyValue(parameter); parameter.type = nzParameterType_Boolean; parameter.value.boolVal = value; } void NzParameterList::SetParameter(const NzString& name, float value) { std::pair<ParameterMap::iterator, bool> pair = m_parameters.insert(std::make_pair(name, Parameter())); Parameter& parameter = pair.first->second; if (!pair.second) DestroyValue(parameter); parameter.type = nzParameterType_Float; parameter.value.floatVal = value; } void NzParameterList::SetParameter(const NzString& name, int value) { std::pair<ParameterMap::iterator, bool> pair = m_parameters.insert(std::make_pair(name, Parameter())); Parameter& parameter = pair.first->second; if (!pair.second) DestroyValue(parameter); parameter.type = nzParameterType_Integer; parameter.value.intVal = value; } NzParameterList& NzParameterList::operator=(const NzParameterList& list) { Clear(); for (auto it = list.m_parameters.begin(); it != list.m_parameters.end(); ++it) { Parameter& parameter = m_parameters[it->first]; switch (it->second.type) { case nzParameterType_Boolean: case nzParameterType_Float: case nzParameterType_Integer: case nzParameterType_Pointer: std::memcpy(&parameter, &it->second, sizeof(Parameter)); break; case nzParameterType_String: parameter.type = nzParameterType_String; NzPlacementNew<NzString>(&parameter.value.stringVal, it->second.value.stringVal); break; case nzParameterType_Userdata: parameter.type = nzParameterType_Userdata; parameter.value.userdataVal = it->second.value.userdataVal; ++(parameter.value.userdataVal->counter); break; case nzParameterType_None: parameter.type = nzParameterType_None; break; } } return *this; } NzParameterList& NzParameterList::operator=(NzParameterList&& list) { m_parameters = std::move(list.m_parameters); return *this; } void NzParameterList::DestroyValue(Parameter& parameter) { switch (parameter.type) { case nzParameterType_String: parameter.value.stringVal.~NzString(); break; case nzParameterType_Userdata: { Parameter::UserdataValue* userdata = parameter.value.userdataVal; if (--userdata->counter == 0) { userdata->destructor(userdata->ptr); delete userdata; } break; } case nzParameterType_Boolean: case nzParameterType_Float: case nzParameterType_Integer: case nzParameterType_None: case nzParameterType_Pointer: break; } } <commit_msg>Core/ParameterList: Fixed typo<commit_after>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Core/ParameterList.hpp> #include <Nazara/Core/Error.hpp> #include <Nazara/Core/MemoryHelper.hpp> #include <cstring> #include <limits> #include <new> #include <Nazara/Core/Debug.hpp> NzParameterList::NzParameterList(const NzParameterList& list) { operator=(list); } NzParameterList::NzParameterList(NzParameterList&& list) : m_parameters(std::move(list.m_parameters)) { } NzParameterList::~NzParameterList() { Clear(); } void NzParameterList::Clear() { for (auto it = m_parameters.begin(); it != m_parameters.end(); ++it) DestroyValue(it->second); m_parameters.clear(); } bool NzParameterList::GetBooleanParameter(const NzString& name, bool* value) const { auto it = m_parameters.find(name); if (it == m_parameters.end()) { NazaraError("Parameter \"" + name + "\" is not present"); return false; } switch (it->second.type) { case nzParameterType_Boolean: *value = it->second.value.boolVal; return true; case nzParameterType_Integer: *value = (it->second.value.intVal != 0); return true; case nzParameterType_String: { bool converted; if (it->second.value.stringVal.ToBool(&converted, NzString::CaseInsensitive)) { *value = converted; return true; } break; } case nzParameterType_Float: case nzParameterType_None: case nzParameterType_Pointer: case nzParameterType_Userdata: break; } NazaraError("Parameter value is not representable as a boolean"); return false; } bool NzParameterList::GetFloatParameter(const NzString& name, float* value) const { auto it = m_parameters.find(name); if (it == m_parameters.end()) { NazaraError("Parameter \"" + name + "\" is not present"); return false; } switch (it->second.type) { case nzParameterType_Float: *value = it->second.value.floatVal; return true; case nzParameterType_Integer: *value = static_cast<float>(it->second.value.intVal); return true; case nzParameterType_String: { double converted; if (it->second.value.stringVal.ToDouble(&converted)) { *value = static_cast<float>(converted); return true; } break; } case nzParameterType_Boolean: case nzParameterType_None: case nzParameterType_Pointer: case nzParameterType_Userdata: break; } NazaraError("Parameter value is not representable as a float"); return false; } bool NzParameterList::GetIntegerParameter(const NzString& name, int* value) const { auto it = m_parameters.find(name); if (it == m_parameters.end()) { NazaraError("Parameter \"" + name + "\" is not present"); return false; } switch (it->second.type) { case nzParameterType_Boolean: *value = (it->second.value.boolVal) ? 1 : 0; return true; case nzParameterType_Float: *value = static_cast<int>(it->second.value.floatVal); return true; case nzParameterType_Integer: *value = it->second.value.intVal; return false; case nzParameterType_String: { long long converted; if (it->second.value.stringVal.ToInteger(&converted)) { if (converted <= std::numeric_limits<int>::max() && converted >= std::numeric_limits<int>::min()) { *value = static_cast<int>(converted); return true; } } break; } case nzParameterType_None: case nzParameterType_Pointer: case nzParameterType_Userdata: break; } NazaraError("Parameter value is not representable as a integer"); return false; } bool NzParameterList::GetParameterType(const NzString& name, nzParameterType* type) const { auto it = m_parameters.find(name); if (it == m_parameters.end()) return false; *type = it->second.type; return true; } bool NzParameterList::GetPointerParameter(const NzString& name, void** value) const { auto it = m_parameters.find(name); if (it == m_parameters.end()) { NazaraError("Parameter \"" + name + "\" is not present"); return false; } switch (it->second.type) { case nzParameterType_Pointer: *value = it->second.value.ptrVal; return true; case nzParameterType_Userdata: *value = it->second.value.userdataVal->ptr; return true; case nzParameterType_Boolean: case nzParameterType_Float: case nzParameterType_Integer: case nzParameterType_None: case nzParameterType_String: break; } NazaraError("Parameter value is not a pointer"); return false; } bool NzParameterList::GetStringParameter(const NzString& name, NzString* value) const { auto it = m_parameters.find(name); if (it == m_parameters.end()) { NazaraError("Parameter \"" + name + "\" is not present"); return false; } switch (it->second.type) { case nzParameterType_Boolean: *value = NzString::Boolean(it->second.value.boolVal); return true; case nzParameterType_Float: *value = NzString::Number(it->second.value.floatVal); return true; case nzParameterType_Integer: *value = NzString::Number(it->second.value.intVal); return true; case nzParameterType_String: *value = it->second.value.stringVal; return true; case nzParameterType_Pointer: *value = NzString::Pointer(it->second.value.ptrVal); return true; case nzParameterType_Userdata: *value = NzString::Pointer(it->second.value.userdataVal->ptr); return true; case nzParameterType_None: *value = NzString(); return true; } NazaraInternalError("Parameter value is not valid"); return false; } bool NzParameterList::GetUserdataParameter(const NzString& name, void** value) const { auto it = m_parameters.find(name); if (it == m_parameters.end()) { NazaraError("Parameter \"" + name + "\" is not present"); return false; } if (it->second.type == nzParameterType_Userdata) { *value = it->second.value.userdataVal->ptr; return true; } else { NazaraError("Parameter value is not a userdata"); return false; } } bool NzParameterList::HasParameter(const NzString& name) const { return m_parameters.find(name) != m_parameters.end(); } void NzParameterList::RemoveParameter(const NzString& name) { auto it = m_parameters.find(name); if (it != m_parameters.end()) { DestroyValue(it->second); m_parameters.erase(it); } } void NzParameterList::SetParameter(const NzString& name) { std::pair<ParameterMap::iterator, bool> pair = m_parameters.insert(std::make_pair(name, Parameter())); Parameter& parameter = pair.first->second; if (!pair.second) DestroyValue(parameter); parameter.type = nzParameterType_None; } void NzParameterList::SetParameter(const NzString& name, const NzString& value) { std::pair<ParameterMap::iterator, bool> pair = m_parameters.insert(std::make_pair(name, Parameter())); Parameter& parameter = pair.first->second; if (!pair.second) DestroyValue(parameter); parameter.type = nzParameterType_String; NzPlacementNew<NzString>(&parameter.value.stringVal, value); } void NzParameterList::SetParameter(const NzString& name, const char* value) { std::pair<ParameterMap::iterator, bool> pair = m_parameters.insert(std::make_pair(name, Parameter())); Parameter& parameter = pair.first->second; if (!pair.second) DestroyValue(parameter); parameter.type = nzParameterType_String; NzPlacementNew<NzString>(&parameter.value.stringVal, value); } void NzParameterList::SetParameter(const NzString& name, void* value) { std::pair<ParameterMap::iterator, bool> pair = m_parameters.insert(std::make_pair(name, Parameter())); Parameter& parameter = pair.first->second; if (!pair.second) DestroyValue(parameter); parameter.type = nzParameterType_Pointer; parameter.value.ptrVal = value; } void NzParameterList::SetParameter(const NzString& name, void* value, Destructor destructor) { std::pair<ParameterMap::iterator, bool> pair = m_parameters.insert(std::make_pair(name, Parameter())); Parameter& parameter = pair.first->second; if (!pair.second) DestroyValue(parameter); parameter.type = nzParameterType_Userdata; parameter.value.userdataVal = new Parameter::UserdataValue(destructor, value); } void NzParameterList::SetParameter(const NzString& name, bool value) { std::pair<ParameterMap::iterator, bool> pair = m_parameters.insert(std::make_pair(name, Parameter())); Parameter& parameter = pair.first->second; if (!pair.second) DestroyValue(parameter); parameter.type = nzParameterType_Boolean; parameter.value.boolVal = value; } void NzParameterList::SetParameter(const NzString& name, float value) { std::pair<ParameterMap::iterator, bool> pair = m_parameters.insert(std::make_pair(name, Parameter())); Parameter& parameter = pair.first->second; if (!pair.second) DestroyValue(parameter); parameter.type = nzParameterType_Float; parameter.value.floatVal = value; } void NzParameterList::SetParameter(const NzString& name, int value) { std::pair<ParameterMap::iterator, bool> pair = m_parameters.insert(std::make_pair(name, Parameter())); Parameter& parameter = pair.first->second; if (!pair.second) DestroyValue(parameter); parameter.type = nzParameterType_Integer; parameter.value.intVal = value; } NzParameterList& NzParameterList::operator=(const NzParameterList& list) { Clear(); for (auto it = list.m_parameters.begin(); it != list.m_parameters.end(); ++it) { Parameter& parameter = m_parameters[it->first]; switch (it->second.type) { case nzParameterType_Boolean: case nzParameterType_Float: case nzParameterType_Integer: case nzParameterType_Pointer: std::memcpy(&parameter, &it->second, sizeof(Parameter)); break; case nzParameterType_String: parameter.type = nzParameterType_String; NzPlacementNew<NzString>(&parameter.value.stringVal, it->second.value.stringVal); break; case nzParameterType_Userdata: parameter.type = nzParameterType_Userdata; parameter.value.userdataVal = it->second.value.userdataVal; ++(parameter.value.userdataVal->counter); break; case nzParameterType_None: parameter.type = nzParameterType_None; break; } } return *this; } NzParameterList& NzParameterList::operator=(NzParameterList&& list) { m_parameters = std::move(list.m_parameters); return *this; } void NzParameterList::DestroyValue(Parameter& parameter) { switch (parameter.type) { case nzParameterType_String: parameter.value.stringVal.~NzString(); break; case nzParameterType_Userdata: { Parameter::UserdataValue* userdata = parameter.value.userdataVal; if (--userdata->counter == 0) { userdata->destructor(userdata->ptr); delete userdata; } break; } case nzParameterType_Boolean: case nzParameterType_Float: case nzParameterType_Integer: case nzParameterType_None: case nzParameterType_Pointer: break; } } <|endoftext|>
<commit_before>// Copyright (C) 2012 Jérôme Leclercq // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Core/TaskScheduler.hpp> #include <Nazara/Core/ConditionVariable.hpp> #include <Nazara/Core/Error.hpp> #include <Nazara/Core/LockGuard.hpp> #include <Nazara/Core/Mutex.hpp> #include <Nazara/Core/Thread.hpp> #include <queue> #include <vector> #include <Nazara/Core/Debug.hpp> namespace { struct TaskSchedulerImpl { std::queue<NzFunctor*> tasks; std::vector<NzThread*> workers; NzConditionVariable waiterConditionVariable; NzConditionVariable workerConditionVariable; NzMutex taskMutex; NzMutex waiterConditionVariableMutex; NzMutex workerConditionVariableMutex; volatile bool running = true; }; TaskSchedulerImpl* s_impl = nullptr; void WorkerFunc() { do { NzFunctor* task; { NzLockGuard lock(s_impl->taskMutex); if (!s_impl->tasks.empty()) { task = s_impl->tasks.front(); s_impl->tasks.pop(); } else task = nullptr; } // Avons-nous une tâche ? if (task) task->Run(); // Chouette ! Allons travailler gaiement else { // On peut signaler à tout le monde qu'il n'y a plus de tâches s_impl->waiterConditionVariableMutex.Lock(); s_impl->waiterConditionVariable.SignalAll(); s_impl->waiterConditionVariableMutex.Unlock(); // Nous attendons qu'une nouvelle tâche arrive s_impl->workerConditionVariableMutex.Lock(); s_impl->workerConditionVariable.Wait(&s_impl->workerConditionVariableMutex); s_impl->workerConditionVariableMutex.Unlock(); } } while (s_impl->running); } } unsigned int NzTaskScheduler::GetWorkerCount() { #ifdef NAZARA_CORE_SAFE if (!s_impl) { NazaraError("Task scheduler is not initialized"); return 0; } #endif return s_impl->workers.size(); } bool NzTaskScheduler::Initialize() { if (s_impl) return true; // Déjà initialisé s_impl = new TaskSchedulerImpl; unsigned int workerCount = NzThread::HardwareConcurrency(); for (unsigned int i = 0; i < workerCount; ++i) { NzThread* thread = new NzThread(WorkerFunc); s_impl->workers.push_back(thread); } return true; } void NzTaskScheduler::Uninitialize() { if (s_impl) { s_impl->running = false; s_impl->workerConditionVariableMutex.Lock(); s_impl->workerConditionVariable.SignalAll(); s_impl->workerConditionVariableMutex.Unlock(); for (NzThread* thread : s_impl->workers) { thread->Join(); delete thread; } delete s_impl; } } void NzTaskScheduler::WaitForTasks() { #ifdef NAZARA_CORE_SAFE if (!s_impl) { NazaraError("Task scheduler is not initialized"); return; } #endif s_impl->taskMutex.Lock(); // Tout d'abord, il y a-t-il des tâches en attente ? if (s_impl->tasks.empty()) { s_impl->taskMutex.Unlock(); return; } // On verrouille d'abord la mutex entourant le signal (Pour ne pas perdre le signal en chemin) s_impl->waiterConditionVariableMutex.Lock(); // Et ensuite seulement on déverrouille la mutex des tâches s_impl->taskMutex.Unlock(); s_impl->waiterConditionVariable.Wait(&s_impl->waiterConditionVariableMutex); s_impl->waiterConditionVariableMutex.Unlock(); } void NzTaskScheduler::AddTaskFunctor(NzFunctor* taskFunctor) { #ifdef NAZARA_CORE_SAFE if (!s_impl) { NazaraError("Task scheduler is not initialized"); return; } #endif { NzLockGuard lock(s_impl->taskMutex); s_impl->tasks.push(taskFunctor); } s_impl->workerConditionVariableMutex.Lock(); s_impl->workerConditionVariable.Signal(); s_impl->workerConditionVariableMutex.Unlock(); } <commit_msg>Fixed TaskScheduler not resetting impl pointer<commit_after>// Copyright (C) 2012 Jérôme Leclercq // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Core/TaskScheduler.hpp> #include <Nazara/Core/ConditionVariable.hpp> #include <Nazara/Core/Error.hpp> #include <Nazara/Core/LockGuard.hpp> #include <Nazara/Core/Mutex.hpp> #include <Nazara/Core/Thread.hpp> #include <queue> #include <vector> #include <Nazara/Core/Debug.hpp> namespace { struct TaskSchedulerImpl { std::queue<NzFunctor*> tasks; std::vector<NzThread*> workers; NzConditionVariable waiterConditionVariable; NzConditionVariable workerConditionVariable; NzMutex taskMutex; NzMutex waiterConditionVariableMutex; NzMutex workerConditionVariableMutex; volatile bool running = true; }; TaskSchedulerImpl* s_impl = nullptr; void WorkerFunc() { do { NzFunctor* task; { NzLockGuard lock(s_impl->taskMutex); if (!s_impl->tasks.empty()) { task = s_impl->tasks.front(); s_impl->tasks.pop(); } else task = nullptr; } // Avons-nous une tâche ? if (task) task->Run(); // Chouette ! Allons travailler gaiement else { // On peut signaler à tout le monde qu'il n'y a plus de tâches s_impl->waiterConditionVariableMutex.Lock(); s_impl->waiterConditionVariable.SignalAll(); s_impl->waiterConditionVariableMutex.Unlock(); // Nous attendons qu'une nouvelle tâche arrive s_impl->workerConditionVariableMutex.Lock(); s_impl->workerConditionVariable.Wait(&s_impl->workerConditionVariableMutex); s_impl->workerConditionVariableMutex.Unlock(); } } while (s_impl->running); } } unsigned int NzTaskScheduler::GetWorkerCount() { #ifdef NAZARA_CORE_SAFE if (!s_impl) { NazaraError("Task scheduler is not initialized"); return 0; } #endif return s_impl->workers.size(); } bool NzTaskScheduler::Initialize() { if (s_impl) return true; // Déjà initialisé s_impl = new TaskSchedulerImpl; unsigned int workerCount = NzThread::HardwareConcurrency(); for (unsigned int i = 0; i < workerCount; ++i) { NzThread* thread = new NzThread(WorkerFunc); s_impl->workers.push_back(thread); } return true; } void NzTaskScheduler::Uninitialize() { if (s_impl) { s_impl->running = false; s_impl->workerConditionVariableMutex.Lock(); s_impl->workerConditionVariable.SignalAll(); s_impl->workerConditionVariableMutex.Unlock(); for (NzThread* thread : s_impl->workers) { thread->Join(); delete thread; } delete s_impl; s_impl = nullptr; } } void NzTaskScheduler::WaitForTasks() { #ifdef NAZARA_CORE_SAFE if (!s_impl) { NazaraError("Task scheduler is not initialized"); return; } #endif s_impl->taskMutex.Lock(); // Tout d'abord, il y a-t-il des tâches en attente ? if (s_impl->tasks.empty()) { s_impl->taskMutex.Unlock(); return; } // On verrouille d'abord la mutex entourant le signal (Pour ne pas perdre le signal en chemin) s_impl->waiterConditionVariableMutex.Lock(); // Et ensuite seulement on déverrouille la mutex des tâches s_impl->taskMutex.Unlock(); s_impl->waiterConditionVariable.Wait(&s_impl->waiterConditionVariableMutex); s_impl->waiterConditionVariableMutex.Unlock(); } void NzTaskScheduler::AddTaskFunctor(NzFunctor* taskFunctor) { #ifdef NAZARA_CORE_SAFE if (!s_impl) { NazaraError("Task scheduler is not initialized"); return; } #endif { NzLockGuard lock(s_impl->taskMutex); s_impl->tasks.push(taskFunctor); } s_impl->workerConditionVariableMutex.Lock(); s_impl->workerConditionVariable.Signal(); s_impl->workerConditionVariableMutex.Unlock(); } <|endoftext|>
<commit_before>#include "PatternMatch.hpp" bool patternMatch (uint64_t startwall, patternlist startpattern, const wallgraphvector& wallgraphptr ) { typedef std::pair<uint64_t,patternlist> wallpair; std::deque<wallpair> nodes_to_visit; wallpair root = std::make_pair(startwall,startpattern); nodes_to_visit.push_front(root); while ( !(nodes_to_visit.empty()) ) { // std::cout << "New while: \n"; // for (auto p : nodes_to_visit) { // std::cout << p.first << "\n"; // } // std::cout << "\n"; wallpair currentpair = nodes_to_visit.front(); nodes_to_visit.pop_front(); auto wall = currentpair.first; auto pattern = currentpair.second; if ( pattern.empty() ) { return true; } auto extremum = pattern.front(); auto intermediate = pattern.front(); std::replace(intermediate.begin(),intermediate.end(),'M','I'); std::replace(intermediate.begin(),intermediate.end(),'m','D'); // std::cout << "extremum: " << extremum << ", intermediate: " << intermediate << "\n"; auto walllabels = wallgraphptr[ wall ].labels; bool extremum_in_labels = true; bool intermediate_in_labels = true; for ( int i = 0; i < walllabels.size(); ++i ) { if ( walllabels[ i ].count( extremum[ i ] ) == 0) { extremum_in_labels = false; } if ( walllabels[ i ].count( intermediate[ i ] ) == 0) { intermediate_in_labels = false; } if ( !extremum_in_labels && !intermediate_in_labels ) { break; } } if ( !extremum_in_labels && !intermediate_in_labels ) { continue; } auto outedges = wallgraphptr[ wall ].outedges; auto patterntail = pattern; patterntail.pop_front(); if ( intermediate_in_labels ) { for ( auto nextwallindex : outedges) { nodes_to_visit.push_front( std::make_pair( nextwallindex, pattern ) ); } } if ( extremum_in_labels ) { for ( auto nextwallindex : outedges) { nodes_to_visit.push_front( std::make_pair( nextwallindex, patterntail ) ); } } } return false; } // boost::unordered_map memoize = {}; // bool recursePattern (uint64_t currentwallindex, patternlist pattern, const wallgraphvector& wallgraphptr, const bool boolflag = true ) { // // memoize should be member of class // // wallgraph should be member of class // static bool foundmatch = false; // std::pair<uint64_t,patternlist> key (currentwallindex,pattern); // if ( !(memoize.count(key)) ) { // if ( pattern.empty() ) { // if ( boolflag ) { // return true; // } else { // foundmatch = true; // memoize[key] = true; // } // } else { // auto extremum = pattern.front(); // auto intermediate = pattern.front(); // std::replace(intermediate.begin(),intermediate.end(),'M','I') // std::replace(intermediate.begin(),intermediate.end(),'m','D') // auto walllabels = wallgraphptr[ currentwallindex ].walllabels; // bool extremum_in_labels = true; // bool intermediate_in_labels = true; // for ( int i = 0; i < walllabels.size(); ++i ) { // if ( walllabels[ i ].count( extremum[ i ] ) == 0) { // extremum_in_labels = false; // } // if ( walllabels[ i ].count( intermediate[ i ] ) == 0) { // intermediate_in_labels = false; // } // if ( !extremum_in_labels && !intermediate_in_labels ) { // memoize[key] = false; // break; // } // } // auto outedges = wallgraphptr[ currentwallindex ].outedges; // auto patterntail = pattern; // patterntail.pop_front(); // if ( extremum_in_labels ) { // for ( auto nextwallindex : outedges) { // if ( recursePattern( nextwallindex, patterntail, wallgraphptr ) ) { // if ( boolflag ) { // return true; // } else { // foundmatch = true; // memoize[key] = true; // } // } // else, keep recursing // } // } // if ( intermediate_in_labels ) { // for ( auto nextwallindex : outedges) { // if ( recursePattern( nextwallindex, pattern, wallgraphptr ) ) { // if ( boolflag ) { // return true; // } else { // foundmatch = true; // memoize[key] = true; // } // } // else, keep recursing // } // } // } // return foundmatch; // } // } // void printMatch( std::list<uint64_t> match ) { // for ( auto m : match ) { // std::cout << m << " "; // } // std::cout << "\n"; // } // std::list<uint64_t> match recursePattern_withmatch (uint64_t currentwallindex, patternlist pattern, const wallgraphvector& wallgraphptr, std::list<uint64_t> match) { // if ( pattern.empty() ) { // std::cout << "HAVE MATCH!!\n"; // printMatch( match ); // return true; // } else { // auto extremum = ( pattern.front() ).extremum; // auto intermediate = ( pattern.front() ).intermediate; // auto walllabels = wallgraphptr[ currentwallindex ].walllabels; // bool extremum_in_labels = ( std::find(walllabels.begin(), walllabels.end(), extremum) != walllabels.end() ); // bool intermediate_in_labels = ( std::find(walllabels.begin(), walllabels.end(), intermediate) != walllabels.end() ); // auto outedges = wallgraphptr[ currentwallindex ].outedges; // auto patterntail = pattern; // patterntail.pop_front(); // match.push_back( currentwallindex ); // if ( extremum_in_labels ) { // for ( auto nextwallindex : outedges) { // if ( recursePattern_withmatch( nextwallindex, patterntail, wallgraphptr, match ) ) { // return true; // } // else, keep recursing // } // } // if ( intermediate_in_labels ) { // for ( auto nextwallindex : outedges) { // if ( recursePattern_withmatch( nextwallindex, pattern, wallgraphptr, match ) ) { // return true; // } // else, keep recursing // } // } // } // // std::cout << "fall out\n"; // return false; // } <commit_msg>memoization partly implemented<commit_after>#include "PatternMatch.hpp" bool patternMatch (uint64_t startwall, patternlist startpattern, const wallgraphvector& wallgraphptr ) { typedef std::pair<uint64_t,patternlist> wallpair; std::deque<wallpair> nodes_to_visit; nodes_to_visit.push_front( std::make_pair(startwall,startpattern) ); // // memoize should be member of class // // wallgraph should be member of class while ( !(nodes_to_visit.empty()) ) { // std::cout << "New while: \n"; // for (auto p : nodes_to_visit) { // std::cout << p.first << "\n"; // } // std::cout << "\n"; wallpair node = nodes_to_visit.front(); nodes_to_visit.pop_front(); auto wall = node.first; auto pattern = node.second; if ( pattern.empty() ) { return true; } auto extremum = pattern.front(); auto intermediate = pattern.front(); std::replace(intermediate.begin(),intermediate.end(),'M','I'); std::replace(intermediate.begin(),intermediate.end(),'m','D'); // std::cout << "extremum: " << extremum << ", intermediate: " << intermediate << "\n"; auto walllabels = wallgraphptr[ wall ].labels; bool extremum_in_labels = true; bool intermediate_in_labels = true; for ( int i = 0; i < walllabels.size(); ++i ) { if ( walllabels[ i ].count( extremum[ i ] ) == 0) { extremum_in_labels = false; } if ( walllabels[ i ].count( intermediate[ i ] ) == 0) { intermediate_in_labels = false; } if ( !extremum_in_labels && !intermediate_in_labels ) { break; } } if ( !extremum_in_labels && !intermediate_in_labels ) { continue; } auto outedges = wallgraphptr[ wall ].outedges; auto patterntail = pattern; patterntail.pop_front(); if ( intermediate_in_labels ) { for ( auto nextwallindex : outedges) { nodes_to_visit.push_front( std::make_pair( nextwallindex, pattern ) ); } } if ( extremum_in_labels ) { for ( auto nextwallindex : outedges) { nodes_to_visit.push_front( std::make_pair( nextwallindex, patterntail ) ); } } } return false; } boost::unordered_map memoize; bool patternMatch (uint64_t startwall, patternlist startpattern, const wallgraphvector& wallgraphptr ) { bool foundmatch = false; typedef std::pair<uint64_t,patternlist> wallpair; std::deque<wallpair> nodes_to_visit; nodes_to_visit.push_front( std::make_pair(startwall,startpattern) ); void addToStack (bool x, patternlist p); // // memoize should be member of class // // wallgraph should be member of class while ( !nodes_to_visit.empty() ) { wallpair key = nodes_to_visit.front(); nodes_to_visit.pop_front(); if ( memoize.count( key ) ) { continue; } if ( pattern.empty() ) { memoize[ key ] = true; foundmatch = true; continue; } auto wall = key.first; auto pattern = key.second; auto extremum = pattern.front(); auto intermediate = pattern.front(); std::replace(intermediate.begin(),intermediate.end(),'M','I'); std::replace(intermediate.begin(),intermediate.end(),'m','D'); auto walllabels = wallgraphptr[ wall ].labels; bool extremum_in_labels = true; bool intermediate_in_labels = true; for ( int i = 0; i < walllabels.size(); ++i ) { if ( walllabels[ i ].count( extremum[ i ] ) == 0) { extremum_in_labels = false; } if ( walllabels[ i ].count( intermediate[ i ] ) == 0) { intermediate_in_labels = false; } if ( !extremum_in_labels && !intermediate_in_labels ) { break; } } if ( !extremum_in_labels && !intermediate_in_labels ) { memoize[ key ] = false; continue; } auto outedges = wallgraphptr[ wall ].outedges; auto patterntail = pattern; patterntail.pop_front(); addToStack( intermediate_in_labels, pattern ) addToStack( extremum_in_labels, patterntail ) void addToStack (bool x, patternlist p) { bool doassign = true; std::list<bool> truthvalues = {}; wallpair new_node; if ( x ) { for ( auto nextwall : outedges) { new_node = std::make_pair( nextwall, p ); if ( !memoize.count( key ) ) { doassign = false; nodes_to_visit.push_front( new_node ); } else { truthvalues.push_back( memoize.count( key ) ); } } if ( doassign ) { memoize[ key ] = ( std::find( truthvalues.begin(), truthvalues.end(), true ) != truthvalues.end() ); } } } } return foundmatch; } // bool recursePattern (uint64_t currentwallindex, patternlist pattern, const wallgraphvector& wallgraphptr, const bool boolflag = true ) { // // memoize should be member of class // // wallgraph should be member of class // static bool foundmatch = false; // std::pair<uint64_t,patternlist> key (currentwallindex,pattern); // if ( !(memoize.count(key)) ) { // if ( pattern.empty() ) { // if ( boolflag ) { // return true; // } else { // foundmatch = true; // memoize[key] = true; // } // } else { // auto extremum = pattern.front(); // auto intermediate = pattern.front(); // std::replace(intermediate.begin(),intermediate.end(),'M','I') // std::replace(intermediate.begin(),intermediate.end(),'m','D') // auto walllabels = wallgraphptr[ currentwallindex ].walllabels; // bool extremum_in_labels = true; // bool intermediate_in_labels = true; // for ( int i = 0; i < walllabels.size(); ++i ) { // if ( walllabels[ i ].count( extremum[ i ] ) == 0) { // extremum_in_labels = false; // } // if ( walllabels[ i ].count( intermediate[ i ] ) == 0) { // intermediate_in_labels = false; // } // if ( !extremum_in_labels && !intermediate_in_labels ) { // memoize[key] = false; // break; // } // } // auto outedges = wallgraphptr[ currentwallindex ].outedges; // auto patterntail = pattern; // patterntail.pop_front(); // if ( extremum_in_labels ) { // for ( auto nextwallindex : outedges) { // if ( recursePattern( nextwallindex, patterntail, wallgraphptr ) ) { // if ( boolflag ) { // return true; // } else { // foundmatch = true; // memoize[key] = true; // } // } // else, keep recursing // } // } // if ( intermediate_in_labels ) { // for ( auto nextwallindex : outedges) { // if ( recursePattern( nextwallindex, pattern, wallgraphptr ) ) { // if ( boolflag ) { // return true; // } else { // foundmatch = true; // memoize[key] = true; // } // } // else, keep recursing // } // } // } // return foundmatch; // } // } // void printMatch( std::list<uint64_t> match ) { // for ( auto m : match ) { // std::cout << m << " "; // } // std::cout << "\n"; // } // std::list<uint64_t> match recursePattern_withmatch (uint64_t currentwallindex, patternlist pattern, const wallgraphvector& wallgraphptr, std::list<uint64_t> match) { // if ( pattern.empty() ) { // std::cout << "HAVE MATCH!!\n"; // printMatch( match ); // return true; // } else { // auto extremum = ( pattern.front() ).extremum; // auto intermediate = ( pattern.front() ).intermediate; // auto walllabels = wallgraphptr[ currentwallindex ].walllabels; // bool extremum_in_labels = ( std::find(walllabels.begin(), walllabels.end(), extremum) != walllabels.end() ); // bool intermediate_in_labels = ( std::find(walllabels.begin(), walllabels.end(), intermediate) != walllabels.end() ); // auto outedges = wallgraphptr[ currentwallindex ].outedges; // auto patterntail = pattern; // patterntail.pop_front(); // match.push_back( currentwallindex ); // if ( extremum_in_labels ) { // for ( auto nextwallindex : outedges) { // if ( recursePattern_withmatch( nextwallindex, patterntail, wallgraphptr, match ) ) { // return true; // } // else, keep recursing // } // } // if ( intermediate_in_labels ) { // for ( auto nextwallindex : outedges) { // if ( recursePattern_withmatch( nextwallindex, pattern, wallgraphptr, match ) ) { // return true; // } // else, keep recursing // } // } // } // // std::cout << "fall out\n"; // return false; // } <|endoftext|>
<commit_before>/* ********************************************************** * Copyright (c) 2007-2008 VMware, Inc. All rights reserved. * **********************************************************/ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of VMware, Inc. nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ /* Copyright (c) 2003-2007 Determina Corp. */ /* Copyright (c) 2002-2003 Massachusetts Institute of Technology */ /* Copyright (c) 2002 Hewlett-Packard Company */ // ShellInterface.cpp: implementation of the CShellInterface class. // ////////////////////////////////////////////////////////////////////// #ifndef DYNAMORIO_DEMO /* around whole file */ #include "stdafx.h" #include "DynamoRIO.h" #include "ShellInterface.h" #include <shlobj.h> #include <objbase.h> #include <shlwapi.h> #include <assert.h> #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CShellInterface::CShellInterface() { } CShellInterface::~CShellInterface() { } /*static */void CShellInterface::Initialize() { if (m_bInitialized) return; int res = CoInitialize(NULL); assert(res == S_OK); m_bInitialized = TRUE; } /*static */void CShellInterface::Uninitialize() { if (!m_bInitialized) return; CoUninitialize(); m_bInitialized = FALSE; } /*static */BOOL CShellInterface::m_bInitialized = FALSE; /*static */BOOL CShellInterface::ResolveLinkFile(TCHAR *name, TCHAR *resolution, TCHAR *arguments, TCHAR *working_dir, HWND hwnd) { assert(m_bInitialized); HRESULT hres; IShellLink* psl; WIN32_FIND_DATA wfd; *resolution = 0; // assume failure // Get a pointer to the IShellLink interface. hres = CoCreateInstance (CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void **)&psl); if (SUCCEEDED (hres)) { IPersistFile *ppf; // Get a pointer to the IPersistFile interface. hres = psl->QueryInterface (IID_IPersistFile, (void **)&ppf); if (SUCCEEDED (hres)) { #ifndef UNICODE WORD wsz [MAX_PATH]; // buffer for Unicode string // Ensure that the string consists of Unicode TCHARacters. MultiByteToWideChar(CP_ACP, 0, name, -1, wsz, MAX_PATH); #else TCHAR *wsz = name; #endif // Load the shortcut. hres = ppf->Load(wsz, STGM_READ); if (SUCCEEDED(hres)) { // Resolve the shortcut. hres = psl->Resolve(hwnd, SLR_ANY_MATCH); if (SUCCEEDED(hres)) { _tcscpy(resolution, name); // Get the path to the shortcut target. hres = psl->GetPath(resolution, MAX_PATH, (WIN32_FIND_DATA *)&wfd, SLGP_SHORTPATH); if (! SUCCEEDED(hres)) goto cleanup; hres = psl->GetArguments(arguments, MAX_PATH); if (! SUCCEEDED(hres)) goto cleanup; hres = psl->GetWorkingDirectory(working_dir, MAX_PATH); if (! SUCCEEDED(hres)) goto cleanup; } } cleanup: // Release the pointer to IPersistFile. ppf->Release (); } // Release the pointer to IShellLink. psl->Release (); } return (SUCCEEDED(hres) ? TRUE : FALSE); } #if 0 // from "Shell Links" in MSDN library: /* The application-defined ResolveIt function in the following example resolves a shortcut. Its parameters include a window handle, a pointer to the path of the shortcut, and the address of a buffer that receives the new path to the object. The window handle identifies the parent window for any message boxes that the shell may need to display. For example, the shell can display a message box if the link is on unshared media, if network problems occur, if the user needs to insert a floppy disk, and so on. The ResolveIt function calls theCoCreateInstance function and assumes that theCoInitialize function has already been called. Note that ResolveIt needs to use theIPersistFile interface to store the link information. IPersistFile is implemented by the IShellLink object. The link information must be loaded before the path information is retrieved, which is shown later in the example. Failing to load the link information causes the calls to the IShellLink::GetPath and IShellLink::GetDescription member functions to fail. */ HRESULT ResolveIt(HWND hwnd, LPCSTR lpszLinkFile, LPSTR lpszPath) { HRESULT hres; IShellLink* psl; TCHAR szGotPath[MAX_PATH]; TCHAR szDescription[MAX_PATH]; WIN32_FIND_DATA wfd; *lpszPath = 0; // assume failure // Get a pointer to the IShellLink interface. hres = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, &IID_IShellLink, &psl); if (SUCCEEDED(hres)) { IPersistFile* ppf; // Get a pointer to the IPersistFile interface. hres = psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile, &ppf); if (SUCCEEDED(hres)) { WORD wsz[MAX_PATH]; // Ensure that the string is Unicode. MultiByteToWideChar(CP_ACP, 0, lpszLinkFile, -1, wsz, MAX_PATH); // Load the shortcut. hres = ppf->lpVtbl->Load(ppf, wsz, STGM_READ); if (SUCCEEDED(hres)) { // Resolve the link. hres = psl->lpVtbl->Resolve(psl, hwnd, SLR_ANY_MATCH); if (SUCCEEDED(hres)) { // Get the path to the link target. hres = psl->lpVtbl->GetPath(psl, szGotPath, MAX_PATH, (WIN32_FIND_DATA *)&wfd, SLGP_SHORTPATH ); if (!SUCCEEDED(hres)) HandleErr(hres); // application-defined function // Get the description of the target. hres = psl->lpVtbl->GetDescription(psl, szDescription, MAX_PATH); if (!SUCCEEDED(hres)) HandleErr(hres); lstrcpy(lpszPath, szGotPath); } } // Release the pointer to the IPersistFile interface. ppf->lpVtbl->Release(ppf); } // Release the pointer to the IShellLink interface. psl->lpVtbl->Release(psl); } return hres; } /* From MSDN's MFC sample: "SHORTCUT: A SampleThat Manipulates Shortcuts" */ HRESULT CreateShortCut::CreateIt (LPCSTR pszShortcutFile, LPSTR pszLink, LPSTR pszDesc) { HRESULT hres; IShellLink *psl; // Create an IShellLink object and get a pointer to the IShellLink // interface (returned from CoCreateInstance). hres = CoCreateInstance (CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void **)&psl); if (SUCCEEDED (hres)) { IPersistFile *ppf; // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. hres = psl->QueryInterface (IID_IPersistFile, (void **)&ppf); if (SUCCEEDED (hres)) { WORD wsz [MAX_PATH]; // buffer for Unicode string // Set the path to the shortcut target. hres = psl->SetPath (pszShortcutFile); if (! SUCCEEDED (hres)) AfxMessageBox ("SetPath failed!"); // Set the description of the shortcut. hres = psl->SetDescription (pszDesc); if (! SUCCEEDED (hres)) AfxMessageBox ("SetDescription failed!"); // Ensure that the string consists of ANSI TCHARacters. MultiByteToWideChar (CP_ACP, 0, pszLink, -1, wsz, MAX_PATH); // Save the shortcut via the IPersistFile::Save member function. hres = ppf->Save (wsz, TRUE); if (! SUCCEEDED (hres)) AfxMessageBox (Save failed!); // Release the pointer to IPersistFile. ppf->Release (); } // Release the pointer to IShellLink. psl->Release (); } return hres; } void ResolveShortCut::OnOK () { TCHAR szFile [MAX_PATH]; // Get the selected item in the list box. DlgDirSelect (szFile, IDC_LIST1); // Find out whether it is a LNK file. if (_tcsstr (szFile, ".lnk") != NULL) // Make the call to ResolveShortcut::ResolveIt here. ResolveIt (m_hWnd, szFile); CDialog::OnOK (); } HRESULT ResolveShortCut::ResolveIt (HWND hwnd, LPCSTR pszShortcutFile) { HRESULT hres; IShellLink *psl; TCHAR szGotPath [MAX_PATH]; TCHAR szDescription [MAX_PATH]; WIN32_FIND_DATA wfd; // Get a pointer to the IShellLink interface. hres = CoCreateInstance (CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void **)&psl); if (SUCCEEDED (hres)) { IPersistFile *ppf; // Get a pointer to the IPersistFile interface. hres = psl->QueryInterface (IID_IPersistFile, (void **)&ppf); if (SUCCEEDED (hres)) { WORD wsz [MAX_PATH]; // buffer for Unicode string // Ensure that the string consists of Unicode TCHARacters. MultiByteToWideChar (CP_ACP, 0, pszShortcutFile, -1, wsz, MAX_PATH); // Load the shortcut. hres = ppf->Load (wsz, STGM_READ); if (SUCCEEDED (hres)) { // Resolve the shortcut. hres = psl->Resolve (hwnd, SLR_ANY_MATCH); if (SUCCEEDED (hres)) { _tcscpy (szGotPath, pszShortcutFile); // Get the path to the shortcut target. hres = psl->GetPath (szGotPath, MAX_PATH, (WIN32_FIND_DATA *)&wfd, SLGP_SHORTPATH); if (! SUCCEEDED (hres)) AfxMessageBox ("GetPath failed!"); else AfxMessageBox (szGotPath); // Get the description of the target. hres = psl->GetDescription (szDescription, MAX_PATH); if (! SUCCEEDED (hres)) AfxMessageBox ("GetDescription failed!"); else AfxMessageBox (szDescription); } } // Release the pointer to IPersistFile. ppf->Release (); } // Release the pointer to IShellLink. psl->Release (); } return hres; } #endif /* 0 */ #endif /* !DYNAMORIO_DEMO */ /* around whole file */ <commit_msg>convert extended-ascii chars to plain quotes<commit_after>/* ********************************************************** * Copyright (c) 2007-2008 VMware, Inc. All rights reserved. * **********************************************************/ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of VMware, Inc. nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ /* Copyright (c) 2003-2007 Determina Corp. */ /* Copyright (c) 2002-2003 Massachusetts Institute of Technology */ /* Copyright (c) 2002 Hewlett-Packard Company */ // ShellInterface.cpp: implementation of the CShellInterface class. // ////////////////////////////////////////////////////////////////////// #ifndef DYNAMORIO_DEMO /* around whole file */ #include "stdafx.h" #include "DynamoRIO.h" #include "ShellInterface.h" #include <shlobj.h> #include <objbase.h> #include <shlwapi.h> #include <assert.h> #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CShellInterface::CShellInterface() { } CShellInterface::~CShellInterface() { } /*static */void CShellInterface::Initialize() { if (m_bInitialized) return; int res = CoInitialize(NULL); assert(res == S_OK); m_bInitialized = TRUE; } /*static */void CShellInterface::Uninitialize() { if (!m_bInitialized) return; CoUninitialize(); m_bInitialized = FALSE; } /*static */BOOL CShellInterface::m_bInitialized = FALSE; /*static */BOOL CShellInterface::ResolveLinkFile(TCHAR *name, TCHAR *resolution, TCHAR *arguments, TCHAR *working_dir, HWND hwnd) { assert(m_bInitialized); HRESULT hres; IShellLink* psl; WIN32_FIND_DATA wfd; *resolution = 0; // assume failure // Get a pointer to the IShellLink interface. hres = CoCreateInstance (CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void **)&psl); if (SUCCEEDED (hres)) { IPersistFile *ppf; // Get a pointer to the IPersistFile interface. hres = psl->QueryInterface (IID_IPersistFile, (void **)&ppf); if (SUCCEEDED (hres)) { #ifndef UNICODE WORD wsz [MAX_PATH]; // buffer for Unicode string // Ensure that the string consists of Unicode TCHARacters. MultiByteToWideChar(CP_ACP, 0, name, -1, wsz, MAX_PATH); #else TCHAR *wsz = name; #endif // Load the shortcut. hres = ppf->Load(wsz, STGM_READ); if (SUCCEEDED(hres)) { // Resolve the shortcut. hres = psl->Resolve(hwnd, SLR_ANY_MATCH); if (SUCCEEDED(hres)) { _tcscpy(resolution, name); // Get the path to the shortcut target. hres = psl->GetPath(resolution, MAX_PATH, (WIN32_FIND_DATA *)&wfd, SLGP_SHORTPATH); if (! SUCCEEDED(hres)) goto cleanup; hres = psl->GetArguments(arguments, MAX_PATH); if (! SUCCEEDED(hres)) goto cleanup; hres = psl->GetWorkingDirectory(working_dir, MAX_PATH); if (! SUCCEEDED(hres)) goto cleanup; } } cleanup: // Release the pointer to IPersistFile. ppf->Release (); } // Release the pointer to IShellLink. psl->Release (); } return (SUCCEEDED(hres) ? TRUE : FALSE); } #if 0 // from "Shell Links" in MSDN library: /* The application-defined ResolveIt function in the following example resolves a shortcut. Its parameters include a window handle, a pointer to the path of the shortcut, and the address of a buffer that receives the new path to the object. The window handle identifies the parent window for any message boxes that the shell may need to display. For example, the shell can display a message box if the link is on unshared media, if network problems occur, if the user needs to insert a floppy disk, and so on. The ResolveIt function calls theCoCreateInstance function and assumes that theCoInitialize function has already been called. Note that ResolveIt needs to use theIPersistFile interface to store the link information. IPersistFile is implemented by the IShellLink object. The link information must be loaded before the path information is retrieved, which is shown later in the example. Failing to load the link information causes the calls to the IShellLink::GetPath and IShellLink::GetDescription member functions to fail. */ HRESULT ResolveIt(HWND hwnd, LPCSTR lpszLinkFile, LPSTR lpszPath) { HRESULT hres; IShellLink* psl; TCHAR szGotPath[MAX_PATH]; TCHAR szDescription[MAX_PATH]; WIN32_FIND_DATA wfd; *lpszPath = 0; // assume failure // Get a pointer to the IShellLink interface. hres = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, &IID_IShellLink, &psl); if (SUCCEEDED(hres)) { IPersistFile* ppf; // Get a pointer to the IPersistFile interface. hres = psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile, &ppf); if (SUCCEEDED(hres)) { WORD wsz[MAX_PATH]; // Ensure that the string is Unicode. MultiByteToWideChar(CP_ACP, 0, lpszLinkFile, -1, wsz, MAX_PATH); // Load the shortcut. hres = ppf->lpVtbl->Load(ppf, wsz, STGM_READ); if (SUCCEEDED(hres)) { // Resolve the link. hres = psl->lpVtbl->Resolve(psl, hwnd, SLR_ANY_MATCH); if (SUCCEEDED(hres)) { // Get the path to the link target. hres = psl->lpVtbl->GetPath(psl, szGotPath, MAX_PATH, (WIN32_FIND_DATA *)&wfd, SLGP_SHORTPATH ); if (!SUCCEEDED(hres)) HandleErr(hres); // application-defined function // Get the description of the target. hres = psl->lpVtbl->GetDescription(psl, szDescription, MAX_PATH); if (!SUCCEEDED(hres)) HandleErr(hres); lstrcpy(lpszPath, szGotPath); } } // Release the pointer to the IPersistFile interface. ppf->lpVtbl->Release(ppf); } // Release the pointer to the IShellLink interface. psl->lpVtbl->Release(psl); } return hres; } /* From MSDN's MFC sample: "SHORTCUT: A SampleThat Manipulates Shortcuts" */ HRESULT CreateShortCut::CreateIt (LPCSTR pszShortcutFile, LPSTR pszLink, LPSTR pszDesc) { HRESULT hres; IShellLink *psl; // Create an IShellLink object and get a pointer to the IShellLink // interface (returned from CoCreateInstance). hres = CoCreateInstance (CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void **)&psl); if (SUCCEEDED (hres)) { IPersistFile *ppf; // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. hres = psl->QueryInterface (IID_IPersistFile, (void **)&ppf); if (SUCCEEDED (hres)) { WORD wsz [MAX_PATH]; // buffer for Unicode string // Set the path to the shortcut target. hres = psl->SetPath (pszShortcutFile); if (! SUCCEEDED (hres)) AfxMessageBox ("SetPath failed!"); // Set the description of the shortcut. hres = psl->SetDescription (pszDesc); if (! SUCCEEDED (hres)) AfxMessageBox ("SetDescription failed!"); // Ensure that the string consists of ANSI TCHARacters. MultiByteToWideChar (CP_ACP, 0, pszLink, -1, wsz, MAX_PATH); // Save the shortcut via the IPersistFile::Save member function. hres = ppf->Save (wsz, TRUE); if (! SUCCEEDED (hres)) AfxMessageBox ("Save failed!"); // Release the pointer to IPersistFile. ppf->Release (); } // Release the pointer to IShellLink. psl->Release (); } return hres; } void ResolveShortCut::OnOK () { TCHAR szFile [MAX_PATH]; // Get the selected item in the list box. DlgDirSelect (szFile, IDC_LIST1); // Find out whether it is a LNK file. if (_tcsstr (szFile, ".lnk") != NULL) // Make the call to ResolveShortcut::ResolveIt here. ResolveIt (m_hWnd, szFile); CDialog::OnOK (); } HRESULT ResolveShortCut::ResolveIt (HWND hwnd, LPCSTR pszShortcutFile) { HRESULT hres; IShellLink *psl; TCHAR szGotPath [MAX_PATH]; TCHAR szDescription [MAX_PATH]; WIN32_FIND_DATA wfd; // Get a pointer to the IShellLink interface. hres = CoCreateInstance (CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void **)&psl); if (SUCCEEDED (hres)) { IPersistFile *ppf; // Get a pointer to the IPersistFile interface. hres = psl->QueryInterface (IID_IPersistFile, (void **)&ppf); if (SUCCEEDED (hres)) { WORD wsz [MAX_PATH]; // buffer for Unicode string // Ensure that the string consists of Unicode TCHARacters. MultiByteToWideChar (CP_ACP, 0, pszShortcutFile, -1, wsz, MAX_PATH); // Load the shortcut. hres = ppf->Load (wsz, STGM_READ); if (SUCCEEDED (hres)) { // Resolve the shortcut. hres = psl->Resolve (hwnd, SLR_ANY_MATCH); if (SUCCEEDED (hres)) { _tcscpy (szGotPath, pszShortcutFile); // Get the path to the shortcut target. hres = psl->GetPath (szGotPath, MAX_PATH, (WIN32_FIND_DATA *)&wfd, SLGP_SHORTPATH); if (! SUCCEEDED (hres)) AfxMessageBox ("GetPath failed!"); else AfxMessageBox (szGotPath); // Get the description of the target. hres = psl->GetDescription (szDescription, MAX_PATH); if (! SUCCEEDED (hres)) AfxMessageBox ("GetDescription failed!"); else AfxMessageBox (szDescription); } } // Release the pointer to IPersistFile. ppf->Release (); } // Release the pointer to IShellLink. psl->Release (); } return hres; } #endif /* 0 */ #endif /* !DYNAMORIO_DEMO */ /* around whole file */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: so_checksum.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 13:32:32 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "md5.hxx" #include <stdio.h> #include <string.hxx> int main( int argc, char * argv[] ) { for ( int n = 1; n < argc; n++ ) { ByteString aChecksum; rtlDigestError error = calc_md5_checksum( argv[n], aChecksum ); if ( rtl_Digest_E_None == error ) { printf( "%s %s\n", aChecksum.GetBuffer(), argv[n] ); } else printf( "ERROR: Unable to calculate MD5 checksum for %s\n", argv[n] ); } return 0; } <commit_msg>INTEGRATION: CWS pchfix02 (1.4.120); FILE MERGED 2006/09/01 17:54:47 kaib 1.4.120.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: so_checksum.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-17 00:49:37 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_tools.hxx" #include "md5.hxx" #include <stdio.h> #include <string.hxx> int main( int argc, char * argv[] ) { for ( int n = 1; n < argc; n++ ) { ByteString aChecksum; rtlDigestError error = calc_md5_checksum( argv[n], aChecksum ); if ( rtl_Digest_E_None == error ) { printf( "%s %s\n", aChecksum.GetBuffer(), argv[n] ); } else printf( "ERROR: Unable to calculate MD5 checksum for %s\n", argv[n] ); } return 0; } <|endoftext|>
<commit_before>#include "hierarchy.h" #include "core/array.h" #include "core/hash_map.h" #include "core/iserializer.h" #include "core/matrix.h" #include "core/pod_hash_map.h" #include "universe.h" namespace Lumix { class HierarchyImpl : public Hierarchy { private: typedef PODHashMap<int32_t, Array<Child>* > Children; typedef HashMap<int32_t, int32_t> Parents; public: HierarchyImpl(Universe& universe, IAllocator& allocator) : m_universe(universe) , m_parents(allocator) , m_children(allocator) , m_allocator(allocator) , m_parent_set(allocator) { universe.entityMoved().bind<HierarchyImpl, &HierarchyImpl::onEntityMoved>(this); } ~HierarchyImpl() { PODHashMap<int32_t, Array<Child>*>::iterator iter = m_children.begin(), end = m_children.end(); while (iter != end) { m_allocator.deleteObject(iter.value()); ++iter; } } IAllocator& getAllocator() { return m_allocator; } void onEntityMoved(const Entity& entity) { Children::iterator iter = m_children.find(entity.index); if(iter.isValid()) { Matrix parent_matrix = entity.getMatrix(); Array<Child>& children = *iter.value(); for(int i = 0, c = children.size(); i < c; ++i) { Entity e(&m_universe, children[i].m_entity); e.setMatrix(parent_matrix * children[i].m_local_matrix); } } Parents::iterator parent_iter = m_parents.find(entity.index); if(parent_iter.isValid()) { Entity parent(&m_universe, parent_iter.value()); Children::iterator child_iter = m_children.find(parent.index); if(child_iter.isValid()) { Array<Child>& children = *child_iter.value(); for(int i = 0, c = children.size(); i < c; ++i) { if(children[i].m_entity == entity.index) { Matrix inv_parent_matrix = parent.getMatrix(); inv_parent_matrix.inverse(); children[i].m_local_matrix = inv_parent_matrix * entity.getMatrix(); break; } } } } } virtual void setParent(const Entity& child, const Entity& parent) override { Parents::iterator old_parent_iter = m_parents.find(child.index); if(old_parent_iter.isValid()) { Children::iterator child_iter = m_children.find(old_parent_iter.value()); ASSERT(child_iter.isValid()); Array<Child>& children = *child_iter.value(); for(int i = 0; i < children.size(); ++i) { if(children[i].m_entity == child.index) { children.erase(i); break; } } m_parents.erase(old_parent_iter); } if(parent.index >= 0) { m_parents.insert(child.index, parent.index); Children::iterator child_iter = m_children.find(parent.index); if(!child_iter.isValid()) { m_children.insert(parent.index, m_allocator.newObject<Array<Child> >(m_allocator)); child_iter = m_children.find(parent.index); } Child& c = child_iter.value()->pushEmpty(); c.m_entity = child.index; Matrix inv_parent_matrix = parent.getMatrix(); inv_parent_matrix.inverse(); c.m_local_matrix = inv_parent_matrix * child.getMatrix(); } m_parent_set.invoke(child, parent); } virtual Entity getParent(const Entity& child) override { Parents::iterator parent_iter = m_parents.find(child.index); if(parent_iter.isValid()) { return Entity(&m_universe, parent_iter.value()); } return Entity::INVALID; } virtual void serialize(ISerializer& serializer) override { int size = m_parents.size(); serializer.serialize("hierarchy_size", size); serializer.beginArray("hierarchy"); Parents::iterator iter = m_parents.begin(), end = m_parents.end(); while(iter != end) { serializer.serializeArrayItem(iter.key()); serializer.serializeArrayItem(iter.value()); ++iter; } serializer.endArray(); } virtual void deserialize(ISerializer& serializer) override { int size; serializer.deserialize("hierarchy_size", size, 0); serializer.deserializeArrayBegin("hierarchy"); for(int i = 0; i < size; ++i) { int32_t child, parent; serializer.deserializeArrayItem(child, 0); serializer.deserializeArrayItem(parent, 0); setParent(Entity(&m_universe, child), Entity(&m_universe, parent)); } serializer.deserializeArrayEnd(); } virtual DelegateList<void (const Entity&, const Entity&)>& parentSet() override { return m_parent_set; } virtual Array<Child>* getChildren(const Entity& parent) override { Children::iterator iter = m_children.find(parent.index); if(iter.isValid()) { return iter.value(); } return NULL; } private: IAllocator& m_allocator; Universe& m_universe; Parents m_parents; Children m_children; DelegateList<void (const Entity&, const Entity&)> m_parent_set; }; Hierarchy* Hierarchy::create(Universe& universe, IAllocator& allocator) { return allocator.newObject<HierarchyImpl>(universe, allocator); } void Hierarchy::destroy(Hierarchy* hierarchy) { static_cast<HierarchyImpl*>(hierarchy)->getAllocator().deleteObject(hierarchy); } } // namespace Lumix<commit_msg>when a parent entity is transformed, child's local matrix does not change<commit_after>#include "hierarchy.h" #include "core/array.h" #include "core/hash_map.h" #include "core/iserializer.h" #include "core/matrix.h" #include "core/pod_hash_map.h" #include "universe.h" namespace Lumix { class HierarchyImpl : public Hierarchy { private: typedef PODHashMap<int32_t, Array<Child>* > Children; typedef HashMap<int32_t, int32_t> Parents; public: HierarchyImpl(Universe& universe, IAllocator& allocator) : m_universe(universe) , m_parents(allocator) , m_children(allocator) , m_allocator(allocator) , m_parent_set(allocator) { m_is_processing = false; universe.entityMoved().bind<HierarchyImpl, &HierarchyImpl::onEntityMoved>(this); } ~HierarchyImpl() { PODHashMap<int32_t, Array<Child>*>::iterator iter = m_children.begin(), end = m_children.end(); while (iter != end) { m_allocator.deleteObject(iter.value()); ++iter; } } IAllocator& getAllocator() { return m_allocator; } void onEntityMoved(const Entity& entity) { if (!m_is_processing) { m_is_processing = true; Children::iterator iter = m_children.find(entity.index); if (iter.isValid()) { Matrix parent_matrix = entity.getMatrix(); Array<Child>& children = *iter.value(); for (int i = 0, c = children.size(); i < c; ++i) { Entity e(&m_universe, children[i].m_entity); e.setMatrix(parent_matrix * children[i].m_local_matrix); } } Parents::iterator parent_iter = m_parents.find(entity.index); if (parent_iter.isValid()) { Entity parent(&m_universe, parent_iter.value()); Children::iterator child_iter = m_children.find(parent.index); if (child_iter.isValid()) { Array<Child>& children = *child_iter.value(); for (int i = 0, c = children.size(); i < c; ++i) { if (children[i].m_entity == entity.index) { Matrix inv_parent_matrix = parent.getMatrix(); inv_parent_matrix.inverse(); children[i].m_local_matrix = inv_parent_matrix * entity.getMatrix(); break; } } } } m_is_processing = false; } } virtual void setParent(const Entity& child, const Entity& parent) override { Parents::iterator old_parent_iter = m_parents.find(child.index); if(old_parent_iter.isValid()) { Children::iterator child_iter = m_children.find(old_parent_iter.value()); ASSERT(child_iter.isValid()); Array<Child>& children = *child_iter.value(); for(int i = 0; i < children.size(); ++i) { if(children[i].m_entity == child.index) { children.erase(i); break; } } m_parents.erase(old_parent_iter); } if(parent.index >= 0) { m_parents.insert(child.index, parent.index); Children::iterator child_iter = m_children.find(parent.index); if(!child_iter.isValid()) { m_children.insert(parent.index, m_allocator.newObject<Array<Child> >(m_allocator)); child_iter = m_children.find(parent.index); } Child& c = child_iter.value()->pushEmpty(); c.m_entity = child.index; Matrix inv_parent_matrix = parent.getMatrix(); inv_parent_matrix.inverse(); c.m_local_matrix = inv_parent_matrix * child.getMatrix(); } m_parent_set.invoke(child, parent); } virtual Entity getParent(const Entity& child) override { Parents::iterator parent_iter = m_parents.find(child.index); if(parent_iter.isValid()) { return Entity(&m_universe, parent_iter.value()); } return Entity::INVALID; } virtual void serialize(ISerializer& serializer) override { int size = m_parents.size(); serializer.serialize("hierarchy_size", size); serializer.beginArray("hierarchy"); Parents::iterator iter = m_parents.begin(), end = m_parents.end(); while(iter != end) { serializer.serializeArrayItem(iter.key()); serializer.serializeArrayItem(iter.value()); ++iter; } serializer.endArray(); } virtual void deserialize(ISerializer& serializer) override { int size; serializer.deserialize("hierarchy_size", size, 0); serializer.deserializeArrayBegin("hierarchy"); for(int i = 0; i < size; ++i) { int32_t child, parent; serializer.deserializeArrayItem(child, 0); serializer.deserializeArrayItem(parent, 0); setParent(Entity(&m_universe, child), Entity(&m_universe, parent)); } serializer.deserializeArrayEnd(); } virtual DelegateList<void (const Entity&, const Entity&)>& parentSet() override { return m_parent_set; } virtual Array<Child>* getChildren(const Entity& parent) override { Children::iterator iter = m_children.find(parent.index); if(iter.isValid()) { return iter.value(); } return NULL; } private: IAllocator& m_allocator; Universe& m_universe; Parents m_parents; Children m_children; DelegateList<void (const Entity&, const Entity&)> m_parent_set; bool m_is_processing; }; Hierarchy* Hierarchy::create(Universe& universe, IAllocator& allocator) { return allocator.newObject<HierarchyImpl>(universe, allocator); } void Hierarchy::destroy(Hierarchy* hierarchy) { static_cast<HierarchyImpl*>(hierarchy)->getAllocator().deleteObject(hierarchy); } } // namespace Lumix<|endoftext|>
<commit_before>// $Id$ /*********************************************************************** Moses - factored phrase-based language decoder Copyright (C) 2006 University of Edinburgh This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include <assert.h> #include <limits> #include <iostream> #include <fstream> #include "NGramNode.h" #include "LanguageModel.h" #include "TypeDef.h" #include "Util.h" #include "FactorCollection.h" #include "Phrase.h" using namespace std; void LanguageModel::CalcScore(const Phrase &phrase , float &fullScore , float &ngramScore , list< std::pair<size_t, float> > &ngramComponent) const { fullScore = 0; ngramScore = 0; FactorType factorType = GetFactorType(); size_t phraseSize = phrase.GetSize(); vector<const Factor*> contextFactor; contextFactor.reserve(m_nGramOrder); // start of sentence for (size_t currPos = 0 ; currPos < m_nGramOrder && currPos < phraseSize ; currPos++) { contextFactor.push_back(phrase.GetFactor(currPos, factorType)); fullScore = GetValue(contextFactor); } // main loop for (size_t currPos = m_nGramOrder ; currPos < phraseSize ; currPos++) { // used by hypo to speed up lm score calc contextFactor[0] = phrase.GetFactor(currPos-2, factorType); contextFactor[1] = phrase.GetFactor(currPos-1, factorType); contextFactor[2] = phrase.GetFactor(currPos, factorType); ngramScore += GetValue(contextFactor); } fullScore += ngramScore; #ifdef N_BEST size_t lmId = GetId(); pair<size_t, float> store(lmId, ngramScore); ngramComponent.push_back(store); #endif } #ifdef LM_SRI LanguageModel::LanguageModel() :m_srilmVocab() ,m_srilmModel(m_srilmVocab, 3) { m_srilmModel.skipOOVs() = false; } void LanguageModel::Load(size_t id , const std::string &fileName , FactorCollection &factorCollection , FactorType factorType , float weight , size_t nGramOrder) { m_id = id; m_factorType = factorType; m_weight = weight; m_nGramOrder = nGramOrder; File file( fileName.c_str(), "r" ); if (m_srilmModel.read(file)) { } else { TRACE_ERR("warning/failed loading language model" << endl); } // LM can be ok, just outputs warnings CreateFactors(factorCollection); } void LanguageModel::CreateFactors(FactorCollection &factorCollection) { // add factors which have srilm id VocabString str; LmId lmId; VocabIter iter(m_srilmVocab); while ( (str = iter.next()) != NULL) { LmId lmId = GetLmID(str); factorCollection.AddFactor(Output, m_factorType, str, lmId); } lmId = GetLmID(SENTENCE_START); m_sentenceStart = factorCollection.AddFactor(Output, m_factorType, SENTENCE_START, lmId); lmId = GetLmID(SENTENCE_END); m_sentenceEnd = factorCollection.AddFactor(Output, m_factorType, SENTENCE_END, lmId); } float LanguageModel::GetValue(const vector<const Factor*> &contextFactor) const { // set up context size_t count = contextFactor.size(); LmId *context = (LmId*) malloc(count * sizeof(LmId)); for (size_t i = 0 ; i < count - 1 ; i++) { context[i] = GetLmID(contextFactor[count-2-i]); } context[count-1] = Vocab_None; // call sri lm fn float ret = GetValue(GetLmID(contextFactor[count-1]), context); free(context); return ret; } #endif #ifdef LM_INTERNAL #include "InputFileStream.h" // static variable init const LmId LanguageModel::UNKNOWN_LM_ID = NULL; // class methods LanguageModel::LanguageModel() { } void LanguageModel::Load(size_t id , const std::string &fileName , FactorCollection &factorCollection , FactorType factorType , float weight , size_t nGramOrder) { m_id = id; m_factorType = factorType; m_weight = weight; m_nGramOrder = nGramOrder; // make sure start & end tags in factor collection m_sentenceStart = factorCollection.AddFactor(Target, m_factorType, SENTENCE_START); m_sentenceEnd = factorCollection.AddFactor(Target, m_factorType, SENTENCE_END); // read in file TRACE_ERR(fileName << endl); InputFileStream inFile(fileName); string line; int lineNo = 0; while( !getline(inFile, line, '\n').eof()) { lineNo++; if (line.size() != 0 && line.substr(0,1) != "\\") { vector<string> tokens = Tokenize(line, "\t"); if (tokens.size() >= 2) { // split unigram/bigram trigrams vector<string> factorStr = Tokenize(tokens[1], " "); // create / traverse down tree NGramCollection *ngramColl = &m_map; NGramNode *nGram; const Factor *factor; for (int currFactor = (int) factorStr.size() - 1 ; currFactor >= 0 ; currFactor--) { factor = factorCollection.AddFactor(Target, m_factorType, factorStr[currFactor]); nGram = ngramColl->GetOrCreateNGram(factor); ngramColl = nGram->GetNGramColl(); } NGramNode *rootNGram = m_map.GetNGram(factor); nGram->SetRootNGram(rootNGram); factorCollection.SetFactorLmId(factor, rootNGram); float score = TransformSRIScore(Scan<float>(tokens[0])); nGram->SetScore( score ); if (tokens.size() == 3) { float logBackOff = TransformSRIScore(Scan<float>(tokens[2])); nGram->SetLogBackOff( logBackOff ); } else { nGram->SetLogBackOff( 0 ); } } } } } float LanguageModel::GetValue(const std::vector<const Factor*> &contextFactor) const { float score; size_t nGramOrder = contextFactor.size(); assert(nGramOrder <= 3); if (nGramOrder == 1) score = GetValue(contextFactor[0]); else if (nGramOrder == 2) score = GetValue(contextFactor[0], contextFactor[1]); else if (nGramOrder == 3) score = GetValue(contextFactor[0], contextFactor[1], contextFactor[2]); return FloorSRIScore(score); } float LanguageModel::GetValue(const Factor *factor0) const { float prob; const NGramNode *nGram = factor0->GetLmId(); if (nGram == NULL) { prob = -numeric_limits<float>::infinity(); } else { prob = nGram->GetScore(); } return FloorSRIScore(prob); } float LanguageModel::GetValue(const Factor *factor0, const Factor *factor1) const { float score; const NGramNode *nGram[2]; nGram[1] = factor1->GetLmId(); if (nGram[1] == NULL) { score = -numeric_limits<float>::infinity(); } else { nGram[0] = nGram[1]->GetNGram(factor0); if (nGram[0] == NULL) { // something unigram nGram[0] = factor0->GetLmId(); if (nGram[0] == NULL) { // stops at unigram score = nGram[1]->GetScore(); } else { // unigram unigram score = nGram[1]->GetScore() + nGram[0]->GetLogBackOff(); } } else { // bigram score = nGram[0]->GetScore(); } } return FloorSRIScore(score); } float LanguageModel::GetValue(const Factor *factor0, const Factor *factor1, const Factor *factor2) const { float score; const NGramNode *nGram[3]; nGram[2] = factor2->GetLmId(); if (nGram[2] == NULL) { score = -numeric_limits<float>::infinity(); } else { nGram[1] = nGram[2]->GetNGram(factor1); if (nGram[1] == NULL) { // something unigram nGram[1] = factor1->GetLmId(); if (nGram[1] == NULL) { // stops at unigram score = nGram[2]->GetScore(); } else { nGram[0] = nGram[1]->GetNGram(factor0); if (nGram[0] == NULL) { // unigram unigram score = nGram[2]->GetScore() + nGram[1]->GetLogBackOff(); } else { // unigram bigram score = nGram[2]->GetScore() + nGram[1]->GetLogBackOff() + nGram[0]->GetLogBackOff(); } } } else { // trigram, or something bigram nGram[0] = nGram[1]->GetNGram(factor0); if (nGram[0] != NULL) { // trigram score = nGram[0]->GetScore(); } else { score = nGram[1]->GetScore(); nGram[1] = nGram[1]->GetRootNGram(); nGram[0] = nGram[1]->GetNGram(factor0); if (nGram[0] == NULL) { // just bigram // do nothing } else { score += nGram[0]->GetLogBackOff(); } } // else do nothing. just use 1st bigram } } return FloorSRIScore(score); } #endif <commit_msg>variable number of translation component scores<commit_after>// $Id$ /*********************************************************************** Moses - factored phrase-based language decoder Copyright (C) 2006 University of Edinburgh This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include <assert.h> #include <limits> #include <iostream> #include <fstream> #include "NGramNode.h" #include "LanguageModel.h" #include "TypeDef.h" #include "Util.h" #include "FactorCollection.h" #include "Phrase.h" using namespace std; void LanguageModel::CalcScore(const Phrase &phrase , float &fullScore , float &ngramScore , list< std::pair<size_t, float> > &ngramComponent) const { fullScore = 0; ngramScore = 0; FactorType factorType = GetFactorType(); size_t phraseSize = phrase.GetSize(); vector<const Factor*> contextFactor; contextFactor.reserve(m_nGramOrder); // start of sentence for (size_t currPos = 0 ; currPos < m_nGramOrder - 1 && currPos < phraseSize ; currPos++) { contextFactor.push_back(phrase.GetFactor(currPos, factorType)); fullScore = GetValue(contextFactor); } // main loop for (size_t currPos = m_nGramOrder - 1; currPos < phraseSize ; currPos++) { // used by hypo to speed up lm score calc // ?? trigram only !!! contextFactor[0] = phrase.GetFactor(currPos-2, factorType); contextFactor[1] = phrase.GetFactor(currPos-1, factorType); contextFactor[2] = phrase.GetFactor(currPos, factorType); ngramScore += GetValue(contextFactor); } fullScore += ngramScore; #ifdef N_BEST size_t lmId = GetId(); pair<size_t, float> store(lmId, ngramScore); ngramComponent.push_back(store); #endif } #ifdef LM_SRI LanguageModel::LanguageModel() :m_srilmVocab() ,m_srilmModel(m_srilmVocab, 3) { m_srilmModel.skipOOVs() = false; } void LanguageModel::Load(size_t id , const std::string &fileName , FactorCollection &factorCollection , FactorType factorType , float weight , size_t nGramOrder) { m_id = id; m_factorType = factorType; m_weight = weight; m_nGramOrder = nGramOrder; File file( fileName.c_str(), "r" ); if (m_srilmModel.read(file)) { } else { TRACE_ERR("warning/failed loading language model" << endl); } // LM can be ok, just outputs warnings CreateFactors(factorCollection); } void LanguageModel::CreateFactors(FactorCollection &factorCollection) { // add factors which have srilm id VocabString str; LmId lmId; VocabIter iter(m_srilmVocab); while ( (str = iter.next()) != NULL) { LmId lmId = GetLmID(str); factorCollection.AddFactor(Output, m_factorType, str, lmId); } lmId = GetLmID(SENTENCE_START); m_sentenceStart = factorCollection.AddFactor(Output, m_factorType, SENTENCE_START, lmId); lmId = GetLmID(SENTENCE_END); m_sentenceEnd = factorCollection.AddFactor(Output, m_factorType, SENTENCE_END, lmId); } float LanguageModel::GetValue(const vector<const Factor*> &contextFactor) const { // set up context size_t count = contextFactor.size(); LmId *context = (LmId*) malloc(count * sizeof(LmId)); for (size_t i = 0 ; i < count - 1 ; i++) { context[i] = GetLmID(contextFactor[count-2-i]); } context[count-1] = Vocab_None; // call sri lm fn float ret = GetValue(GetLmID(contextFactor[count-1]), context); free(context); return ret; } #endif #ifdef LM_INTERNAL #include "InputFileStream.h" // static variable init const LmId LanguageModel::UNKNOWN_LM_ID = NULL; // class methods LanguageModel::LanguageModel() { } void LanguageModel::Load(size_t id , const std::string &fileName , FactorCollection &factorCollection , FactorType factorType , float weight , size_t nGramOrder) { m_id = id; m_factorType = factorType; m_weight = weight; m_nGramOrder = nGramOrder; // make sure start & end tags in factor collection m_sentenceStart = factorCollection.AddFactor(Target, m_factorType, SENTENCE_START); m_sentenceEnd = factorCollection.AddFactor(Target, m_factorType, SENTENCE_END); // read in file TRACE_ERR(fileName << endl); InputFileStream inFile(fileName); string line; int lineNo = 0; while( !getline(inFile, line, '\n').eof()) { lineNo++; if (line.size() != 0 && line.substr(0,1) != "\\") { vector<string> tokens = Tokenize(line, "\t"); if (tokens.size() >= 2) { // split unigram/bigram trigrams vector<string> factorStr = Tokenize(tokens[1], " "); // create / traverse down tree NGramCollection *ngramColl = &m_map; NGramNode *nGram; const Factor *factor; for (int currFactor = (int) factorStr.size() - 1 ; currFactor >= 0 ; currFactor--) { factor = factorCollection.AddFactor(Target, m_factorType, factorStr[currFactor]); nGram = ngramColl->GetOrCreateNGram(factor); ngramColl = nGram->GetNGramColl(); } NGramNode *rootNGram = m_map.GetNGram(factor); nGram->SetRootNGram(rootNGram); factorCollection.SetFactorLmId(factor, rootNGram); float score = TransformSRIScore(Scan<float>(tokens[0])); nGram->SetScore( score ); if (tokens.size() == 3) { float logBackOff = TransformSRIScore(Scan<float>(tokens[2])); nGram->SetLogBackOff( logBackOff ); } else { nGram->SetLogBackOff( 0 ); } } } } } float LanguageModel::GetValue(const std::vector<const Factor*> &contextFactor) const { float score; size_t nGramOrder = contextFactor.size(); assert(nGramOrder <= 3); if (nGramOrder == 1) score = GetValue(contextFactor[0]); else if (nGramOrder == 2) score = GetValue(contextFactor[0], contextFactor[1]); else if (nGramOrder == 3) score = GetValue(contextFactor[0], contextFactor[1], contextFactor[2]); return FloorSRIScore(score); } float LanguageModel::GetValue(const Factor *factor0) const { float prob; const NGramNode *nGram = factor0->GetLmId(); if (nGram == NULL) { prob = -numeric_limits<float>::infinity(); } else { prob = nGram->GetScore(); } return FloorSRIScore(prob); } float LanguageModel::GetValue(const Factor *factor0, const Factor *factor1) const { float score; const NGramNode *nGram[2]; nGram[1] = factor1->GetLmId(); if (nGram[1] == NULL) { score = -numeric_limits<float>::infinity(); } else { nGram[0] = nGram[1]->GetNGram(factor0); if (nGram[0] == NULL) { // something unigram nGram[0] = factor0->GetLmId(); if (nGram[0] == NULL) { // stops at unigram score = nGram[1]->GetScore(); } else { // unigram unigram score = nGram[1]->GetScore() + nGram[0]->GetLogBackOff(); } } else { // bigram score = nGram[0]->GetScore(); } } return FloorSRIScore(score); } float LanguageModel::GetValue(const Factor *factor0, const Factor *factor1, const Factor *factor2) const { float score; const NGramNode *nGram[3]; nGram[2] = factor2->GetLmId(); if (nGram[2] == NULL) { score = -numeric_limits<float>::infinity(); } else { nGram[1] = nGram[2]->GetNGram(factor1); if (nGram[1] == NULL) { // something unigram nGram[1] = factor1->GetLmId(); if (nGram[1] == NULL) { // stops at unigram score = nGram[2]->GetScore(); } else { nGram[0] = nGram[1]->GetNGram(factor0); if (nGram[0] == NULL) { // unigram unigram score = nGram[2]->GetScore() + nGram[1]->GetLogBackOff(); } else { // unigram bigram score = nGram[2]->GetScore() + nGram[1]->GetLogBackOff() + nGram[0]->GetLogBackOff(); } } } else { // trigram, or something bigram nGram[0] = nGram[1]->GetNGram(factor0); if (nGram[0] != NULL) { // trigram score = nGram[0]->GetScore(); } else { score = nGram[1]->GetScore(); nGram[1] = nGram[1]->GetRootNGram(); nGram[0] = nGram[1]->GetNGram(factor0); if (nGram[0] == NULL) { // just bigram // do nothing } else { score += nGram[0]->GetLogBackOff(); } } // else do nothing. just use 1st bigram } } return FloorSRIScore(score); } #endif <|endoftext|>
<commit_before>/* This file is part of VROOM. Copyright (c) 2015-2018, Julien Coupey. All rights reserved (see LICENSE). */ #include "./input_parser.h" // Helper to get optional array of coordinates. inline std::array<coordinate_t, 2> parse_coordinates(const rapidjson::Value& object, const char* key) { if (!object[key].IsArray() or (object[key].Size() < 2) or !object[key][0].IsNumber() or !object[key][1].IsNumber()) { throw custom_exception("Invalid " + std::string(key) + " array."); } return {object[key][0].GetDouble(), object[key][1].GetDouble()}; } inline amount_t parse_amount(const rapidjson::Value& object, const char* key) { if (!object[key].IsArray()) { throw custom_exception("Invalid " + std::string(key) + " array."); } amount_t amount; for (rapidjson::SizeType i = 0; i < object[key].Size(); ++i) { if (!object[key][i].IsInt64()) { throw custom_exception("Invalid " + std::string(key) + " value."); } amount.push_back(object[key][i].GetInt64()); } return amount; } inline boost::optional<amount_t> get_amount(const rapidjson::Value& object, const char* key) { if (!object.HasMember(key)) { return boost::none; } if (!object[key].IsArray()) { throw custom_exception("Invalid " + std::string(key) + " array."); } amount_t amount; for (rapidjson::SizeType i = 0; i < object[key].Size(); ++i) { if (!object[key][i].IsInt64()) { throw custom_exception("Invalid " + std::string(key) + " value."); } amount.push_back(object[key][i].GetInt64()); } return amount; } inline bool valid_vehicle(const rapidjson::Value& v) { return v.IsObject() and v.HasMember("id") and v["id"].IsUint64(); } input parse(const cl_args_t& cl_args) { BOOST_LOG_TRIVIAL(info) << "[Loading] Parsing input."; // Set relevant wrapper to retrieve the matrix and geometry. std::unique_ptr<routing_io<cost_t>> routing_wrapper; if (!cl_args.use_libosrm) { // Use osrm-routed. routing_wrapper = std::make_unique<routed_wrapper>(cl_args.osrm_address, cl_args.osrm_port, cl_args.osrm_profile); } else { #if LIBOSRM // Use libosrm. if (cl_args.osrm_profile.empty()) { throw custom_exception("-l flag requires -m."); } routing_wrapper = std::make_unique<libosrm_wrapper>(cl_args.osrm_profile); #else throw custom_exception("libosrm must be installed to use -l."); #endif } // Custom input object embedding jobs, vehicles and matrix. input input_data(std::move(routing_wrapper), cl_args.geometry); // Input json object. rapidjson::Document json_input; // Parsing input string to populate the input object. if (json_input.Parse(cl_args.input.c_str()).HasParseError()) { std::string error_msg = std::string(rapidjson::GetParseError_En(json_input.GetParseError())) + " (offset: " + std::to_string(json_input.GetErrorOffset()) + ")"; throw custom_exception(error_msg); } // Main Checks for valid json input. if (!json_input.HasMember("jobs") or !json_input["jobs"].IsArray()) { throw custom_exception("Invalid jobs."); } if (!json_input.HasMember("vehicles") or !json_input["vehicles"].IsArray() or json_input["vehicles"].Empty()) { throw custom_exception("Invalid vehicles."); } // Switch input type: explicit matrix or using OSRM. if (json_input.HasMember("matrix")) { if (!json_input["matrix"].IsArray()) { throw custom_exception("Invalid matrix."); } // Load custom matrix while checking if it is square. rapidjson::SizeType matrix_size = json_input["matrix"].Size(); input_data._max_cost_per_line.assign(matrix_size, 0); input_data._max_cost_per_column.assign(matrix_size, 0); matrix<cost_t> matrix_input(matrix_size); for (rapidjson::SizeType i = 0; i < matrix_size; ++i) { if (!json_input["matrix"][i].IsArray() or (json_input["matrix"][i].Size() != matrix_size)) { throw custom_exception("Invalid matrix line " + std::to_string(i) + "."); } for (rapidjson::SizeType j = 0; j < matrix_size; ++j) { if (!json_input["matrix"][i][j].IsUint()) { throw custom_exception("Invalid matrix entry (" + std::to_string(i) + "," + std::to_string(j) + ")."); } cost_t cost = json_input["matrix"][i][j].GetUint(); matrix_input[i][j] = cost; input_data._max_cost_per_line[i] = std::max(input_data._max_cost_per_line[i], cost); input_data._max_cost_per_column[j] = std::max(input_data._max_cost_per_column[j], cost); } } input_data._matrix = matrix_input; // Add all vehicles. for (rapidjson::SizeType i = 0; i < json_input["vehicles"].Size(); ++i) { if (!valid_vehicle(json_input["vehicles"][i])) { throw custom_exception("Invalid vehicle at " + std::to_string(i) + "."); } // Check if vehicle has start_index or end_index. bool has_start_index = json_input["vehicles"][i].HasMember("start_index"); index_t start_index = 0; // Initial value actually never used. if (has_start_index) { if (!json_input["vehicles"][i]["start_index"].IsUint()) { throw custom_exception("Invalid start_index for vehicle at 0."); } start_index = json_input["vehicles"][i]["start_index"].GetUint(); if (matrix_size <= start_index) { throw custom_exception( "start_index exceeding matrix size for vehicle at 0."); } } bool has_start_coords = json_input["vehicles"][i].HasMember("start"); bool has_end_index = json_input["vehicles"][i].HasMember("end_index"); index_t end_index = 0; // Initial value actually never used. if (has_end_index) { if (!json_input["vehicles"][i]["end_index"].IsUint()) { throw custom_exception("Invalid end_index for vehicle at 0."); } end_index = json_input["vehicles"][i]["end_index"].GetUint(); if (matrix_size <= end_index) { throw custom_exception( "end_index exceeding matrix size for vehicle at 0."); } } bool has_end_coords = json_input["vehicles"][i].HasMember("end"); // Add vehicle to input boost::optional<location_t> start; if (has_start_index) { if (has_start_coords) { start = boost::optional<location_t>(location_t( {start_index, parse_coordinates(json_input["vehicles"][i], "start")})); } else { start = boost::optional<location_t>(start_index); } } boost::optional<location_t> end; if (has_end_index) { if (has_end_coords) { end = boost::optional<location_t>(location_t( {end_index, parse_coordinates(json_input["vehicles"][i], "end")})); } else { end = boost::optional<location_t>(end_index); } } vehicle_t current_v(json_input["vehicles"][i]["id"].GetUint(), start, end, get_amount(json_input["vehicles"][i], "capacity")); input_data.add_vehicle(current_v); } // Add the jobs for (rapidjson::SizeType i = 0; i < json_input["jobs"].Size(); ++i) { if (!json_input["jobs"][i].IsObject()) { throw custom_exception("Invalid job."); } if (!json_input["jobs"][i].HasMember("id") or !json_input["jobs"][i]["id"].IsUint64()) { throw custom_exception("Invalid id for job at " + std::to_string(i) + "."); } if (!json_input["jobs"][i].HasMember("location_index") or !json_input["jobs"][i]["location_index"].IsUint()) { throw custom_exception("Invalid location_index for job at " + std::to_string(i) + "."); } if (matrix_size <= json_input["jobs"][i]["location_index"].GetUint()) { throw custom_exception( "location_index exceeding matrix size for job at " + std::to_string(i) + "."); } if (json_input["jobs"][i].HasMember("location")) { job_t current_job(json_input["jobs"][i]["id"].GetUint64(), get_amount(json_input["jobs"][i], "amount"), json_input["jobs"][i]["location_index"].GetUint(), parse_coordinates(json_input["jobs"][i], "location")); input_data.add_job(current_job); } else { job_t current_job(json_input["jobs"][i]["id"].GetUint64(), get_amount(json_input["jobs"][i], "amount"), json_input["jobs"][i]["location_index"].GetUint()); input_data.add_job(current_job); } } } else { // Adding vehicles and jobs only, matrix will be computed using // OSRM upon solving. // All vehicles. for (rapidjson::SizeType i = 0; i < json_input["vehicles"].Size(); ++i) { if (!valid_vehicle(json_input["vehicles"][i])) { throw custom_exception("Invalid vehicle at " + std::to_string(i) + "."); } // Start def is a ugly workaround as using plain: // // boost::optional<location_t> start; // // will raise a false positive -Wmaybe-uninitialized with gcc, // see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=47679 auto start([]() -> boost::optional<location_t> { return boost::none; }()); if (json_input["vehicles"][i].HasMember("start")) { start = boost::optional<location_t>( parse_coordinates(json_input["vehicles"][i], "start")); } boost::optional<location_t> end; if (json_input["vehicles"][i].HasMember("end")) { end = boost::optional<location_t>( parse_coordinates(json_input["vehicles"][i], "end")); } vehicle_t current_v(json_input["vehicles"][i]["id"].GetUint(), start, end, get_amount(json_input["vehicles"][i], "capacity")); input_data.add_vehicle(current_v); } // Getting jobs. for (rapidjson::SizeType i = 0; i < json_input["jobs"].Size(); ++i) { if (!json_input["jobs"][i].IsObject()) { throw custom_exception("Invalid job."); } if (!json_input["jobs"][i].HasMember("location") or !json_input["jobs"][i]["location"].IsArray()) { throw custom_exception("Invalid location for job at " + std::to_string(i) + "."); } if (!json_input["jobs"][i].HasMember("id") or !json_input["jobs"][i]["id"].IsUint64()) { throw custom_exception("Invalid id for job at " + std::to_string(i) + "."); } job_t current_job(json_input["jobs"][i]["id"].GetUint64(), get_amount(json_input["jobs"][i], "amount"), parse_coordinates(json_input["jobs"][i], "location")); input_data.add_job(current_job); } } if (input_data._locations.size() <= 1) { throw custom_exception("At least two locations required!"); } return input_data; } <commit_msg>Report ids on parsing errors whenever possible.<commit_after>/* This file is part of VROOM. Copyright (c) 2015-2018, Julien Coupey. All rights reserved (see LICENSE). */ #include "./input_parser.h" // Helper to get optional array of coordinates. inline std::array<coordinate_t, 2> parse_coordinates(const rapidjson::Value& object, const char* key) { if (!object[key].IsArray() or (object[key].Size() < 2) or !object[key][0].IsNumber() or !object[key][1].IsNumber()) { throw custom_exception("Invalid " + std::string(key) + " array."); } return {object[key][0].GetDouble(), object[key][1].GetDouble()}; } inline amount_t parse_amount(const rapidjson::Value& object, const char* key) { if (!object[key].IsArray()) { throw custom_exception("Invalid " + std::string(key) + " array."); } amount_t amount; for (rapidjson::SizeType i = 0; i < object[key].Size(); ++i) { if (!object[key][i].IsInt64()) { throw custom_exception("Invalid " + std::string(key) + " value."); } amount.push_back(object[key][i].GetInt64()); } return amount; } inline boost::optional<amount_t> get_amount(const rapidjson::Value& object, const char* key) { if (!object.HasMember(key)) { return boost::none; } if (!object[key].IsArray()) { throw custom_exception("Invalid " + std::string(key) + " array."); } amount_t amount; for (rapidjson::SizeType i = 0; i < object[key].Size(); ++i) { if (!object[key][i].IsInt64()) { throw custom_exception("Invalid " + std::string(key) + " value."); } amount.push_back(object[key][i].GetInt64()); } return amount; } inline bool valid_vehicle(const rapidjson::Value& v) { return v.IsObject() and v.HasMember("id") and v["id"].IsUint64(); } input parse(const cl_args_t& cl_args) { BOOST_LOG_TRIVIAL(info) << "[Loading] Parsing input."; // Set relevant wrapper to retrieve the matrix and geometry. std::unique_ptr<routing_io<cost_t>> routing_wrapper; if (!cl_args.use_libosrm) { // Use osrm-routed. routing_wrapper = std::make_unique<routed_wrapper>(cl_args.osrm_address, cl_args.osrm_port, cl_args.osrm_profile); } else { #if LIBOSRM // Use libosrm. if (cl_args.osrm_profile.empty()) { throw custom_exception("-l flag requires -m."); } routing_wrapper = std::make_unique<libosrm_wrapper>(cl_args.osrm_profile); #else throw custom_exception("libosrm must be installed to use -l."); #endif } // Custom input object embedding jobs, vehicles and matrix. input input_data(std::move(routing_wrapper), cl_args.geometry); // Input json object. rapidjson::Document json_input; // Parsing input string to populate the input object. if (json_input.Parse(cl_args.input.c_str()).HasParseError()) { std::string error_msg = std::string(rapidjson::GetParseError_En(json_input.GetParseError())) + " (offset: " + std::to_string(json_input.GetErrorOffset()) + ")"; throw custom_exception(error_msg); } // Main Checks for valid json input. if (!json_input.HasMember("jobs") or !json_input["jobs"].IsArray()) { throw custom_exception("Invalid jobs."); } if (!json_input.HasMember("vehicles") or !json_input["vehicles"].IsArray() or json_input["vehicles"].Empty()) { throw custom_exception("Invalid vehicles."); } // Switch input type: explicit matrix or using OSRM. if (json_input.HasMember("matrix")) { if (!json_input["matrix"].IsArray()) { throw custom_exception("Invalid matrix."); } // Load custom matrix while checking if it is square. rapidjson::SizeType matrix_size = json_input["matrix"].Size(); input_data._max_cost_per_line.assign(matrix_size, 0); input_data._max_cost_per_column.assign(matrix_size, 0); matrix<cost_t> matrix_input(matrix_size); for (rapidjson::SizeType i = 0; i < matrix_size; ++i) { if (!json_input["matrix"][i].IsArray() or (json_input["matrix"][i].Size() != matrix_size)) { throw custom_exception("Invalid matrix line " + std::to_string(i) + "."); } for (rapidjson::SizeType j = 0; j < matrix_size; ++j) { if (!json_input["matrix"][i][j].IsUint()) { throw custom_exception("Invalid matrix entry (" + std::to_string(i) + "," + std::to_string(j) + ")."); } cost_t cost = json_input["matrix"][i][j].GetUint(); matrix_input[i][j] = cost; input_data._max_cost_per_line[i] = std::max(input_data._max_cost_per_line[i], cost); input_data._max_cost_per_column[j] = std::max(input_data._max_cost_per_column[j], cost); } } input_data._matrix = matrix_input; // Add all vehicles. for (rapidjson::SizeType i = 0; i < json_input["vehicles"].Size(); ++i) { if (!valid_vehicle(json_input["vehicles"][i])) { throw custom_exception("Invalid vehicle at " + std::to_string(i) + "."); } auto v_id = json_input["vehicles"][i]["id"].GetUint(); // Check if vehicle has start_index or end_index. bool has_start_index = json_input["vehicles"][i].HasMember("start_index"); index_t start_index = 0; // Initial value actually never used. if (has_start_index) { if (!json_input["vehicles"][i]["start_index"].IsUint()) { throw custom_exception("Invalid start_index for vehicle " + std::to_string(v_id) + "."); } start_index = json_input["vehicles"][i]["start_index"].GetUint(); if (matrix_size <= start_index) { throw custom_exception( "start_index exceeding matrix size for vehicle" + std::to_string(v_id) + "."); } } bool has_start_coords = json_input["vehicles"][i].HasMember("start"); bool has_end_index = json_input["vehicles"][i].HasMember("end_index"); index_t end_index = 0; // Initial value actually never used. if (has_end_index) { if (!json_input["vehicles"][i]["end_index"].IsUint()) { throw custom_exception("Invalid end_index for vehicle" + std::to_string(v_id) + "."); } end_index = json_input["vehicles"][i]["end_index"].GetUint(); if (matrix_size <= end_index) { throw custom_exception("end_index exceeding matrix size for vehicle" + std::to_string(v_id) + "."); } } bool has_end_coords = json_input["vehicles"][i].HasMember("end"); // Add vehicle to input boost::optional<location_t> start; if (has_start_index) { if (has_start_coords) { start = boost::optional<location_t>(location_t( {start_index, parse_coordinates(json_input["vehicles"][i], "start")})); } else { start = boost::optional<location_t>(start_index); } } boost::optional<location_t> end; if (has_end_index) { if (has_end_coords) { end = boost::optional<location_t>(location_t( {end_index, parse_coordinates(json_input["vehicles"][i], "end")})); } else { end = boost::optional<location_t>(end_index); } } vehicle_t current_v(v_id, start, end, get_amount(json_input["vehicles"][i], "capacity")); input_data.add_vehicle(current_v); } // Add the jobs for (rapidjson::SizeType i = 0; i < json_input["jobs"].Size(); ++i) { if (!json_input["jobs"][i].IsObject()) { throw custom_exception("Invalid job."); } if (!json_input["jobs"][i].HasMember("id") or !json_input["jobs"][i]["id"].IsUint64()) { throw custom_exception("Invalid id for job at " + std::to_string(i) + "."); } auto j_id = json_input["jobs"][i]["id"].GetUint64(); if (!json_input["jobs"][i].HasMember("location_index") or !json_input["jobs"][i]["location_index"].IsUint()) { throw custom_exception("Invalid location_index for job " + std::to_string(j_id) + "."); } if (matrix_size <= json_input["jobs"][i]["location_index"].GetUint()) { throw custom_exception("location_index exceeding matrix size for job " + std::to_string(j_id) + "."); } if (json_input["jobs"][i].HasMember("location")) { job_t current_job(j_id, get_amount(json_input["jobs"][i], "amount"), json_input["jobs"][i]["location_index"].GetUint(), parse_coordinates(json_input["jobs"][i], "location")); input_data.add_job(current_job); } else { job_t current_job(json_input["jobs"][i]["id"].GetUint64(), get_amount(json_input["jobs"][i], "amount"), json_input["jobs"][i]["location_index"].GetUint()); input_data.add_job(current_job); } } } else { // Adding vehicles and jobs only, matrix will be computed using // OSRM upon solving. // All vehicles. for (rapidjson::SizeType i = 0; i < json_input["vehicles"].Size(); ++i) { if (!valid_vehicle(json_input["vehicles"][i])) { throw custom_exception("Invalid vehicle at " + std::to_string(i) + "."); } // Start def is a ugly workaround as using plain: // // boost::optional<location_t> start; // // will raise a false positive -Wmaybe-uninitialized with gcc, // see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=47679 auto start([]() -> boost::optional<location_t> { return boost::none; }()); if (json_input["vehicles"][i].HasMember("start")) { start = boost::optional<location_t>( parse_coordinates(json_input["vehicles"][i], "start")); } boost::optional<location_t> end; if (json_input["vehicles"][i].HasMember("end")) { end = boost::optional<location_t>( parse_coordinates(json_input["vehicles"][i], "end")); } vehicle_t current_v(json_input["vehicles"][i]["id"].GetUint(), start, end, get_amount(json_input["vehicles"][i], "capacity")); input_data.add_vehicle(current_v); } // Getting jobs. for (rapidjson::SizeType i = 0; i < json_input["jobs"].Size(); ++i) { if (!json_input["jobs"][i].IsObject()) { throw custom_exception("Invalid job."); } if (!json_input["jobs"][i].HasMember("id") or !json_input["jobs"][i]["id"].IsUint64()) { throw custom_exception("Invalid id for job at " + std::to_string(i) + "."); } auto j_id = json_input["jobs"][i]["id"].GetUint64(); if (!json_input["jobs"][i].HasMember("location") or !json_input["jobs"][i]["location"].IsArray()) { throw custom_exception("Invalid location for job " + std::to_string(j_id) + "."); } job_t current_job(j_id, get_amount(json_input["jobs"][i], "amount"), parse_coordinates(json_input["jobs"][i], "location")); input_data.add_job(current_job); } } if (input_data._locations.size() <= 1) { throw custom_exception("At least two locations required!"); } return input_data; } <|endoftext|>
<commit_before>/* Copyright (c) 2009, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/utp_stream.hpp" #include "libtorrent/udp_socket.hpp" #include "libtorrent/utp_socket_manager.hpp" #include "libtorrent/instantiate_connection.hpp" #include "libtorrent/socket_io.hpp" #define TORRENT_UTP_LOG 1 #if TORRENT_UTP_LOG namespace libtorrent { extern void utp_log(char const* fmt, ...); } #define UTP_LOG utp_log #define UTP_LOGV utp_log #else #define UTP_LOG if (false) printf #define UTP_LOGV if (false) printf #endif namespace libtorrent { utp_socket_manager::utp_socket_manager(session_settings const& sett, udp_socket& s , incoming_utp_callback_t cb) : m_sock(s) , m_cb(cb) , m_last_socket(0) , m_new_connection(-1) , m_sett(sett) {} utp_socket_manager::~utp_socket_manager() { for (socket_map_t::iterator i = m_utp_sockets.begin() , end(m_utp_sockets.end()); i != end; ++i) { delete_utp_impl(i->second); } } void utp_socket_manager::get_status(utp_status& s) const { s.num_idle = 0; s.num_syn_sent = 0; s.num_connected = 0; s.num_fin_sent = 0; s.num_close_wait = 0; for (socket_map_t::const_iterator i = m_utp_sockets.begin() , end(m_utp_sockets.end()); i != end; ++i) { int state = utp_socket_state(i->second); switch (state) { case 0: ++s.num_idle; break; case 1: ++s.num_syn_sent; break; case 2: ++s.num_connected; break; case 3: ++s.num_fin_sent; break; case 4: ++s.num_close_wait; break; case 5: ++s.num_close_wait; break; } } } void utp_socket_manager::tick(ptime now) { for (socket_map_t::iterator i = m_utp_sockets.begin() , end(m_utp_sockets.end()); i != end;) { if (should_delete(i->second)) { delete_utp_impl(i->second); if (m_last_socket == i->second) m_last_socket = 0; m_utp_sockets.erase(i++); continue; } tick_utp_impl(i->second, now); ++i; } } void utp_socket_manager::send_packet(udp::endpoint const& ep, char const* p , int len, error_code& ec) { if (!m_sock.is_open()) { ec = asio::error::operation_aborted; return; } m_sock.send(ep, p, len, ec); } tcp::endpoint utp_socket_manager::local_endpoint(error_code& ec) const { return m_sock.local_endpoint(ec); } bool utp_socket_manager::incoming_packet(char const* p, int size, udp::endpoint const& ep) { // UTP_LOGV("incoming packet size:%d\n", size); if (size < sizeof(utp_header)) return false; utp_header const* ph = (utp_header*)p; // UTP_LOGV("incoming packet version:%d\n", int(ph->ver)); if (ph->ver != 1) return false; // parse out connection ID and look for existing // connections. If found, forward to the utp_stream. boost::uint16_t id = ph->connection_id; // first test to see if it's the same socket as last time // in most cases it is if (m_last_socket && id == utp_receive_id(m_last_socket) && ep == utp_remote_endpoint(m_last_socket)) { return utp_incoming_packet(m_last_socket, p, size, ep); } socket_map_t::iterator i = m_utp_sockets.find(id); std::pair<socket_map_t::iterator, socket_map_t::iterator> r = m_utp_sockets.equal_range(id); for (; r.first != r.second; ++r.first) { if (ep != utp_remote_endpoint(r.first->second)) continue; bool ret = utp_incoming_packet(r.first->second, p, size, ep); if (ret) m_last_socket = r.first->second; return ret; } // UTP_LOGV("incoming packet id:%d source:%s\n", id, print_endpoint(ep).c_str()); // if not found, see if it's a SYN packet, if it is, // create a new utp_stream if (ph->type == ST_SYN) { // create the new socket with this ID m_new_connection = id; // UTP_LOGV("not found, new connection id:%d\n", m_new_connection); boost::shared_ptr<socket_type> c(new (std::nothrow) socket_type(m_sock.get_io_service())); if (!c) return false; instantiate_connection(m_sock.get_io_service(), proxy_settings(), this, *c); utp_stream* str = c->get<utp_stream>(); TORRENT_ASSERT(str); bool ret = utp_incoming_packet(str->get_impl(), p, size, ep); if (!ret) return false; m_cb(c); // the connection most likely changed its connection ID here // we need to move it to the correct ID return true; } // #error send reset return false; } void utp_socket_manager::remove_socket(boost::uint16_t id) { socket_map_t::iterator i = m_utp_sockets.find(id); if (i == m_utp_sockets.end()) return; delete_utp_impl(i->second); if (m_last_socket == i->second) m_last_socket = 0; m_utp_sockets.erase(i); } utp_socket_impl* utp_socket_manager::new_utp_socket(utp_stream* str) { boost::uint16_t send_id = 0; boost::uint16_t recv_id = 0; if (m_new_connection != -1) { send_id = m_new_connection; recv_id = m_new_connection + 1; m_new_connection = -1; } else { send_id = rand(); recv_id = send_id - 1; } utp_socket_impl* impl = construct_utp_impl(recv_id, send_id, str, this); m_utp_sockets.insert(std::make_pair(recv_id, impl)); return impl; } } <commit_msg>fix disabling of incoming utp connections<commit_after>/* Copyright (c) 2009, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/utp_stream.hpp" #include "libtorrent/udp_socket.hpp" #include "libtorrent/utp_socket_manager.hpp" #include "libtorrent/instantiate_connection.hpp" #include "libtorrent/socket_io.hpp" #define TORRENT_UTP_LOG 1 #if TORRENT_UTP_LOG namespace libtorrent { extern void utp_log(char const* fmt, ...); } #define UTP_LOG utp_log #define UTP_LOGV utp_log #else #define UTP_LOG if (false) printf #define UTP_LOGV if (false) printf #endif namespace libtorrent { utp_socket_manager::utp_socket_manager(session_settings const& sett, udp_socket& s , incoming_utp_callback_t cb) : m_sock(s) , m_cb(cb) , m_last_socket(0) , m_new_connection(-1) , m_sett(sett) {} utp_socket_manager::~utp_socket_manager() { for (socket_map_t::iterator i = m_utp_sockets.begin() , end(m_utp_sockets.end()); i != end; ++i) { delete_utp_impl(i->second); } } void utp_socket_manager::get_status(utp_status& s) const { s.num_idle = 0; s.num_syn_sent = 0; s.num_connected = 0; s.num_fin_sent = 0; s.num_close_wait = 0; for (socket_map_t::const_iterator i = m_utp_sockets.begin() , end(m_utp_sockets.end()); i != end; ++i) { int state = utp_socket_state(i->second); switch (state) { case 0: ++s.num_idle; break; case 1: ++s.num_syn_sent; break; case 2: ++s.num_connected; break; case 3: ++s.num_fin_sent; break; case 4: ++s.num_close_wait; break; case 5: ++s.num_close_wait; break; } } } void utp_socket_manager::tick(ptime now) { for (socket_map_t::iterator i = m_utp_sockets.begin() , end(m_utp_sockets.end()); i != end;) { if (should_delete(i->second)) { delete_utp_impl(i->second); if (m_last_socket == i->second) m_last_socket = 0; m_utp_sockets.erase(i++); continue; } tick_utp_impl(i->second, now); ++i; } } void utp_socket_manager::send_packet(udp::endpoint const& ep, char const* p , int len, error_code& ec) { if (!m_sock.is_open()) { ec = asio::error::operation_aborted; return; } m_sock.send(ep, p, len, ec); } tcp::endpoint utp_socket_manager::local_endpoint(error_code& ec) const { return m_sock.local_endpoint(ec); } bool utp_socket_manager::incoming_packet(char const* p, int size, udp::endpoint const& ep) { // UTP_LOGV("incoming packet size:%d\n", size); if (size < sizeof(utp_header)) return false; utp_header const* ph = (utp_header*)p; // UTP_LOGV("incoming packet version:%d\n", int(ph->ver)); if (ph->ver != 1) return false; // parse out connection ID and look for existing // connections. If found, forward to the utp_stream. boost::uint16_t id = ph->connection_id; // first test to see if it's the same socket as last time // in most cases it is if (m_last_socket && id == utp_receive_id(m_last_socket) && ep == utp_remote_endpoint(m_last_socket)) { return utp_incoming_packet(m_last_socket, p, size, ep); } socket_map_t::iterator i = m_utp_sockets.find(id); std::pair<socket_map_t::iterator, socket_map_t::iterator> r = m_utp_sockets.equal_range(id); for (; r.first != r.second; ++r.first) { if (ep != utp_remote_endpoint(r.first->second)) continue; bool ret = utp_incoming_packet(r.first->second, p, size, ep); if (ret) m_last_socket = r.first->second; return ret; } // UTP_LOGV("incoming packet id:%d source:%s\n", id, print_endpoint(ep).c_str()); if (!m_sett.enable_incoming_utp) return false; // if not found, see if it's a SYN packet, if it is, // create a new utp_stream if (ph->type == ST_SYN) { // create the new socket with this ID m_new_connection = id; // UTP_LOGV("not found, new connection id:%d\n", m_new_connection); boost::shared_ptr<socket_type> c(new (std::nothrow) socket_type(m_sock.get_io_service())); if (!c) return false; instantiate_connection(m_sock.get_io_service(), proxy_settings(), this, *c); utp_stream* str = c->get<utp_stream>(); TORRENT_ASSERT(str); bool ret = utp_incoming_packet(str->get_impl(), p, size, ep); if (!ret) return false; m_cb(c); // the connection most likely changed its connection ID here // we need to move it to the correct ID return true; } // #error send reset return false; } void utp_socket_manager::remove_socket(boost::uint16_t id) { socket_map_t::iterator i = m_utp_sockets.find(id); if (i == m_utp_sockets.end()) return; delete_utp_impl(i->second); if (m_last_socket == i->second) m_last_socket = 0; m_utp_sockets.erase(i); } utp_socket_impl* utp_socket_manager::new_utp_socket(utp_stream* str) { boost::uint16_t send_id = 0; boost::uint16_t recv_id = 0; if (m_new_connection != -1) { send_id = m_new_connection; recv_id = m_new_connection + 1; m_new_connection = -1; } else { send_id = rand(); recv_id = send_id - 1; } utp_socket_impl* impl = construct_utp_impl(recv_id, send_id, str, this); m_utp_sockets.insert(std::make_pair(recv_id, impl)); return impl; } } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "TraceListenerDefault.hpp" #include <PlatformSupport/PrintWriter.hpp> #include <DOMSupport/DOMServices.hpp> #include <XPath/NodeRefListBase.hpp> #include <XPath/XPath.hpp> #include "Constants.hpp" #include "ElemTextLiteral.hpp" #include "ElemTemplate.hpp" #include "GenerateEvent.hpp" #include "SelectionEvent.hpp" #include "StylesheetRoot.hpp" #include "TracerEvent.hpp" TraceListenerDefault::TraceListenerDefault( PrintWriter& thePrintWriter, bool traceTemplates, bool traceElements, bool traceGeneration, bool traceSelection) : m_printWriter(thePrintWriter), m_traceTemplates(traceTemplates), m_traceElements(traceElements), m_traceGeneration(traceGeneration), m_traceSelection(traceSelection) { } TraceListenerDefault::~TraceListenerDefault() { } void TraceListenerDefault::trace(const TracerEvent& ev) { switch(ev.m_styleNode.getXSLToken()) { case Constants::ELEMNAME_TEXTLITERALRESULT: if(m_traceElements == true) { m_printWriter.print(XALAN_STATIC_UCODE_STRING("Line #")); m_printWriter.print(ev.m_styleNode.getLineNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", ")); m_printWriter.print(XALAN_STATIC_UCODE_STRING("Column #")); m_printWriter.print(ev.m_styleNode.getColumnNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(": ")); m_printWriter.print(ev.m_styleNode.getElementName()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(" ")); const ElemTextLiteral& etl = #if defined(XALAN_OLD_STYLE_CASTS) (const ElemTextLiteral&)ev.m_styleNode; #else static_cast<const ElemTextLiteral&>(ev.m_styleNode); #endif m_printWriter.println(&*etl.getText().begin(), etl.getText().size()); } break; case Constants::ELEMNAME_TEMPLATE: if(m_traceTemplates == true || m_traceElements == true) { const ElemTemplate& et = #if defined(XALAN_OLD_STYLE_CASTS) (const ElemTemplate&)ev.m_styleNode; #else static_cast<const ElemTemplate&>(ev.m_styleNode); #endif m_printWriter.print(XALAN_STATIC_UCODE_STRING("Line #")); m_printWriter.print(ev.m_styleNode.getLineNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", ")); m_printWriter.print(XALAN_STATIC_UCODE_STRING("Column #")); m_printWriter.print(ev.m_styleNode.getColumnNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(": ")); m_printWriter.print(ev.m_styleNode.getElementName()); const XPath* const theMatchPattern = et.getMatchPattern(); if(0 != theMatchPattern) { m_printWriter.print(XALAN_STATIC_UCODE_STRING(" match=\"")); m_printWriter.print(theMatchPattern->getExpression().getCurrentPattern()); m_printWriter.print(XALAN_STATIC_UCODE_STRING("\" ")); } const QName& theName = et.getName(); if(theName.isEmpty() == false) { m_printWriter.print(XALAN_STATIC_UCODE_STRING("name=\"")); const XalanDOMString& theNamespace = theName.getNamespace(); if (isEmpty(theNamespace) == false) { m_printWriter.print(theNamespace); m_printWriter.print(XalanUnicode::charColon); } m_printWriter.print(theName.getLocalPart()); m_printWriter.print(XALAN_STATIC_UCODE_STRING("\" ")); } m_printWriter.println(); } break; default: if(m_traceElements == true) { m_printWriter.print(XALAN_STATIC_UCODE_STRING("Line #")); m_printWriter.print(ev.m_styleNode.getLineNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", Column #")); m_printWriter.print(ev.m_styleNode.getColumnNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(": ")); m_printWriter.println(ev.m_styleNode.getElementName()); } break; } } void TraceListenerDefault::selected(const SelectionEvent& ev) { if(m_traceSelection == true) { const ElemTemplateElement& ete = ev.m_styleNode; if(ev.m_styleNode.getLineNumber() == 0) { // You may not have line numbers if the selection is occuring from a // default template. ElemTemplateElement* const parent = ete.getParentNodeElem(); if(parent == ete.getStylesheet().getStylesheetRoot().getDefaultRootRule()) { m_printWriter.print("(default root rule) "); } else if(parent == ete.getStylesheet().getStylesheetRoot().getDefaultTextRule()) { m_printWriter.print("(default text rule) "); } else if(parent == ete.getStylesheet().getStylesheetRoot().getDefaultRule()) { m_printWriter.print("(default rule) "); } } else { m_printWriter.print(XALAN_STATIC_UCODE_STRING("Line #")); m_printWriter.print(ev.m_styleNode.getLineNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", ")); m_printWriter.print(XALAN_STATIC_UCODE_STRING("Column #")); m_printWriter.print(ev.m_styleNode.getColumnNumber()); m_printWriter.print(", "); } m_printWriter.print(ete.getElementName()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", ")); m_printWriter.print(ev.m_attributeName); m_printWriter.print(XALAN_STATIC_UCODE_STRING("=\"")); m_printWriter.print(ev.m_xpath.getExpression().getCurrentPattern()); m_printWriter.print(XALAN_STATIC_UCODE_STRING("\": ")); if (ev.m_selection.null() == true) { assert(ev.m_sourceNode != 0); m_printWriter.println(); m_printWriter.print(XALAN_STATIC_UCODE_STRING(" ")); m_printWriter.println(DOMServices::getNodeData(*ev.m_sourceNode)); } else if(ev.m_selection->getType() == XObject::eTypeNodeSet) { m_printWriter.println(); const NodeRefListBase& nl = ev.m_selection->nodeset(); const unsigned int n = nl.getLength(); if(n == 0) { m_printWriter.println(XALAN_STATIC_UCODE_STRING(" [empty node list]")); } else { for(unsigned int i = 0; i < n; i++) { assert(nl.item(i) != 0); m_printWriter.print(XALAN_STATIC_UCODE_STRING(" ")); m_printWriter.println(DOMServices::getNodeData(*nl.item(i))); } } } else { m_printWriter.println(ev.m_selection->str()); } } } void TraceListenerDefault::generated(const GenerateEvent& ev) { if(m_traceGeneration == true) { switch(ev.m_eventType) { case GenerateEvent::EVENTTYPE_STARTDOCUMENT: m_printWriter.println(XALAN_STATIC_UCODE_STRING("STARTDOCUMENT")); break; case GenerateEvent::EVENTTYPE_ENDDOCUMENT: m_printWriter.println(); m_printWriter.println(XALAN_STATIC_UCODE_STRING("ENDDOCUMENT")); break; case GenerateEvent::EVENTTYPE_STARTELEMENT: m_printWriter.print(XALAN_STATIC_UCODE_STRING("STARTELEMENT: ")); m_printWriter.println(ev.m_name); break; case GenerateEvent::EVENTTYPE_ENDELEMENT: m_printWriter.print(XALAN_STATIC_UCODE_STRING("ENDELEMENT: ")); m_printWriter.println(ev.m_name); break; case GenerateEvent::EVENTTYPE_CHARACTERS: m_printWriter.print(XALAN_STATIC_UCODE_STRING("CHARACTERS: ")); m_printWriter.println(ev.m_characters); break; case GenerateEvent::EVENTTYPE_CDATA: m_printWriter.print(XALAN_STATIC_UCODE_STRING("CDATA: ")); m_printWriter.println(ev.m_characters); break; case GenerateEvent::EVENTTYPE_COMMENT: m_printWriter.print(XALAN_STATIC_UCODE_STRING("COMMENT: ")); m_printWriter.println(ev.m_data); break; case GenerateEvent::EVENTTYPE_PI: m_printWriter.print(XALAN_STATIC_UCODE_STRING("PI: ")); m_printWriter.print(ev.m_name); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", ")); m_printWriter.println(ev.m_data); break; case GenerateEvent::EVENTTYPE_ENTITYREF: m_printWriter.println(XALAN_STATIC_UCODE_STRING("ENTITYREF: ")); m_printWriter.println(ev.m_name); break; case GenerateEvent::EVENTTYPE_IGNORABLEWHITESPACE: m_printWriter.println(XALAN_STATIC_UCODE_STRING("IGNORABLEWHITESPACE")); break; } } } <commit_msg>Changed call to get text for ElemLiteralResult.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "TraceListenerDefault.hpp" #include <PlatformSupport/PrintWriter.hpp> #include <DOMSupport/DOMServices.hpp> #include <XPath/NodeRefListBase.hpp> #include <XPath/XPath.hpp> #include "Constants.hpp" #include "ElemTextLiteral.hpp" #include "ElemTemplate.hpp" #include "GenerateEvent.hpp" #include "SelectionEvent.hpp" #include "StylesheetRoot.hpp" #include "TracerEvent.hpp" TraceListenerDefault::TraceListenerDefault( PrintWriter& thePrintWriter, bool traceTemplates, bool traceElements, bool traceGeneration, bool traceSelection) : m_printWriter(thePrintWriter), m_traceTemplates(traceTemplates), m_traceElements(traceElements), m_traceGeneration(traceGeneration), m_traceSelection(traceSelection) { } TraceListenerDefault::~TraceListenerDefault() { } void TraceListenerDefault::trace(const TracerEvent& ev) { switch(ev.m_styleNode.getXSLToken()) { case Constants::ELEMNAME_TEXTLITERALRESULT: if(m_traceElements == true) { m_printWriter.print(XALAN_STATIC_UCODE_STRING("Line #")); m_printWriter.print(ev.m_styleNode.getLineNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", ")); m_printWriter.print(XALAN_STATIC_UCODE_STRING("Column #")); m_printWriter.print(ev.m_styleNode.getColumnNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(": ")); m_printWriter.print(ev.m_styleNode.getElementName()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(" ")); const ElemTextLiteral& etl = #if defined(XALAN_OLD_STYLE_CASTS) (const ElemTextLiteral&)ev.m_styleNode; #else static_cast<const ElemTextLiteral&>(ev.m_styleNode); #endif m_printWriter.println(etl.getText()); } break; case Constants::ELEMNAME_TEMPLATE: if(m_traceTemplates == true || m_traceElements == true) { const ElemTemplate& et = #if defined(XALAN_OLD_STYLE_CASTS) (const ElemTemplate&)ev.m_styleNode; #else static_cast<const ElemTemplate&>(ev.m_styleNode); #endif m_printWriter.print(XALAN_STATIC_UCODE_STRING("Line #")); m_printWriter.print(ev.m_styleNode.getLineNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", ")); m_printWriter.print(XALAN_STATIC_UCODE_STRING("Column #")); m_printWriter.print(ev.m_styleNode.getColumnNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(": ")); m_printWriter.print(ev.m_styleNode.getElementName()); const XPath* const theMatchPattern = et.getMatchPattern(); if(0 != theMatchPattern) { m_printWriter.print(XALAN_STATIC_UCODE_STRING(" match=\"")); m_printWriter.print(theMatchPattern->getExpression().getCurrentPattern()); m_printWriter.print(XALAN_STATIC_UCODE_STRING("\" ")); } const QName& theName = et.getName(); if(theName.isEmpty() == false) { m_printWriter.print(XALAN_STATIC_UCODE_STRING("name=\"")); const XalanDOMString& theNamespace = theName.getNamespace(); if (isEmpty(theNamespace) == false) { m_printWriter.print(theNamespace); m_printWriter.print(XalanUnicode::charColon); } m_printWriter.print(theName.getLocalPart()); m_printWriter.print(XALAN_STATIC_UCODE_STRING("\" ")); } m_printWriter.println(); } break; default: if(m_traceElements == true) { m_printWriter.print(XALAN_STATIC_UCODE_STRING("Line #")); m_printWriter.print(ev.m_styleNode.getLineNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", Column #")); m_printWriter.print(ev.m_styleNode.getColumnNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(": ")); m_printWriter.println(ev.m_styleNode.getElementName()); } break; } } void TraceListenerDefault::selected(const SelectionEvent& ev) { if(m_traceSelection == true) { const ElemTemplateElement& ete = ev.m_styleNode; if(ev.m_styleNode.getLineNumber() == 0) { // You may not have line numbers if the selection is occuring from a // default template. ElemTemplateElement* const parent = ete.getParentNodeElem(); if(parent == ete.getStylesheet().getStylesheetRoot().getDefaultRootRule()) { m_printWriter.print("(default root rule) "); } else if(parent == ete.getStylesheet().getStylesheetRoot().getDefaultTextRule()) { m_printWriter.print("(default text rule) "); } else if(parent == ete.getStylesheet().getStylesheetRoot().getDefaultRule()) { m_printWriter.print("(default rule) "); } } else { m_printWriter.print(XALAN_STATIC_UCODE_STRING("Line #")); m_printWriter.print(ev.m_styleNode.getLineNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", ")); m_printWriter.print(XALAN_STATIC_UCODE_STRING("Column #")); m_printWriter.print(ev.m_styleNode.getColumnNumber()); m_printWriter.print(", "); } m_printWriter.print(ete.getElementName()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", ")); m_printWriter.print(ev.m_attributeName); m_printWriter.print(XALAN_STATIC_UCODE_STRING("=\"")); m_printWriter.print(ev.m_xpath.getExpression().getCurrentPattern()); m_printWriter.print(XALAN_STATIC_UCODE_STRING("\": ")); if (ev.m_selection.null() == true) { assert(ev.m_sourceNode != 0); m_printWriter.println(); m_printWriter.print(XALAN_STATIC_UCODE_STRING(" ")); m_printWriter.println(DOMServices::getNodeData(*ev.m_sourceNode)); } else if(ev.m_selection->getType() == XObject::eTypeNodeSet) { m_printWriter.println(); const NodeRefListBase& nl = ev.m_selection->nodeset(); const unsigned int n = nl.getLength(); if(n == 0) { m_printWriter.println(XALAN_STATIC_UCODE_STRING(" [empty node list]")); } else { for(unsigned int i = 0; i < n; i++) { assert(nl.item(i) != 0); m_printWriter.print(XALAN_STATIC_UCODE_STRING(" ")); m_printWriter.println(DOMServices::getNodeData(*nl.item(i))); } } } else { m_printWriter.println(ev.m_selection->str()); } } } void TraceListenerDefault::generated(const GenerateEvent& ev) { if(m_traceGeneration == true) { switch(ev.m_eventType) { case GenerateEvent::EVENTTYPE_STARTDOCUMENT: m_printWriter.println(XALAN_STATIC_UCODE_STRING("STARTDOCUMENT")); break; case GenerateEvent::EVENTTYPE_ENDDOCUMENT: m_printWriter.println(); m_printWriter.println(XALAN_STATIC_UCODE_STRING("ENDDOCUMENT")); break; case GenerateEvent::EVENTTYPE_STARTELEMENT: m_printWriter.print(XALAN_STATIC_UCODE_STRING("STARTELEMENT: ")); m_printWriter.println(ev.m_name); break; case GenerateEvent::EVENTTYPE_ENDELEMENT: m_printWriter.print(XALAN_STATIC_UCODE_STRING("ENDELEMENT: ")); m_printWriter.println(ev.m_name); break; case GenerateEvent::EVENTTYPE_CHARACTERS: m_printWriter.print(XALAN_STATIC_UCODE_STRING("CHARACTERS: ")); m_printWriter.println(ev.m_characters); break; case GenerateEvent::EVENTTYPE_CDATA: m_printWriter.print(XALAN_STATIC_UCODE_STRING("CDATA: ")); m_printWriter.println(ev.m_characters); break; case GenerateEvent::EVENTTYPE_COMMENT: m_printWriter.print(XALAN_STATIC_UCODE_STRING("COMMENT: ")); m_printWriter.println(ev.m_data); break; case GenerateEvent::EVENTTYPE_PI: m_printWriter.print(XALAN_STATIC_UCODE_STRING("PI: ")); m_printWriter.print(ev.m_name); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", ")); m_printWriter.println(ev.m_data); break; case GenerateEvent::EVENTTYPE_ENTITYREF: m_printWriter.println(XALAN_STATIC_UCODE_STRING("ENTITYREF: ")); m_printWriter.println(ev.m_name); break; case GenerateEvent::EVENTTYPE_IGNORABLEWHITESPACE: m_printWriter.println(XALAN_STATIC_UCODE_STRING("IGNORABLEWHITESPACE")); break; } } } <|endoftext|>
<commit_before>/* * Copyright 2011-2017 Branimir Karadzic. All rights reserved. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause */ #include "shaderc.h" namespace bgfx { bool compilePSSLShader(bx::CommandLine& _cmdLine, uint32_t _version, const std::string& _code, bx::WriterI* _writer) { BX_UNUSED(_cmdLine, _version, _code, _writer); fprintf(stderr, "PSSL compiler is not supported.\n"); return false; } } // namespace bgfx <commit_msg>Fixed build.<commit_after>/* * Copyright 2011-2017 Branimir Karadzic. All rights reserved. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause */ #include "shaderc.h" namespace bgfx { bool compilePSSLShader(const bx::CommandLine& _cmdLine, uint32_t _version, const std::string& _code, bx::WriterI* _writer) { BX_UNUSED(_cmdLine, _version, _code, _writer); fprintf(stderr, "PSSL compiler is not supported.\n"); return false; } } // namespace bgfx <|endoftext|>
<commit_before>/* Copyright (c) 2009, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/utp_stream.hpp" #include "libtorrent/udp_socket.hpp" #include "libtorrent/utp_socket_manager.hpp" #include "libtorrent/instantiate_connection.hpp" #include "libtorrent/socket_io.hpp" #include "libtorrent/broadcast_socket.hpp" // for is_teredo #include "libtorrent/random.hpp" // #define TORRENT_DEBUG_MTU 1135 namespace libtorrent { utp_socket_manager::utp_socket_manager(session_settings const& sett, udp_socket& s , incoming_utp_callback_t cb) : m_sock(s) , m_cb(cb) , m_last_socket(0) , m_new_connection(-1) , m_sett(sett) , m_last_route_update(min_time()) , m_sock_buf_size(0) {} utp_socket_manager::~utp_socket_manager() { for (socket_map_t::iterator i = m_utp_sockets.begin() , end(m_utp_sockets.end()); i != end; ++i) { delete_utp_impl(i->second); } } void utp_socket_manager::get_status(utp_status& s) const { s.num_idle = 0; s.num_syn_sent = 0; s.num_connected = 0; s.num_fin_sent = 0; s.num_close_wait = 0; for (socket_map_t::const_iterator i = m_utp_sockets.begin() , end(m_utp_sockets.end()); i != end; ++i) { int state = utp_socket_state(i->second); switch (state) { case 0: ++s.num_idle; break; case 1: ++s.num_syn_sent; break; case 2: ++s.num_connected; break; case 3: ++s.num_fin_sent; break; case 4: ++s.num_close_wait; break; case 5: ++s.num_close_wait; break; } } } void utp_socket_manager::tick(ptime now) { for (socket_map_t::iterator i = m_utp_sockets.begin() , end(m_utp_sockets.end()); i != end;) { if (should_delete(i->second)) { delete_utp_impl(i->second); if (m_last_socket == i->second) m_last_socket = 0; m_utp_sockets.erase(i++); continue; } tick_utp_impl(i->second, now); ++i; } } void utp_socket_manager::mtu_for_dest(address const& addr, int& link_mtu, int& utp_mtu) { if (time_now() - m_last_route_update > seconds(60)) { m_last_route_update = time_now(); error_code ec; m_routes = enum_routes(m_sock.get_io_service(), ec); } int mtu = 0; if (!m_routes.empty()) { for (std::vector<ip_route>::iterator i = m_routes.begin() , end(m_routes.end()); i != end; ++i) { if (!match_addr_mask(addr, i->destination, i->netmask)) continue; // assume that we'll actually use the route with the largest // MTU (seems like a reasonable assumption). // this could however be improved by using the route metrics // and the prefix length of the netmask to order the matches if (mtu < i->mtu) mtu = i->mtu; } } if (mtu == 0) { if (is_teredo(addr)) mtu = TORRENT_TEREDO_MTU; else mtu = TORRENT_ETHERNET_MTU; } // clamp the MTU within reasonable bounds if (mtu < TORRENT_INET_MIN_MTU) mtu = TORRENT_INET_MIN_MTU; else if (mtu > TORRENT_INET_MAX_MTU) mtu = TORRENT_INET_MAX_MTU; link_mtu = mtu; mtu -= TORRENT_UDP_HEADER; if (m_sock.get_proxy_settings().type == proxy_settings::socks5 || m_sock.get_proxy_settings().type == proxy_settings::socks5_pw) { // this is for the IP layer address proxy_addr = m_sock.proxy_addr().address(); if (proxy_addr.is_v4()) mtu -= TORRENT_IPV4_HEADER; else mtu -= TORRENT_IPV6_HEADER; // this is for the SOCKS layer mtu -= TORRENT_SOCKS5_HEADER; // the address field in the SOCKS header if (addr.is_v4()) mtu -= 4; else mtu -= 16; } else { if (addr.is_v4()) mtu -= TORRENT_IPV4_HEADER; else mtu -= TORRENT_IPV6_HEADER; } utp_mtu = mtu; } void utp_socket_manager::send_packet(udp::endpoint const& ep, char const* p , int len, error_code& ec, int flags) { if (!m_sock.is_open()) { ec = asio::error::operation_aborted; return; } #ifdef TORRENT_DEBUG_MTU // drop packets that exceed the debug MTU if ((flags & dont_fragment) && len > TORRENT_DEBUG_MTU) return; #endif #ifdef TORRENT_HAS_DONT_FRAGMENT error_code tmp; if (flags & utp_socket_manager::dont_fragment) m_sock.set_option(libtorrent::dont_fragment(true), tmp); #endif m_sock.send(ep, p, len, ec); #ifdef TORRENT_HAS_DONT_FRAGMENT if (flags & utp_socket_manager::dont_fragment) m_sock.set_option(libtorrent::dont_fragment(false), tmp); #endif } tcp::endpoint utp_socket_manager::local_endpoint(error_code& ec) const { return m_sock.local_endpoint(ec); } bool utp_socket_manager::incoming_packet(char const* p, int size, udp::endpoint const& ep) { // UTP_LOGV("incoming packet size:%d\n", size); if (size < int(sizeof(utp_header))) return false; utp_header const* ph = (utp_header*)p; // UTP_LOGV("incoming packet version:%d\n", int(ph->get_version())); if (ph->get_version() != 1) return false; const ptime receive_time = time_now_hires(); // parse out connection ID and look for existing // connections. If found, forward to the utp_stream. boost::uint16_t id = ph->connection_id; // first test to see if it's the same socket as last time // in most cases it is if (m_last_socket && utp_match(m_last_socket, ep, id)) { return utp_incoming_packet(m_last_socket, p, size, ep, receive_time); } std::pair<socket_map_t::iterator, socket_map_t::iterator> r = m_utp_sockets.equal_range(id); for (; r.first != r.second; ++r.first) { if (!utp_match(r.first->second, ep, id)) continue; bool ret = utp_incoming_packet(r.first->second, p, size, ep, receive_time); if (ret) m_last_socket = r.first->second; return ret; } // UTP_LOGV("incoming packet id:%d source:%s\n", id, print_endpoint(ep).c_str()); if (!m_sett.enable_incoming_utp) return false; // if not found, see if it's a SYN packet, if it is, // create a new utp_stream if (ph->get_type() == ST_SYN) { // create the new socket with this ID m_new_connection = id; // UTP_LOGV("not found, new connection id:%d\n", m_new_connection); boost::shared_ptr<socket_type> c(new (std::nothrow) socket_type(m_sock.get_io_service())); if (!c) return false; instantiate_connection(m_sock.get_io_service(), proxy_settings(), *c, 0, this); utp_stream* str = c->get<utp_stream>(); TORRENT_ASSERT(str); int link_mtu, utp_mtu; mtu_for_dest(ep.address(), link_mtu, utp_mtu); utp_init_mtu(str->get_impl(), link_mtu, utp_mtu); bool ret = utp_incoming_packet(str->get_impl(), p, size, ep, receive_time); if (!ret) return false; m_cb(c); // the connection most likely changed its connection ID here // we need to move it to the correct ID return true; } // #error send reset return false; } void utp_socket_manager::remove_socket(boost::uint16_t id) { socket_map_t::iterator i = m_utp_sockets.find(id); if (i == m_utp_sockets.end()) return; delete_utp_impl(i->second); if (m_last_socket == i->second) m_last_socket = 0; m_utp_sockets.erase(i); } void utp_socket_manager::set_sock_buf(int size) { if (size < m_sock_buf_size) return; m_sock.set_buf_size(size); error_code ec; // add more socket buffer storage on the lower level socket // to avoid dropping packets because of a full receive buffer // while processing a packet // only update the buffer size if it's bigger than // what we already have datagram_socket::receive_buffer_size recv_buf_size_opt; m_sock.get_option(recv_buf_size_opt, ec); if (recv_buf_size_opt.value() < size * 10) { m_sock.set_option(datagram_socket::receive_buffer_size(size * 10), ec); m_sock.set_option(datagram_socket::send_buffer_size(size * 3), ec); } m_sock_buf_size = size; } utp_socket_impl* utp_socket_manager::new_utp_socket(utp_stream* str) { boost::uint16_t send_id = 0; boost::uint16_t recv_id = 0; if (m_new_connection != -1) { send_id = m_new_connection; recv_id = m_new_connection + 1; m_new_connection = -1; } else { send_id = random(); recv_id = send_id - 1; } utp_socket_impl* impl = construct_utp_impl(recv_id, send_id, str, this); m_utp_sockets.insert(std::make_pair(recv_id, impl)); return impl; } } <commit_msg>don't accept incoming uTP connections indefinitely<commit_after>/* Copyright (c) 2009, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/utp_stream.hpp" #include "libtorrent/udp_socket.hpp" #include "libtorrent/utp_socket_manager.hpp" #include "libtorrent/instantiate_connection.hpp" #include "libtorrent/socket_io.hpp" #include "libtorrent/broadcast_socket.hpp" // for is_teredo #include "libtorrent/random.hpp" // #define TORRENT_DEBUG_MTU 1135 namespace libtorrent { utp_socket_manager::utp_socket_manager(session_settings const& sett, udp_socket& s , incoming_utp_callback_t cb) : m_sock(s) , m_cb(cb) , m_last_socket(0) , m_new_connection(-1) , m_sett(sett) , m_last_route_update(min_time()) , m_sock_buf_size(0) {} utp_socket_manager::~utp_socket_manager() { for (socket_map_t::iterator i = m_utp_sockets.begin() , end(m_utp_sockets.end()); i != end; ++i) { delete_utp_impl(i->second); } } void utp_socket_manager::get_status(utp_status& s) const { s.num_idle = 0; s.num_syn_sent = 0; s.num_connected = 0; s.num_fin_sent = 0; s.num_close_wait = 0; for (socket_map_t::const_iterator i = m_utp_sockets.begin() , end(m_utp_sockets.end()); i != end; ++i) { int state = utp_socket_state(i->second); switch (state) { case 0: ++s.num_idle; break; case 1: ++s.num_syn_sent; break; case 2: ++s.num_connected; break; case 3: ++s.num_fin_sent; break; case 4: ++s.num_close_wait; break; case 5: ++s.num_close_wait; break; } } } void utp_socket_manager::tick(ptime now) { for (socket_map_t::iterator i = m_utp_sockets.begin() , end(m_utp_sockets.end()); i != end;) { if (should_delete(i->second)) { delete_utp_impl(i->second); if (m_last_socket == i->second) m_last_socket = 0; m_utp_sockets.erase(i++); continue; } tick_utp_impl(i->second, now); ++i; } } void utp_socket_manager::mtu_for_dest(address const& addr, int& link_mtu, int& utp_mtu) { if (time_now() - m_last_route_update > seconds(60)) { m_last_route_update = time_now(); error_code ec; m_routes = enum_routes(m_sock.get_io_service(), ec); } int mtu = 0; if (!m_routes.empty()) { for (std::vector<ip_route>::iterator i = m_routes.begin() , end(m_routes.end()); i != end; ++i) { if (!match_addr_mask(addr, i->destination, i->netmask)) continue; // assume that we'll actually use the route with the largest // MTU (seems like a reasonable assumption). // this could however be improved by using the route metrics // and the prefix length of the netmask to order the matches if (mtu < i->mtu) mtu = i->mtu; } } if (mtu == 0) { if (is_teredo(addr)) mtu = TORRENT_TEREDO_MTU; else mtu = TORRENT_ETHERNET_MTU; } // clamp the MTU within reasonable bounds if (mtu < TORRENT_INET_MIN_MTU) mtu = TORRENT_INET_MIN_MTU; else if (mtu > TORRENT_INET_MAX_MTU) mtu = TORRENT_INET_MAX_MTU; link_mtu = mtu; mtu -= TORRENT_UDP_HEADER; if (m_sock.get_proxy_settings().type == proxy_settings::socks5 || m_sock.get_proxy_settings().type == proxy_settings::socks5_pw) { // this is for the IP layer address proxy_addr = m_sock.proxy_addr().address(); if (proxy_addr.is_v4()) mtu -= TORRENT_IPV4_HEADER; else mtu -= TORRENT_IPV6_HEADER; // this is for the SOCKS layer mtu -= TORRENT_SOCKS5_HEADER; // the address field in the SOCKS header if (addr.is_v4()) mtu -= 4; else mtu -= 16; } else { if (addr.is_v4()) mtu -= TORRENT_IPV4_HEADER; else mtu -= TORRENT_IPV6_HEADER; } utp_mtu = mtu; } void utp_socket_manager::send_packet(udp::endpoint const& ep, char const* p , int len, error_code& ec, int flags) { if (!m_sock.is_open()) { ec = asio::error::operation_aborted; return; } #ifdef TORRENT_DEBUG_MTU // drop packets that exceed the debug MTU if ((flags & dont_fragment) && len > TORRENT_DEBUG_MTU) return; #endif #ifdef TORRENT_HAS_DONT_FRAGMENT error_code tmp; if (flags & utp_socket_manager::dont_fragment) m_sock.set_option(libtorrent::dont_fragment(true), tmp); #endif m_sock.send(ep, p, len, ec); #ifdef TORRENT_HAS_DONT_FRAGMENT if (flags & utp_socket_manager::dont_fragment) m_sock.set_option(libtorrent::dont_fragment(false), tmp); #endif } tcp::endpoint utp_socket_manager::local_endpoint(error_code& ec) const { return m_sock.local_endpoint(ec); } bool utp_socket_manager::incoming_packet(char const* p, int size, udp::endpoint const& ep) { // UTP_LOGV("incoming packet size:%d\n", size); if (size < int(sizeof(utp_header))) return false; utp_header const* ph = (utp_header*)p; // UTP_LOGV("incoming packet version:%d\n", int(ph->get_version())); if (ph->get_version() != 1) return false; const ptime receive_time = time_now_hires(); // parse out connection ID and look for existing // connections. If found, forward to the utp_stream. boost::uint16_t id = ph->connection_id; // first test to see if it's the same socket as last time // in most cases it is if (m_last_socket && utp_match(m_last_socket, ep, id)) { return utp_incoming_packet(m_last_socket, p, size, ep, receive_time); } std::pair<socket_map_t::iterator, socket_map_t::iterator> r = m_utp_sockets.equal_range(id); for (; r.first != r.second; ++r.first) { if (!utp_match(r.first->second, ep, id)) continue; bool ret = utp_incoming_packet(r.first->second, p, size, ep, receive_time); if (ret) m_last_socket = r.first->second; return ret; } // UTP_LOGV("incoming packet id:%d source:%s\n", id, print_endpoint(ep).c_str()); if (!m_sett.enable_incoming_utp) return false; // if not found, see if it's a SYN packet, if it is, // create a new utp_stream if (ph->get_type() == ST_SYN) { // possible SYN flood. Just ignore if (m_utp_sockets.size() > m_sett.connections_limit * 2) return false; // create the new socket with this ID m_new_connection = id; // UTP_LOGV("not found, new connection id:%d\n", m_new_connection); boost::shared_ptr<socket_type> c(new (std::nothrow) socket_type(m_sock.get_io_service())); if (!c) return false; instantiate_connection(m_sock.get_io_service(), proxy_settings(), *c, 0, this); utp_stream* str = c->get<utp_stream>(); TORRENT_ASSERT(str); int link_mtu, utp_mtu; mtu_for_dest(ep.address(), link_mtu, utp_mtu); utp_init_mtu(str->get_impl(), link_mtu, utp_mtu); bool ret = utp_incoming_packet(str->get_impl(), p, size, ep, receive_time); if (!ret) return false; m_cb(c); // the connection most likely changed its connection ID here // we need to move it to the correct ID return true; } // #error send reset return false; } void utp_socket_manager::remove_socket(boost::uint16_t id) { socket_map_t::iterator i = m_utp_sockets.find(id); if (i == m_utp_sockets.end()) return; delete_utp_impl(i->second); if (m_last_socket == i->second) m_last_socket = 0; m_utp_sockets.erase(i); } void utp_socket_manager::set_sock_buf(int size) { if (size < m_sock_buf_size) return; m_sock.set_buf_size(size); error_code ec; // add more socket buffer storage on the lower level socket // to avoid dropping packets because of a full receive buffer // while processing a packet // only update the buffer size if it's bigger than // what we already have datagram_socket::receive_buffer_size recv_buf_size_opt; m_sock.get_option(recv_buf_size_opt, ec); if (recv_buf_size_opt.value() < size * 10) { m_sock.set_option(datagram_socket::receive_buffer_size(size * 10), ec); m_sock.set_option(datagram_socket::send_buffer_size(size * 3), ec); } m_sock_buf_size = size; } utp_socket_impl* utp_socket_manager::new_utp_socket(utp_stream* str) { boost::uint16_t send_id = 0; boost::uint16_t recv_id = 0; if (m_new_connection != -1) { send_id = m_new_connection; recv_id = m_new_connection + 1; m_new_connection = -1; } else { send_id = random(); recv_id = send_id - 1; } utp_socket_impl* impl = construct_utp_impl(recv_id, send_id, str, this); m_utp_sockets.insert(std::make_pair(recv_id, impl)); return impl; } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: color.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: ssa $ $Date: 2002-06-26 16:40:33 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <stdlib.h> #ifndef _VOS_MACROS_HXX_ #include <vos/macros.hxx> #endif #ifndef _TOOLS_COLOR_HXX #include <color.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <debug.hxx> #endif #ifndef _STREAM_HXX #include <stream.hxx> #endif // ----------- // - Inlines - // ----------- static inline long _FRound( double fVal ) { return( fVal > 0.0 ? (long) ( fVal + 0.5 ) : -(long) ( -fVal + 0.5 ) ); } // --------- // - Color - // --------- UINT8 Color::GetColorError( const Color& rCompareColor ) const { const long nErrAbs = labs( (long) rCompareColor.GetRed() - GetRed() ) + labs( (long) rCompareColor.GetGreen() - GetGreen() ) + labs( (long) rCompareColor.GetBlue() - GetBlue() ); return (UINT8) _FRound( nErrAbs * 0.3333333333 ); } // ----------------------------------------------------------------------- void Color::IncreaseLuminance( UINT8 cLumInc ) { SetRed( (UINT8) VOS_BOUND( (long) COLORDATA_RED( mnColor ) + cLumInc, 0L, 255L ) ); SetGreen( (UINT8) VOS_BOUND( (long) COLORDATA_GREEN( mnColor ) + cLumInc, 0L, 255L ) ); SetBlue( (UINT8) VOS_BOUND( (long) COLORDATA_BLUE( mnColor ) + cLumInc, 0L, 255L ) ); } // ----------------------------------------------------------------------- void Color::DecreaseLuminance( UINT8 cLumDec ) { SetRed( (UINT8) VOS_BOUND( (long) COLORDATA_RED( mnColor ) - cLumDec, 0L, 255L ) ); SetGreen( (UINT8) VOS_BOUND( (long) COLORDATA_GREEN( mnColor ) - cLumDec, 0L, 255L ) ); SetBlue( (UINT8) VOS_BOUND( (long) COLORDATA_BLUE( mnColor ) - cLumDec, 0L, 255L ) ); } // ----------------------------------------------------------------------- void Color::IncreaseContrast( UINT8 cContInc ) { if( cContInc) { const double fM = 128.0 / ( 128.0 - 0.4985 * cContInc ); const double fOff = 128.0 - fM * 128.0; SetRed( (UINT8) VOS_BOUND( _FRound( COLORDATA_RED( mnColor ) * fM + fOff ), 0L, 255L ) ); SetGreen( (UINT8) VOS_BOUND( _FRound( COLORDATA_GREEN( mnColor ) * fM + fOff ), 0L, 255L ) ); SetBlue( (UINT8) VOS_BOUND( _FRound( COLORDATA_BLUE( mnColor ) * fM + fOff ), 0L, 255L ) ); } } // ----------------------------------------------------------------------- void Color::DecreaseContrast( UINT8 cContDec ) { if( cContDec ) { const double fM = ( 128.0 - 0.4985 * cContDec ) / 128.0; const double fOff = 128.0 - fM * 128.0; SetRed( (UINT8) VOS_BOUND( _FRound( COLORDATA_RED( mnColor ) * fM + fOff ), 0L, 255L ) ); SetGreen( (UINT8) VOS_BOUND( _FRound( COLORDATA_GREEN( mnColor ) * fM + fOff ), 0L, 255L ) ); SetBlue( (UINT8) VOS_BOUND( _FRound( COLORDATA_BLUE( mnColor ) * fM + fOff ), 0L, 255L ) ); } } // ----------------------------------------------------------------------- void Color::Invert() { SetRed( ~COLORDATA_RED( mnColor ) ); SetGreen( ~COLORDATA_GREEN( mnColor ) ); SetBlue( ~COLORDATA_BLUE( mnColor ) ); } // ----------------------------------------------------------------------- BOOL Color::IsDark() const { return GetLuminance() <= 25; } // ----------------------------------------------------------------------- BOOL Color::IsBright() const { return GetLuminance() >= 245; } // ----------------------------------------------------------------------- SvStream& Color::Read( SvStream& rIStm, BOOL bNewFormat ) { if ( bNewFormat ) rIStm >> mnColor; else rIStm >> *this; return rIStm; } // ----------------------------------------------------------------------- SvStream& Color::Write( SvStream& rOStm, BOOL bNewFormat ) { if ( bNewFormat ) rOStm << mnColor; else rOStm << *this; return rOStm; } // ----------------------------------------------------------------------- #define COL_NAME_USER ((USHORT)0x8000) #define COL_RED_1B ((USHORT)0x0001) #define COL_RED_2B ((USHORT)0x0002) #define COL_GREEN_1B ((USHORT)0x0010) #define COL_GREEN_2B ((USHORT)0x0020) #define COL_BLUE_1B ((USHORT)0x0100) #define COL_BLUE_2B ((USHORT)0x0200) // ----------------------------------------------------------------------- SvStream& operator>>( SvStream& rIStream, Color& rColor ) { DBG_ASSERTWARNING( rIStream.GetVersion(), "Color::>> - Solar-Version not set on rIStream" ); USHORT nColorName; USHORT nRed; USHORT nGreen; USHORT nBlue; rIStream >> nColorName; if ( nColorName & COL_NAME_USER ) { if ( rIStream.GetCompressMode() == COMPRESSMODE_FULL ) { unsigned char cAry[6]; USHORT i = 0; nRed = 0; nGreen = 0; nBlue = 0; if ( nColorName & COL_RED_2B ) i += 2; else if ( nColorName & COL_RED_1B ) i++; if ( nColorName & COL_GREEN_2B ) i += 2; else if ( nColorName & COL_GREEN_1B ) i++; if ( nColorName & COL_BLUE_2B ) i += 2; else if ( nColorName & COL_BLUE_1B ) i++; rIStream.Read( cAry, i ); i = 0; if ( nColorName & COL_RED_2B ) { nRed = cAry[i]; nRed <<= 8; i++; nRed |= cAry[i]; i++; } else if ( nColorName & COL_RED_1B ) { nRed = cAry[i]; nRed <<= 8; i++; } if ( nColorName & COL_GREEN_2B ) { nGreen = cAry[i]; nGreen <<= 8; i++; nGreen |= cAry[i]; i++; } else if ( nColorName & COL_GREEN_1B ) { nGreen = cAry[i]; nGreen <<= 8; i++; } if ( nColorName & COL_BLUE_2B ) { nBlue = cAry[i]; nBlue <<= 8; i++; nBlue |= cAry[i]; i++; } else if ( nColorName & COL_BLUE_1B ) { nBlue = cAry[i]; nBlue <<= 8; i++; } } else { rIStream >> nRed; rIStream >> nGreen; rIStream >> nBlue; } rColor.mnColor = RGB_COLORDATA( nRed>>8, nGreen>>8, nBlue>>8 ); } else { static ColorData aColAry[] = { COL_BLACK, // COL_BLACK COL_BLUE, // COL_BLUE COL_GREEN, // COL_GREEN COL_CYAN, // COL_CYAN COL_RED, // COL_RED COL_MAGENTA, // COL_MAGENTA COL_BROWN, // COL_BROWN COL_GRAY, // COL_GRAY COL_LIGHTGRAY, // COL_LIGHTGRAY COL_LIGHTBLUE, // COL_LIGHTBLUE COL_LIGHTGREEN, // COL_LIGHTGREEN COL_LIGHTCYAN, // COL_LIGHTCYAN COL_LIGHTRED, // COL_LIGHTRED COL_LIGHTMAGENTA, // COL_LIGHTMAGENTA COL_YELLOW, // COL_YELLOW COL_WHITE, // COL_WHITE COL_WHITE, // COL_MENUBAR COL_BLACK, // COL_MENUBARTEXT COL_WHITE, // COL_POPUPMENU COL_BLACK, // COL_POPUPMENUTEXT COL_BLACK, // COL_WINDOWTEXT COL_WHITE, // COL_WINDOWWORKSPACE COL_BLACK, // COL_HIGHLIGHT COL_WHITE, // COL_HIGHLIGHTTEXT COL_BLACK, // COL_3DTEXT COL_LIGHTGRAY, // COL_3DFACE COL_WHITE, // COL_3DLIGHT COL_GRAY, // COL_3DSHADOW COL_LIGHTGRAY, // COL_SCROLLBAR COL_WHITE, // COL_FIELD COL_BLACK // COL_FIELDTEXT }; if ( nColorName < (sizeof( aColAry )/sizeof(ColorData)) ) rColor.mnColor = aColAry[nColorName]; else rColor.mnColor = COL_BLACK; } return rIStream; } // ----------------------------------------------------------------------- SvStream& operator<<( SvStream& rOStream, const Color& rColor ) { DBG_ASSERTWARNING( rOStream.GetVersion(), "Color::<< - Solar-Version not set on rOStream" ); USHORT nColorName = COL_NAME_USER; USHORT nRed = rColor.GetRed(); USHORT nGreen = rColor.GetGreen(); USHORT nBlue = rColor.GetBlue(); nRed = (nRed<<8) + nRed; nGreen = (nGreen<<8) + nGreen; nBlue = (nBlue<<8) + nBlue; if ( rOStream.GetCompressMode() == COMPRESSMODE_FULL ) { unsigned char cAry[6]; USHORT i = 0; if ( nRed & 0x00FF ) { nColorName |= COL_RED_2B; cAry[i] = (unsigned char)(nRed & 0xFF); i++; cAry[i] = (unsigned char)((nRed >> 8) & 0xFF); i++; } else if ( nRed & 0xFF00 ) { nColorName |= COL_RED_1B; cAry[i] = (unsigned char)((nRed >> 8) & 0xFF); i++; } if ( nGreen & 0x00FF ) { nColorName |= COL_GREEN_2B; cAry[i] = (unsigned char)(nGreen & 0xFF); i++; cAry[i] = (unsigned char)((nGreen >> 8) & 0xFF); i++; } else if ( nGreen & 0xFF00 ) { nColorName |= COL_GREEN_1B; cAry[i] = (unsigned char)((nGreen >> 8) & 0xFF); i++; } if ( nBlue & 0x00FF ) { nColorName |= COL_BLUE_2B; cAry[i] = (unsigned char)(nBlue & 0xFF); i++; cAry[i] = (unsigned char)((nBlue >> 8) & 0xFF); i++; } else if ( nBlue & 0xFF00 ) { nColorName |= COL_BLUE_1B; cAry[i] = (unsigned char)((nBlue >> 8) & 0xFF); i++; } rOStream << nColorName; rOStream.Write( cAry, i ); } else { rOStream << nColorName; rOStream << nRed; rOStream << nGreen; rOStream << nBlue; } return rOStream; } <commit_msg>#103729# tweak IsDark to MS compatibility<commit_after>/************************************************************************* * * $RCSfile: color.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: ssa $ $Date: 2002-10-24 12:10:57 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <stdlib.h> #ifndef _VOS_MACROS_HXX_ #include <vos/macros.hxx> #endif #ifndef _TOOLS_COLOR_HXX #include <color.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <debug.hxx> #endif #ifndef _STREAM_HXX #include <stream.hxx> #endif // ----------- // - Inlines - // ----------- static inline long _FRound( double fVal ) { return( fVal > 0.0 ? (long) ( fVal + 0.5 ) : -(long) ( -fVal + 0.5 ) ); } // --------- // - Color - // --------- UINT8 Color::GetColorError( const Color& rCompareColor ) const { const long nErrAbs = labs( (long) rCompareColor.GetRed() - GetRed() ) + labs( (long) rCompareColor.GetGreen() - GetGreen() ) + labs( (long) rCompareColor.GetBlue() - GetBlue() ); return (UINT8) _FRound( nErrAbs * 0.3333333333 ); } // ----------------------------------------------------------------------- void Color::IncreaseLuminance( UINT8 cLumInc ) { SetRed( (UINT8) VOS_BOUND( (long) COLORDATA_RED( mnColor ) + cLumInc, 0L, 255L ) ); SetGreen( (UINT8) VOS_BOUND( (long) COLORDATA_GREEN( mnColor ) + cLumInc, 0L, 255L ) ); SetBlue( (UINT8) VOS_BOUND( (long) COLORDATA_BLUE( mnColor ) + cLumInc, 0L, 255L ) ); } // ----------------------------------------------------------------------- void Color::DecreaseLuminance( UINT8 cLumDec ) { SetRed( (UINT8) VOS_BOUND( (long) COLORDATA_RED( mnColor ) - cLumDec, 0L, 255L ) ); SetGreen( (UINT8) VOS_BOUND( (long) COLORDATA_GREEN( mnColor ) - cLumDec, 0L, 255L ) ); SetBlue( (UINT8) VOS_BOUND( (long) COLORDATA_BLUE( mnColor ) - cLumDec, 0L, 255L ) ); } // ----------------------------------------------------------------------- void Color::IncreaseContrast( UINT8 cContInc ) { if( cContInc) { const double fM = 128.0 / ( 128.0 - 0.4985 * cContInc ); const double fOff = 128.0 - fM * 128.0; SetRed( (UINT8) VOS_BOUND( _FRound( COLORDATA_RED( mnColor ) * fM + fOff ), 0L, 255L ) ); SetGreen( (UINT8) VOS_BOUND( _FRound( COLORDATA_GREEN( mnColor ) * fM + fOff ), 0L, 255L ) ); SetBlue( (UINT8) VOS_BOUND( _FRound( COLORDATA_BLUE( mnColor ) * fM + fOff ), 0L, 255L ) ); } } // ----------------------------------------------------------------------- void Color::DecreaseContrast( UINT8 cContDec ) { if( cContDec ) { const double fM = ( 128.0 - 0.4985 * cContDec ) / 128.0; const double fOff = 128.0 - fM * 128.0; SetRed( (UINT8) VOS_BOUND( _FRound( COLORDATA_RED( mnColor ) * fM + fOff ), 0L, 255L ) ); SetGreen( (UINT8) VOS_BOUND( _FRound( COLORDATA_GREEN( mnColor ) * fM + fOff ), 0L, 255L ) ); SetBlue( (UINT8) VOS_BOUND( _FRound( COLORDATA_BLUE( mnColor ) * fM + fOff ), 0L, 255L ) ); } } // ----------------------------------------------------------------------- void Color::Invert() { SetRed( ~COLORDATA_RED( mnColor ) ); SetGreen( ~COLORDATA_GREEN( mnColor ) ); SetBlue( ~COLORDATA_BLUE( mnColor ) ); } // ----------------------------------------------------------------------- BOOL Color::IsDark() const { // #103729# favour compatibility to Word return GetRed()+GetGreen()+GetBlue() < 154; //return GetLuminance() <= 25; } // ----------------------------------------------------------------------- BOOL Color::IsBright() const { return GetLuminance() >= 245; } // ----------------------------------------------------------------------- SvStream& Color::Read( SvStream& rIStm, BOOL bNewFormat ) { if ( bNewFormat ) rIStm >> mnColor; else rIStm >> *this; return rIStm; } // ----------------------------------------------------------------------- SvStream& Color::Write( SvStream& rOStm, BOOL bNewFormat ) { if ( bNewFormat ) rOStm << mnColor; else rOStm << *this; return rOStm; } // ----------------------------------------------------------------------- #define COL_NAME_USER ((USHORT)0x8000) #define COL_RED_1B ((USHORT)0x0001) #define COL_RED_2B ((USHORT)0x0002) #define COL_GREEN_1B ((USHORT)0x0010) #define COL_GREEN_2B ((USHORT)0x0020) #define COL_BLUE_1B ((USHORT)0x0100) #define COL_BLUE_2B ((USHORT)0x0200) // ----------------------------------------------------------------------- SvStream& operator>>( SvStream& rIStream, Color& rColor ) { DBG_ASSERTWARNING( rIStream.GetVersion(), "Color::>> - Solar-Version not set on rIStream" ); USHORT nColorName; USHORT nRed; USHORT nGreen; USHORT nBlue; rIStream >> nColorName; if ( nColorName & COL_NAME_USER ) { if ( rIStream.GetCompressMode() == COMPRESSMODE_FULL ) { unsigned char cAry[6]; USHORT i = 0; nRed = 0; nGreen = 0; nBlue = 0; if ( nColorName & COL_RED_2B ) i += 2; else if ( nColorName & COL_RED_1B ) i++; if ( nColorName & COL_GREEN_2B ) i += 2; else if ( nColorName & COL_GREEN_1B ) i++; if ( nColorName & COL_BLUE_2B ) i += 2; else if ( nColorName & COL_BLUE_1B ) i++; rIStream.Read( cAry, i ); i = 0; if ( nColorName & COL_RED_2B ) { nRed = cAry[i]; nRed <<= 8; i++; nRed |= cAry[i]; i++; } else if ( nColorName & COL_RED_1B ) { nRed = cAry[i]; nRed <<= 8; i++; } if ( nColorName & COL_GREEN_2B ) { nGreen = cAry[i]; nGreen <<= 8; i++; nGreen |= cAry[i]; i++; } else if ( nColorName & COL_GREEN_1B ) { nGreen = cAry[i]; nGreen <<= 8; i++; } if ( nColorName & COL_BLUE_2B ) { nBlue = cAry[i]; nBlue <<= 8; i++; nBlue |= cAry[i]; i++; } else if ( nColorName & COL_BLUE_1B ) { nBlue = cAry[i]; nBlue <<= 8; i++; } } else { rIStream >> nRed; rIStream >> nGreen; rIStream >> nBlue; } rColor.mnColor = RGB_COLORDATA( nRed>>8, nGreen>>8, nBlue>>8 ); } else { static ColorData aColAry[] = { COL_BLACK, // COL_BLACK COL_BLUE, // COL_BLUE COL_GREEN, // COL_GREEN COL_CYAN, // COL_CYAN COL_RED, // COL_RED COL_MAGENTA, // COL_MAGENTA COL_BROWN, // COL_BROWN COL_GRAY, // COL_GRAY COL_LIGHTGRAY, // COL_LIGHTGRAY COL_LIGHTBLUE, // COL_LIGHTBLUE COL_LIGHTGREEN, // COL_LIGHTGREEN COL_LIGHTCYAN, // COL_LIGHTCYAN COL_LIGHTRED, // COL_LIGHTRED COL_LIGHTMAGENTA, // COL_LIGHTMAGENTA COL_YELLOW, // COL_YELLOW COL_WHITE, // COL_WHITE COL_WHITE, // COL_MENUBAR COL_BLACK, // COL_MENUBARTEXT COL_WHITE, // COL_POPUPMENU COL_BLACK, // COL_POPUPMENUTEXT COL_BLACK, // COL_WINDOWTEXT COL_WHITE, // COL_WINDOWWORKSPACE COL_BLACK, // COL_HIGHLIGHT COL_WHITE, // COL_HIGHLIGHTTEXT COL_BLACK, // COL_3DTEXT COL_LIGHTGRAY, // COL_3DFACE COL_WHITE, // COL_3DLIGHT COL_GRAY, // COL_3DSHADOW COL_LIGHTGRAY, // COL_SCROLLBAR COL_WHITE, // COL_FIELD COL_BLACK // COL_FIELDTEXT }; if ( nColorName < (sizeof( aColAry )/sizeof(ColorData)) ) rColor.mnColor = aColAry[nColorName]; else rColor.mnColor = COL_BLACK; } return rIStream; } // ----------------------------------------------------------------------- SvStream& operator<<( SvStream& rOStream, const Color& rColor ) { DBG_ASSERTWARNING( rOStream.GetVersion(), "Color::<< - Solar-Version not set on rOStream" ); USHORT nColorName = COL_NAME_USER; USHORT nRed = rColor.GetRed(); USHORT nGreen = rColor.GetGreen(); USHORT nBlue = rColor.GetBlue(); nRed = (nRed<<8) + nRed; nGreen = (nGreen<<8) + nGreen; nBlue = (nBlue<<8) + nBlue; if ( rOStream.GetCompressMode() == COMPRESSMODE_FULL ) { unsigned char cAry[6]; USHORT i = 0; if ( nRed & 0x00FF ) { nColorName |= COL_RED_2B; cAry[i] = (unsigned char)(nRed & 0xFF); i++; cAry[i] = (unsigned char)((nRed >> 8) & 0xFF); i++; } else if ( nRed & 0xFF00 ) { nColorName |= COL_RED_1B; cAry[i] = (unsigned char)((nRed >> 8) & 0xFF); i++; } if ( nGreen & 0x00FF ) { nColorName |= COL_GREEN_2B; cAry[i] = (unsigned char)(nGreen & 0xFF); i++; cAry[i] = (unsigned char)((nGreen >> 8) & 0xFF); i++; } else if ( nGreen & 0xFF00 ) { nColorName |= COL_GREEN_1B; cAry[i] = (unsigned char)((nGreen >> 8) & 0xFF); i++; } if ( nBlue & 0x00FF ) { nColorName |= COL_BLUE_2B; cAry[i] = (unsigned char)(nBlue & 0xFF); i++; cAry[i] = (unsigned char)((nBlue >> 8) & 0xFF); i++; } else if ( nBlue & 0xFF00 ) { nColorName |= COL_BLUE_1B; cAry[i] = (unsigned char)((nBlue >> 8) & 0xFF); i++; } rOStream << nColorName; rOStream.Write( cAry, i ); } else { rOStream << nColorName; rOStream << nRed; rOStream << nGreen; rOStream << nBlue; } return rOStream; } <|endoftext|>
<commit_before>#include "../screenshot.hpp" #define EzApp EasyGIF::App #define EzUI EasyGIF::UI EzApp::Screenshot::Screenshot() { // create a new RegionPicker but do not activate yet m_Picker = new EzUI::RegionPicker(false); } void EzApp::Screenshot::RunUI() { m_Picker->Activate(); while(m_Picker->IsRunning() && !(m_Picker->IsConfirmed())) { m_Picker->ProcessInput(); m_Picker->UpdateEvents(); } if(m_Picker->IsConfirmed()) { m_Picker->Shutdown(); this->GetData(); } } EzApp::Screenshot::~Screenshot() { if(m_Picker->IsRunning()) m_Picker->Shutdown(); delete m_Picker; } <commit_msg>Forgot to call Draw(), fixed<commit_after>#include "../screenshot.hpp" #define EzApp EasyGIF::App #define EzUI EasyGIF::UI EzApp::Screenshot::Screenshot() { // create a new RegionPicker but do not activate yet m_Picker = new EzUI::RegionPicker(false); } void EzApp::Screenshot::RunUI() { m_Picker->Activate(); while(m_Picker->IsRunning() && !(m_Picker->IsConfirmed())) { m_Picker->ProcessInput(); m_Picker->UpdateEvents(); m_Picker->Draw(); } if(m_Picker->IsConfirmed()) { m_Picker->Shutdown(); this->GetData(); } } EzApp::Screenshot::~Screenshot() { if(m_Picker->IsRunning()) m_Picker->Shutdown(); delete m_Picker; } <|endoftext|>
<commit_before>/********************************************************************* * * Copyright 2011 Intel Corporation * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *********************************************************************/ #include <iostream> #include "os_string.hpp" #include "cli_resources.hpp" #ifdef __GLIBC__ #include <dlfcn.h> static bool tryLib(const os::String &path, bool verbose) { void *handle = dlopen(path.str(), RTLD_LAZY); bool exists = (handle != NULL); if (verbose) { if (exists) { std::cerr << "info: found " << path.str() << "\n"; } else { std::cerr << "info: did not find " << dlerror() << "\n"; } } if (exists) dlclose(handle); return exists; } #endif static bool tryPath(const os::String &path, bool verbose) { bool exists = path.exists(); if (verbose) { std::cerr << "info: " << (exists ? "found" : "did not find") << " " << path.str() << "\n"; } return exists; } os::String findProgram(const char *programFilename, bool verbose) { os::String programPath; os::String processDir = os::getProcessName(); processDir.trimFilename(); programPath = processDir; programPath.join(programFilename); if (tryPath(programPath, verbose)) { return programPath; } #ifndef _WIN32 // Try absolute install directory programPath = APITRACE_PROGRAMS_INSTALL_DIR; programPath.join(programFilename); if (tryPath(programPath, verbose)) { return programPath; } #endif return ""; } os::String findWrapper(const char *wrapperFilename, bool verbose) { os::String wrapperPath; os::String processDir = os::getProcessName(); processDir.trimFilename(); // Try relative build directory // XXX: Just make build and install directory layout match wrapperPath = processDir; #if defined(CMAKE_INTDIR) // Go from `Debug\apitrace.exe` to `wrappers\Debug\foo.dll` on MSVC builds. wrapperPath.join(".."); wrapperPath.join("wrappers"); wrapperPath.join(CMAKE_INTDIR); #else wrapperPath.join("wrappers"); #endif wrapperPath.join(wrapperFilename); if (tryPath(wrapperPath, verbose)) { return wrapperPath; } #ifdef __GLIBC__ // We want to take advantage of $LIB dynamic string token expansion in // glibc dynamic linker to handle multilib layout for us wrapperPath = processDir; wrapperPath.join("../$LIB/apitrace/wrappers"); wrapperPath.join(wrapperFilename); if (tryLib(wrapperPath, verbose)) { return wrapperPath; } #endif // Try relative install directory wrapperPath = processDir; #if defined(_WIN32) wrapperPath.join("..\\lib\\wrappers"); #elif defined(__APPLE__) wrapperPath.join("../lib/wrappers"); #else wrapperPath.join("../lib/apitrace/wrappers"); #endif wrapperPath.join(wrapperFilename); if (tryPath(wrapperPath, verbose)) { return wrapperPath; } #ifndef _WIN32 // Try absolute install directory wrapperPath = APITRACE_WRAPPERS_INSTALL_DIR; wrapperPath.join(wrapperFilename); if (tryPath(wrapperPath, verbose)) { return wrapperPath; } #endif return ""; } os::String findScript(const char *scriptFilename, bool verbose) { os::String scriptPath; os::String processDir = os::getProcessName(); processDir.trimFilename(); // Try relative build directory // XXX: Just make build and install directory layout match #if defined(APITRACE_SOURCE_DIR) scriptPath = APITRACE_SOURCE_DIR; scriptPath.join("scripts"); scriptPath.join(scriptFilename); if (tryPath(scriptPath, verbose)) { return scriptPath; } #endif // Try relative install directory scriptPath = processDir; #if defined(_WIN32) scriptPath.join("..\\lib\\scripts"); #elif defined(__APPLE__) scriptPath.join("../lib/scripts"); #else scriptPath.join("../lib/apitrace/scripts"); #endif scriptPath.join(scriptFilename); if (tryPath(scriptPath, verbose)) { return scriptPath; } #ifndef _WIN32 // Try absolute install directory scriptPath = APITRACE_SCRIPTS_INSTALL_DIR; scriptPath.join(scriptFilename); if (tryPath(scriptPath, verbose)) { return scriptPath; } #endif std::cerr << "error: cannot find " << scriptFilename << " script\n"; exit(1); } <commit_msg>cli: Write full path of where the Python scripts are expected to be.<commit_after>/********************************************************************* * * Copyright 2011 Intel Corporation * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *********************************************************************/ #include <iostream> #include "os_string.hpp" #include "cli_resources.hpp" #ifdef __GLIBC__ #include <dlfcn.h> static bool tryLib(const os::String &path, bool verbose) { void *handle = dlopen(path.str(), RTLD_LAZY); bool exists = (handle != NULL); if (verbose) { if (exists) { std::cerr << "info: found " << path.str() << "\n"; } else { std::cerr << "info: did not find " << dlerror() << "\n"; } } if (exists) dlclose(handle); return exists; } #endif static bool tryPath(const os::String &path, bool verbose) { bool exists = path.exists(); if (verbose) { std::cerr << "info: " << (exists ? "found" : "did not find") << " " << path.str() << "\n"; } return exists; } os::String findProgram(const char *programFilename, bool verbose) { os::String programPath; os::String processDir = os::getProcessName(); processDir.trimFilename(); programPath = processDir; programPath.join(programFilename); if (tryPath(programPath, verbose)) { return programPath; } #ifndef _WIN32 // Try absolute install directory programPath = APITRACE_PROGRAMS_INSTALL_DIR; programPath.join(programFilename); if (tryPath(programPath, verbose)) { return programPath; } #endif return ""; } os::String findWrapper(const char *wrapperFilename, bool verbose) { os::String wrapperPath; os::String processDir = os::getProcessName(); processDir.trimFilename(); // Try relative build directory // XXX: Just make build and install directory layout match wrapperPath = processDir; #if defined(CMAKE_INTDIR) // Go from `Debug\apitrace.exe` to `wrappers\Debug\foo.dll` on MSVC builds. wrapperPath.join(".."); wrapperPath.join("wrappers"); wrapperPath.join(CMAKE_INTDIR); #else wrapperPath.join("wrappers"); #endif wrapperPath.join(wrapperFilename); if (tryPath(wrapperPath, verbose)) { return wrapperPath; } #ifdef __GLIBC__ // We want to take advantage of $LIB dynamic string token expansion in // glibc dynamic linker to handle multilib layout for us wrapperPath = processDir; wrapperPath.join("../$LIB/apitrace/wrappers"); wrapperPath.join(wrapperFilename); if (tryLib(wrapperPath, verbose)) { return wrapperPath; } #endif // Try relative install directory wrapperPath = processDir; #if defined(_WIN32) wrapperPath.join("..\\lib\\wrappers"); #elif defined(__APPLE__) wrapperPath.join("../lib/wrappers"); #else wrapperPath.join("../lib/apitrace/wrappers"); #endif wrapperPath.join(wrapperFilename); if (tryPath(wrapperPath, verbose)) { return wrapperPath; } #ifndef _WIN32 // Try absolute install directory wrapperPath = APITRACE_WRAPPERS_INSTALL_DIR; wrapperPath.join(wrapperFilename); if (tryPath(wrapperPath, verbose)) { return wrapperPath; } #endif return ""; } os::String findScript(const char *scriptFilename, bool verbose) { os::String scriptPath; os::String processDir = os::getProcessName(); processDir.trimFilename(); // Try relative build directory // XXX: Just make build and install directory layout match #if defined(APITRACE_SOURCE_DIR) scriptPath = APITRACE_SOURCE_DIR; scriptPath.join("scripts"); scriptPath.join(scriptFilename); if (tryPath(scriptPath, verbose)) { return scriptPath; } #endif // Try relative install directory scriptPath = processDir; #if defined(_WIN32) scriptPath.join("..\\lib\\scripts"); #elif defined(__APPLE__) scriptPath.join("../lib/scripts"); #else scriptPath.join("../lib/apitrace/scripts"); #endif scriptPath.join(scriptFilename); if (tryPath(scriptPath, verbose)) { return scriptPath; } #ifndef _WIN32 // Try absolute install directory scriptPath = APITRACE_SCRIPTS_INSTALL_DIR; scriptPath.join(scriptFilename); if (tryPath(scriptPath, verbose)) { return scriptPath; } std::cerr << "error: cannot find " << scriptPath << " script\n"; #else std::cerr << "error: cannot find " << scriptFilename << " script\n"; #endif exit(1); } <|endoftext|>
<commit_before>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <thread> //NOLINT #include "paddle/fluid/framework/channel.h" #include "paddle/fluid/operators/reader/reader_op_registry.h" namespace paddle { namespace operators { namespace reader { // 'Double buffer' means we shall maintain two batches of input data at the same // time. So the kCacheSize shoul be at least 2. static constexpr size_t kCacheSize = 2; // There will be two bacthes out of the channel during training: // 1. the one waiting to be sent to the channel // 2. the one just be received from the channel, which is also being used by // subsequent operators. // So the channel size should be kChacheSize - 2 static constexpr size_t kChannelSize = 0; // kCacheSize - 2 class DoubleBufferReader : public framework::DecoratedReader { public: struct Item { Item() : ctx_(nullptr) {} Item(Item&& b) { payloads_ = std::move(b.payloads_); ctx_ = std::move(b.ctx_); } Item& operator=(Item&& b) { payloads_ = std::move(b.payloads_); ctx_ = std::move(b.ctx_); return *this; } std::vector<framework::LoDTensor> payloads_; platform::DeviceContext* ctx_; }; explicit DoubleBufferReader( ReaderBase* reader, platform::Place target_place = platform::CPUPlace()) : DecoratedReader(reader), place_(target_place) { #ifdef PADDLE_WITH_CUDA for (size_t i = 0; i < kCacheSize; ++i) { if (platform::is_gpu_place(place_)) { ctxs_.emplace_back(new platform::CUDADeviceContext( boost::get<platform::CUDAPlace>(place_))); } } #endif StartPrefetcher(); } bool HasNext() const override; void ReadNext(std::vector<framework::LoDTensor>* out) override; void ReInit() override; ~DoubleBufferReader() { EndPrefetcher(); } private: void StartPrefetcher() { channel_ = framework::MakeChannel<Item>(kChannelSize); prefetcher_ = std::thread([this] { PrefetchThreadFunc(); }); } void EndPrefetcher() { channel_->Close(); if (prefetcher_.joinable()) { prefetcher_.join(); } delete channel_; channel_ = nullptr; } void PrefetchThreadFunc(); std::thread prefetcher_; framework::Channel<Item>* channel_; platform::Place place_; std::vector<std::unique_ptr<platform::DeviceContext>> ctxs_; }; class CreateDoubleBufferReaderOp : public framework::OperatorBase { public: using framework::OperatorBase::OperatorBase; private: void RunImpl(const framework::Scope& scope, const platform::Place& dev_place) const override { auto* out = scope.FindVar(Output("Out")) ->template GetMutable<framework::ReaderHolder>(); if (out->Get() != nullptr) { return; } const auto& underlying_reader = scope.FindVar(Input("UnderlyingReader")) ->Get<framework::ReaderHolder>(); auto place_str = Attr<std::string>("place"); platform::Place place; if (place_str == "CPU") { place = platform::CPUPlace(); } else { std::istringstream sin(place_str); sin.seekg(std::string("CUDA:").size(), std::ios::beg); size_t num; sin >> num; place = platform::CUDAPlace(static_cast<int>(num)); } out->Reset(new DoubleBufferReader(underlying_reader.Get(), place)); } }; class CreateDoubleBufferReaderOpMaker : public DecoratedReaderMakerBase { public: CreateDoubleBufferReaderOpMaker(OpProto* op_proto, OpAttrChecker* op_checker) : DecoratedReaderMakerBase(op_proto, op_checker) { AddComment(R"DOC( CreateDoubleBufferReader Operator A double buffer reader takes another reader as its 'underlying reader'. It launches another thread to execute the 'underlying reader' asynchronously, which prevents reading process from blocking subsequent training. )DOC"); std::unordered_set<std::string> enum_range; constexpr size_t kMaxCUDADevs = 128; for (size_t i = 0; i < kMaxCUDADevs; ++i) { enum_range.insert(string::Sprintf("CUDA:%d", i)); } enum_range.insert("CPU"); AddAttr<std::string>("place", "The double buffer place, default is CPU") .SetDefault("CPU") .InEnum({enum_range}); } }; bool DoubleBufferReader::HasNext() const { while (!channel_->IsClosed() && !channel_->CanReceive()) { } return channel_->CanReceive(); } void DoubleBufferReader::ReadNext(std::vector<framework::LoDTensor>* out) { if (!HasNext()) { PADDLE_THROW("There is no next data!"); } Item batch; channel_->Receive(&batch); *out = batch.payloads_; if (batch.ctx_) { batch.ctx_->Wait(); } } void DoubleBufferReader::ReInit() { reader_->ReInit(); EndPrefetcher(); StartPrefetcher(); } void DoubleBufferReader::PrefetchThreadFunc() { VLOG(5) << "A new prefetch thread starts."; std::vector<std::vector<framework::LoDTensor>> cpu_tensor_cache(kCacheSize); std::vector<std::vector<framework::LoDTensor>> gpu_tensor_cache(kCacheSize); size_t cached_tensor_id = 0; while (reader_->HasNext()) { Item batch; auto& cpu_batch = cpu_tensor_cache[cached_tensor_id]; reader_->ReadNext(&cpu_batch); if (platform::is_gpu_place(place_)) { auto& gpu_batch = gpu_tensor_cache[cached_tensor_id]; auto* gpu_ctx = ctxs_[cached_tensor_id].get(); gpu_batch.resize(cpu_batch.size()); for (size_t i = 0; i < cpu_batch.size(); ++i) { framework::TensorCopy(cpu_batch[i], place_, *gpu_ctx, &gpu_batch[i]); gpu_batch[i].set_lod(cpu_batch[i].lod()); } batch.payloads_ = gpu_batch; batch.ctx_ = gpu_ctx; } else { // CPUPlace batch.payloads_ = cpu_batch; } ++cached_tensor_id; cached_tensor_id %= kCacheSize; try { channel_->Send(&batch); } catch (paddle::platform::EnforceNotMet e) { VLOG(5) << "WARNING: The double buffer channel has been closed. The " "prefetch thread will terminate."; break; } } channel_->Close(); VLOG(5) << "Prefetch thread terminates."; } } // namespace reader } // namespace operators } // namespace paddle namespace ops = paddle::operators::reader; REGISTER_DECORATED_READER_OPERATOR(create_double_buffer_reader, ops::CreateDoubleBufferReaderOp, ops::CreateDoubleBufferReaderOpMaker); <commit_msg>fix lint<commit_after>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <thread> //NOLINT #include "paddle/fluid/framework/channel.h" #include "paddle/fluid/operators/reader/reader_op_registry.h" namespace paddle { namespace operators { namespace reader { // 'Double buffer' means we shall maintain two batches of input data at the same // time. So the kCacheSize shoul be at least 2. static constexpr size_t kCacheSize = 2; // There will be two bacthes out of the channel during training: // 1. the one waiting to be sent to the channel // 2. the one just be received from the channel, which is also being used by // subsequent operators. // So the channel size should be kChacheSize - 2 static constexpr size_t kChannelSize = 0; // kCacheSize - 2 class DoubleBufferReader : public framework::DecoratedReader { public: struct Item { Item() : ctx_(nullptr) {} Item(Item&& b) { payloads_ = std::move(b.payloads_); ctx_ = std::move(b.ctx_); } Item& operator=(Item&& b) { payloads_ = std::move(b.payloads_); ctx_ = std::move(b.ctx_); return *this; } std::vector<framework::LoDTensor> payloads_; platform::DeviceContext* ctx_; }; explicit DoubleBufferReader( ReaderBase* reader, platform::Place target_place = platform::CPUPlace()) : DecoratedReader(reader), place_(target_place) { #ifdef PADDLE_WITH_CUDA for (size_t i = 0; i < kCacheSize; ++i) { if (platform::is_gpu_place(place_)) { ctxs_.emplace_back(new platform::CUDADeviceContext( boost::get<platform::CUDAPlace>(place_))); } } #endif StartPrefetcher(); } bool HasNext() const override; void ReadNext(std::vector<framework::LoDTensor>* out) override; void ReInit() override; ~DoubleBufferReader() { EndPrefetcher(); } private: void StartPrefetcher() { channel_ = framework::MakeChannel<Item>(kChannelSize); prefetcher_ = std::thread([this] { PrefetchThreadFunc(); }); } void EndPrefetcher() { channel_->Close(); if (prefetcher_.joinable()) { prefetcher_.join(); } delete channel_; channel_ = nullptr; } void PrefetchThreadFunc(); std::thread prefetcher_; framework::Channel<Item>* channel_; platform::Place place_; std::vector<std::unique_ptr<platform::DeviceContext>> ctxs_; }; class CreateDoubleBufferReaderOp : public framework::OperatorBase { public: using framework::OperatorBase::OperatorBase; private: void RunImpl(const framework::Scope& scope, const platform::Place& dev_place) const override { auto* out = scope.FindVar(Output("Out")) ->template GetMutable<framework::ReaderHolder>(); if (out->Get() != nullptr) { return; } const auto& underlying_reader = scope.FindVar(Input("UnderlyingReader")) ->Get<framework::ReaderHolder>(); auto place_str = Attr<std::string>("place"); platform::Place place; if (place_str == "CPU") { place = platform::CPUPlace(); } else { std::istringstream sin(place_str); sin.seekg(std::string("CUDA:").size(), std::ios::beg); size_t num; sin >> num; place = platform::CUDAPlace(static_cast<int>(num)); } out->Reset(new DoubleBufferReader(underlying_reader.Get(), place)); } }; class CreateDoubleBufferReaderOpMaker : public DecoratedReaderMakerBase { public: CreateDoubleBufferReaderOpMaker(OpProto* op_proto, OpAttrChecker* op_checker) : DecoratedReaderMakerBase(op_proto, op_checker) { AddComment(R"DOC( CreateDoubleBufferReader Operator A double buffer reader takes another reader as its 'underlying reader'. It launches another thread to execute the 'underlying reader' asynchronously, which prevents reading process from blocking subsequent training. )DOC"); std::unordered_set<std::string> enum_range; constexpr size_t kMaxCUDADevs = 128; for (size_t i = 0; i < kMaxCUDADevs; ++i) { enum_range.insert(string::Sprintf("CUDA:%d", i)); } enum_range.insert("CPU"); AddAttr<std::string>("place", "The double buffer place, default is CPU") .SetDefault("CPU") .InEnum({enum_range}); } }; bool DoubleBufferReader::HasNext() const { while (!channel_->IsClosed() && !channel_->CanReceive()) { } return channel_->CanReceive(); } void DoubleBufferReader::ReadNext(std::vector<framework::LoDTensor>* out) { if (!HasNext()) { PADDLE_THROW("There is no next data!"); } Item batch; channel_->Receive(&batch); *out = batch.payloads_; if (batch.ctx_) { batch.ctx_->Wait(); } } void DoubleBufferReader::ReInit() { reader_->ReInit(); EndPrefetcher(); StartPrefetcher(); } void DoubleBufferReader::PrefetchThreadFunc() { VLOG(5) << "A new prefetch thread starts."; std::vector<std::vector<framework::LoDTensor>> cpu_tensor_cache(kCacheSize); std::vector<std::vector<framework::LoDTensor>> gpu_tensor_cache(kCacheSize); size_t cached_tensor_id = 0; while (reader_->HasNext()) { Item batch; auto& cpu_batch = cpu_tensor_cache[cached_tensor_id]; reader_->ReadNext(&cpu_batch); if (platform::is_gpu_place(place_)) { auto& gpu_batch = gpu_tensor_cache[cached_tensor_id]; auto* gpu_ctx = ctxs_[cached_tensor_id].get(); gpu_batch.resize(cpu_batch.size()); for (size_t i = 0; i < cpu_batch.size(); ++i) { framework::TensorCopy(cpu_batch[i], place_, *gpu_ctx, &gpu_batch[i]); gpu_batch[i].set_lod(cpu_batch[i].lod()); } batch.payloads_ = gpu_batch; batch.ctx_ = gpu_ctx; } else { // CPUPlace batch.payloads_ = cpu_batch; } ++cached_tensor_id; cached_tensor_id %= kCacheSize; try { channel_->Send(&batch); } catch (paddle::platform::EnforceNotMet e) { VLOG(5) << "WARNING: The double buffer channel has been closed. The " "prefetch thread will terminate."; break; } } channel_->Close(); VLOG(5) << "Prefetch thread terminates."; } } // namespace reader } // namespace operators } // namespace paddle namespace ops = paddle::operators::reader; REGISTER_DECORATED_READER_OPERATOR(create_double_buffer_reader, ops::CreateDoubleBufferReaderOp, ops::CreateDoubleBufferReaderOpMaker); <|endoftext|>
<commit_before>#include "boost/program_options.hpp" namespace po = boost::program_options; #include "opencv2/opencv.hpp" using namespace cv; #include "autocrop/autocrop.hpp" #include "saliency/saliency.hpp" #include "features/feature.hpp" #include "util/opencv.hpp" int main(int argc, char** argv) { /* * Argument parsing */ po::options_description desc("Available options"); desc.add_options() ("help", "Show this message") ("aspect-ratio,r", po::value<float>()->default_value(0.f), "Width-to-height ratio") ("input-file,i", po::value<std::string>(), "Input file path") ("output-file,o", po::value<std::string>(), "Output file path (default: output.png)") ("headless,hl", po::bool_switch()->default_value(false), "Run without graphical output") ; po::positional_options_description p; p.add("input-file", -1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.size() == 0 || vm.count("help") || !vm.count("input-file")) { std::cout << "Usage: " << argv[0] << " [options] input-file" << std::endl << desc; return 1; } if (vm["headless"].as<bool>()) GRAPHICAL = false; /* * Read image file */ std::string const f = vm["input-file"].as<std::string>(); Mat const in = imread(f, CV_LOAD_IMAGE_COLOR); if (!in.data) { throw std::runtime_error("Invalid input file: " + f); return -1; } /* * Call retargeting methods */ Rect crop = getBestCrop(in, vm["aspect-ratio"].as<float>()); Mat out = in.clone(); // Set crop border pixels to red Scalar red = Scalar(0, 0, 255); out(Rect(crop.x, crop.y, crop.width, 1)) = red; // Top out(Rect(crop.x+crop.width-1, crop.y, 1, crop.height)) = red; // Right out(Rect(crop.x, crop.y+crop.height-1, crop.width, 1)) = red; // Bottom out(Rect(crop.x, crop.y, 1, crop.height)) = red; // Left // Show output image showImageAndWait("Input - Cropped", out); /* * Save output if necessary */ if (vm.count("output-file")) { imwrite(vm["output-file"].as<std::string>(), out); } return 0; } <commit_msg>Show saliency map and only-crop in autocrop results<commit_after>#include "boost/program_options.hpp" namespace po = boost::program_options; #include "opencv2/opencv.hpp" using namespace cv; #include "autocrop/autocrop.hpp" #include "saliency/saliency.hpp" #include "features/feature.hpp" #include "util/opencv.hpp" int main(int argc, char** argv) { /* * Argument parsing */ po::options_description desc("Available options"); desc.add_options() ("help", "Show this message") ("aspect-ratio,r", po::value<float>()->default_value(0.f), "Width-to-height ratio") ("input-file,i", po::value<std::string>(), "Input file path") ("output-file,o", po::value<std::string>(), "Output file path (default: output.png)") ("headless,hl", po::bool_switch()->default_value(false), "Run without graphical output") ; po::positional_options_description p; p.add("input-file", -1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.size() == 0 || vm.count("help") || !vm.count("input-file")) { std::cout << "Usage: " << argv[0] << " [options] input-file" << std::endl << desc; return 1; } if (vm["headless"].as<bool>()) GRAPHICAL = false; /* * Read image file */ std::string const f = vm["input-file"].as<std::string>(); Mat const in = imread(f, CV_LOAD_IMAGE_COLOR); if (!in.data) { throw std::runtime_error("Invalid input file: " + f); return -1; } /* * Call retargeting methods */ Mat saliency = getSaliency(in); Mat gradient = getGradient(in); Rect crop = getBestCrop(saliency, gradient, vm["aspect-ratio"].as<float>()); // Set crop border pixels to red Mat in_crop = in.clone(); Scalar red = Scalar(0, 0, 255); in_crop(Rect(crop.x, crop.y, crop.width, 1)) = red; // Top in_crop(Rect(crop.x+crop.width-1, crop.y, 1, crop.height)) = red; // Right in_crop(Rect(crop.x, crop.y+crop.height-1, crop.width, 1)) = red; // Bottom in_crop(Rect(crop.x, crop.y, 1, crop.height)) = red; // Left // Set cropped out region black Mat out_crop = in.clone(); Scalar black = Scalar(0, 0, 0); out_crop(Rect(0, 0, in.cols, crop.y)) = black; // Top out_crop(Rect(crop.x+crop.width, 0, in.cols-crop.x-crop.width, in.rows)) = black; // Right out_crop(Rect(0, crop.y+crop.height, in.cols, in.rows-crop.y-crop.height)) = black; // Bottom out_crop(Rect(0, 0, crop.x, in.rows)) = black; // Left // Show saliency and crop side-by-side const Mat out = my_hconcat({saliency, in_crop, out_crop}); // Show output image showImageAndWait("Input - Cropped", out); /* * Save output if necessary */ if (vm.count("output-file")) { imwrite(vm["output-file"].as<std::string>(), out); } return 0; } <|endoftext|>
<commit_before>//put global includes in 'BasicIncludes' #include "BasicIncludes.h" #include "rand.h" #include "Camera.h" #include "Input.h" #include "Object.h" //Function List void Update(double); void Draw(); void CameraInput(); void MouseInput(); void InitializeWindow(); void Terminate(); void Run(); //Variables GLFWwindow* mainThread; glm::uvec2 SCREEN_SIZE; Camera camera = Camera(); glm::vec2 mouseChangeDegrees; double deltaTime; std::vector<Object*> objects; void Terminate() { glfwTerminate(); exit(0); } void InitializeWindow() { // if (!glfwInit()) { Terminate(); } //set screen size const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); SCREEN_SIZE = glm::uvec2(720,720); //basic aa done for us ;D glfwWindowHint(GLFW_SAMPLES, 16); glfwWindowHint(GLFW_VISIBLE, GL_TRUE); //can change the screen setting later //if (window == FULLSCREEN) { // glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // mainThread = glfwCreateWindow(SCREEN_SIZE.x, SCREEN_SIZE.y, "LifeSim", glfwGetPrimaryMonitor(), NULL); //} //else if (window == WINDOWED) { glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); mainThread = glfwCreateWindow(SCREEN_SIZE.x, SCREEN_SIZE.y, "LifeSim", NULL, NULL); //} //else if (BORDERLESS) { // glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); // glfwWindowHint(GLFW_RED_BITS, mode->redBits); // glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits); // glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits); // glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate); // mainThread = glfwCreateWindow(mode->width, mode->height, "LifeSim", glfwGetPrimaryMonitor(), NULL); //} if (!mainThread) { glfwTerminate(); throw std::runtime_error("GLFW window failed"); } glfwMakeContextCurrent(mainThread); // initialise GLEW if (glewInit() != GLEW_OK) { throw std::runtime_error("glewInit failed"); } glewExperimental = GL_TRUE; //stops glew crashing on OSX :-/ glfwSetInputMode(mainThread, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetCursorPos(mainThread, SCREEN_SIZE.x / 2.0, SCREEN_SIZE.y / 2.0); //Discard all the errors while (glGetError() != GL_NO_ERROR) {} glEnable(GL_DEPTH_TEST); // enable depth-testing glDepthMask(GL_TRUE); // turn on glDepthFunc(GL_LEQUAL); glDepthRange(0.0f, 1.0f); glEnable(GL_TEXTURE_2D); mouseChangeDegrees = glm::vec2(0); // setup camera camera.setViewportAspectRatio(SCREEN_SIZE.x / (float)SCREEN_SIZE.y); camera.setPosition(glm::vec3(0.0f, 0.0f, (METER))); camera.offsetOrientation(0.0f, -45); //unsigned concurentThreadsSupported = std::thread::hardware_concurrency(); //threads = new ThreadPool(concurentThreadsSupported); //for keyboard controls glfwSetKeyCallback(mainThread, InputKeyboardCallback); SetInputWindow(mainThread); } void Run() { deltaTime = 1.0 / 60; InitializeWindow(); Object testObj = Object(); objects.push_back(&testObj); //timer info for loop double t = 0.0f; double currentTime = glfwGetTime(); double accumulator = 0.0f; glfwPollEvents(); //stop loop when glfw exit is called glfwSetCursorPos(mainThread, SCREEN_SIZE.x / 2.0f, SCREEN_SIZE.y / 2.0f); while (!glfwWindowShouldClose(mainThread)) { double newTime = glfwGetTime(); double frameTime = newTime - currentTime; //std::cout << "FPS:: " <<1.0f / frameTime << std::endl; //setting up timers if (frameTime > 0.25) { frameTime = 0.25; } currentTime = newTime; accumulator += frameTime; //# of updates based on accumulated time while (accumulator >= deltaTime) { MouseInput();//update mouse change glfwPollEvents(); //executes all set input callbacks CameraInput(); //bypasses input system for direct camera manipulation Update(deltaTime); //updates all objects based on the constant deltaTime. t += deltaTime; accumulator -= deltaTime; } //draw glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); Draw(); glfwSwapBuffers(mainThread); } } void MouseInput() { double xPos; double yPos; glfwGetCursorPos(mainThread, &xPos, &yPos); xPos -= (SCREEN_SIZE.x / 2.0); yPos -= (SCREEN_SIZE.y / 2.0); mouseChangeDegrees.x = (float)(xPos / SCREEN_SIZE.x *camera.fieldOfView().x); mouseChangeDegrees.y = (float)(yPos / SCREEN_SIZE.y *camera.fieldOfView().y); /*std::cout << "Change in x (mouse): " << mouseChangeDegrees.x << std::endl; std::cout << "Change in y (mouse): " << mouseChangeDegrees.y << std::endl;*/ camera.offsetOrientation(mouseChangeDegrees.x, mouseChangeDegrees.y); glfwSetCursorPos(mainThread, SCREEN_SIZE.x / 2.0f, SCREEN_SIZE.y / 2.0f); } void CameraInput() { double moveSpeed; if (glfwGetKey(mainThread, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS) { moveSpeed = 9 * METER * deltaTime; } else if (glfwGetKey(mainThread, GLFW_KEY_LEFT_ALT) == GLFW_PRESS) { moveSpeed = 1 * METER * deltaTime; } else { moveSpeed = 4.5 * METER * deltaTime; } if (glfwGetKey(mainThread, GLFW_KEY_S) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * -camera.forward()); } else if (glfwGetKey(mainThread, GLFW_KEY_W) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * camera.forward()); } if (glfwGetKey(mainThread, GLFW_KEY_A) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * -camera.right()); } else if (glfwGetKey(mainThread, GLFW_KEY_D) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * camera.right()); } if (glfwGetKey(mainThread, GLFW_KEY_Z) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * -glm::vec3(0, 0, 1)); } else if (glfwGetKey(mainThread, GLFW_KEY_X) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * glm::vec3(0, 0, 1)); } } void Update(double dt) { } void Draw() { for (int i = 0; i < objects.size();i++){ objects[i]->Draw(camera); } } int main(){ Run(); Terminate(); return 0; } <commit_msg>Updating to 2013?<commit_after>//put global includes in 'BasicIncludes' // hi #include "BasicIncludes.h" #include "rand.h" #include "Camera.h" #include "Input.h" #include "Object.h" //Function List void Update(double); void Draw(); void CameraInput(); void MouseInput(); void InitializeWindow(); void Terminate(); void Run(); //Variables GLFWwindow* mainThread; glm::uvec2 SCREEN_SIZE; Camera camera = Camera(); glm::vec2 mouseChangeDegrees; double deltaTime; std::vector<Object*> objects; void Terminate() { glfwTerminate(); exit(0); } void InitializeWindow() { // if (!glfwInit()) { Terminate(); } //set screen size const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); SCREEN_SIZE = glm::uvec2(720,720); //basic aa done for us ;D glfwWindowHint(GLFW_SAMPLES, 16); glfwWindowHint(GLFW_VISIBLE, GL_TRUE); //can change the screen setting later //if (window == FULLSCREEN) { // glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // mainThread = glfwCreateWindow(SCREEN_SIZE.x, SCREEN_SIZE.y, "LifeSim", glfwGetPrimaryMonitor(), NULL); //} //else if (window == WINDOWED) { glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); mainThread = glfwCreateWindow(SCREEN_SIZE.x, SCREEN_SIZE.y, "LifeSim", NULL, NULL); //} //else if (BORDERLESS) { // glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); // glfwWindowHint(GLFW_RED_BITS, mode->redBits); // glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits); // glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits); // glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate); // mainThread = glfwCreateWindow(mode->width, mode->height, "LifeSim", glfwGetPrimaryMonitor(), NULL); //} if (!mainThread) { glfwTerminate(); throw std::runtime_error("GLFW window failed"); } glfwMakeContextCurrent(mainThread); // initialise GLEW if (glewInit() != GLEW_OK) { throw std::runtime_error("glewInit failed"); } glewExperimental = GL_TRUE; //stops glew crashing on OSX :-/ glfwSetInputMode(mainThread, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetCursorPos(mainThread, SCREEN_SIZE.x / 2.0, SCREEN_SIZE.y / 2.0); //Discard all the errors while (glGetError() != GL_NO_ERROR) {} glEnable(GL_DEPTH_TEST); // enable depth-testing glDepthMask(GL_TRUE); // turn on glDepthFunc(GL_LEQUAL); glDepthRange(0.0f, 1.0f); glEnable(GL_TEXTURE_2D); mouseChangeDegrees = glm::vec2(0); // setup camera camera.setViewportAspectRatio(SCREEN_SIZE.x / (float)SCREEN_SIZE.y); camera.setPosition(glm::vec3(0.0f, 0.0f, (METER))); camera.offsetOrientation(0.0f, -45); //unsigned concurentThreadsSupported = std::thread::hardware_concurrency(); //threads = new ThreadPool(concurentThreadsSupported); //for keyboard controls glfwSetKeyCallback(mainThread, InputKeyboardCallback); SetInputWindow(mainThread); } void Run() { deltaTime = 1.0 / 60; InitializeWindow(); Object testObj = Object(); objects.push_back(&testObj); //timer info for loop double t = 0.0f; double currentTime = glfwGetTime(); double accumulator = 0.0f; glfwPollEvents(); //stop loop when glfw exit is called glfwSetCursorPos(mainThread, SCREEN_SIZE.x / 2.0f, SCREEN_SIZE.y / 2.0f); while (!glfwWindowShouldClose(mainThread)) { double newTime = glfwGetTime(); double frameTime = newTime - currentTime; //std::cout << "FPS:: " <<1.0f / frameTime << std::endl; //setting up timers if (frameTime > 0.25) { frameTime = 0.25; } currentTime = newTime; accumulator += frameTime; //# of updates based on accumulated time while (accumulator >= deltaTime) { MouseInput();//update mouse change glfwPollEvents(); //executes all set input callbacks CameraInput(); //bypasses input system for direct camera manipulation Update(deltaTime); //updates all objects based on the constant deltaTime. t += deltaTime; accumulator -= deltaTime; } //draw glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); Draw(); glfwSwapBuffers(mainThread); } } void MouseInput() { double xPos; double yPos; glfwGetCursorPos(mainThread, &xPos, &yPos); xPos -= (SCREEN_SIZE.x / 2.0); yPos -= (SCREEN_SIZE.y / 2.0); mouseChangeDegrees.x = (float)(xPos / SCREEN_SIZE.x *camera.fieldOfView().x); mouseChangeDegrees.y = (float)(yPos / SCREEN_SIZE.y *camera.fieldOfView().y); /*std::cout << "Change in x (mouse): " << mouseChangeDegrees.x << std::endl; std::cout << "Change in y (mouse): " << mouseChangeDegrees.y << std::endl;*/ camera.offsetOrientation(mouseChangeDegrees.x, mouseChangeDegrees.y); glfwSetCursorPos(mainThread, SCREEN_SIZE.x / 2.0f, SCREEN_SIZE.y / 2.0f); } void CameraInput() { double moveSpeed; if (glfwGetKey(mainThread, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS) { moveSpeed = 9 * METER * deltaTime; } else if (glfwGetKey(mainThread, GLFW_KEY_LEFT_ALT) == GLFW_PRESS) { moveSpeed = 1 * METER * deltaTime; } else { moveSpeed = 4.5 * METER * deltaTime; } if (glfwGetKey(mainThread, GLFW_KEY_S) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * -camera.forward()); } else if (glfwGetKey(mainThread, GLFW_KEY_W) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * camera.forward()); } if (glfwGetKey(mainThread, GLFW_KEY_A) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * -camera.right()); } else if (glfwGetKey(mainThread, GLFW_KEY_D) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * camera.right()); } if (glfwGetKey(mainThread, GLFW_KEY_Z) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * -glm::vec3(0, 0, 1)); } else if (glfwGetKey(mainThread, GLFW_KEY_X) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * glm::vec3(0, 0, 1)); } } void Update(double dt) { } void Draw() { for (int i = 0; i < objects.size();i++){ objects[i]->Draw(camera); } } int main(){ Run(); Terminate(); return 0; } <|endoftext|>
<commit_before>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0 #include "clientapi.hh" #include "internal.hh" #include "../configure.h" // RAPICORN_GETTEXT_DOMAIN #include <stdlib.h> #define SDEBUG(...) RAPICORN_KEY_DEBUG ("StartUp", __VA_ARGS__) namespace Rapicorn { static struct __StaticCTorTest { int v; __StaticCTorTest() : v (0x120caca0) { v += 0x300000; } } __staticctortest; struct AppData { ApplicationH app; Aida::BaseConnectionP connection; }; static DurableInstance<AppData> static_appdata; // use DurableInstance to ensure app stays around for static dtors /** Initialize Rapicorn and the main Application object. * * This funciton initializes the Rapicorn toolkit and starts an asynchronously * running UI thread. The UI thread creates the main Application object, * manages all UI related components and processes UI events. * . * The arguments passed in @a argcp and @a argv are parsed and any Rapicorn * specific arguments are stripped. Note that Rapicorn requires the exact argv0 * as provided by main(). If @a argv[0] as passed into this function is empty or * otherwise altered, the correct value needs to be supplied previously by a * call to program_argv0_init(). * If 'testing=1' is passed in @a args, these command line arguments are supported: * - @c --test-verbose - Execute test cases with verbose message generation. * - @c --test-slow - Execute only test cases excercising slow code paths or loops. * . * The initialization arguments currenlty supported for @a args are as follows: * - @c autonomous - Avoid loading external rc-files or other configurations that could affect test runs. * - @c cpu-affinity - The CPU# to bind the Rapicorn UI thread to. * - @c testing - Enable testing framework, used by init_core_test(), see also #$RAPICORN_TEST. * - @c test-verbose - acts like --test-verbose. * - @c test-slow - acts like --test-slow. * . * Additionally, the @c $RAPICORN environment variable affects toolkit behaviour. It supports * multiple colon (':') separated options (options can be prfixed with 'no-' to disable): * - @c debug - Enables verbose debugging output (default=off). * - @c fatal-syslog - Fatal program conditions that lead to aborting are recorded via syslog (default=on). * - @c syslog - Critical and warning conditions are recorded via syslog (default=off). * - @c fatal-warnings - Critical and warning conditions are treated as fatal conditions (default=off). * - @c logfile=FILENAME - Record all messages and conditions into FILENAME. * . * @param application_name Possibly localized string useful to display the application name in user interfaces. * @param argcp Location of the 'argc' argument to main() * @param argv Location of the 'argv' arguments to main() * @param args Rapicorn initialization arguments. */ ApplicationH init_app (const String &application_name, int *argcp, char **argv, const StringVector &args) { return_unless (static_appdata->app == NULL, static_appdata->app); // assert global_ctors work if (__staticctortest.v != 0x123caca0) fatal ("%s: link error: C++ constructors have not been executed", __func__); // full locale initialization is needed by X11, etc if (!setlocale (LC_ALL,"")) { auto sgetenv = [] (const char *var) { const char *str = getenv (var); return str ? str : ""; }; String lv = string_format ("LANGUAGE=%s;LC_ALL=%s;LC_MONETARY=%s;LC_MESSAGES=%s;LC_COLLATE=%s;LC_CTYPE=%s;LC_TIME=%s;LANG=%s", sgetenv ("LANGUAGE"), sgetenv ("LC_ALL"), sgetenv ("LC_MONETARY"), sgetenv ("LC_MESSAGES"), sgetenv ("LC_COLLATE"), sgetenv ("LC_CTYPE"), sgetenv ("LC_TIME"), sgetenv ("LANG")); SDEBUG ("environment: %s", lv.c_str()); setlocale (LC_ALL, "C"); SDEBUG ("failed to initialize locale, falling back to \"C\""); } // initialize i18n functions RapicornInternal::init_rapicorn_gettext (RAPICORN_GETTEXT_DOMAIN); // miscellaneous sub systems { const String ci = cpu_info(); // initialize cpu info (void) ci; } // initialize core parse_init_args (argcp, argv, args); // boot up UI thread const bool boot_ok = RapicornInternal::uithread_bootup (argcp, argv, args); if (!boot_ok) fatal ("%s: failed to start Rapicorn UI thread: %s", __func__, strerror (errno)); // connect to remote UIThread and fetch main handle static_appdata->connection = Aida::ClientConnection::connect ("inproc://Rapicorn-" RAPICORN_VERSION); if (!static_appdata->connection) fatal ("%s: failed to connect to Rapicorn UI thread: %s", __func__, strerror (errno)); static_appdata->app = static_appdata->connection->remote_origin<ApplicationHandle>(); if (!static_appdata->app) fatal ("%s: failed to retrieve Rapicorn::Application object: %s", __func__, strerror (errno)); if (!application_name.empty()) static_appdata->app.setup (application_name, ""); return static_appdata->app; } ApplicationH ApplicationH::the () { return static_appdata->app; } class AppSource; typedef std::shared_ptr<AppSource> AppSourceP; class AppSource : public EventSource { Rapicorn::Aida::BaseConnection &connection_; PollFD pfd_; bool last_seen_primary, need_check_primary; void check_primaries() { // seen_primary is merely a hint, need to check local and remote states if (ApplicationH::the().finishable() && // remote main_loop()->finishable() && loop_) // local main_loop()->quit(); } AppSource (Rapicorn::Aida::BaseConnection &connection) : connection_ (connection), last_seen_primary (false), need_check_primary (false) { pfd_.fd = connection_.notify_fd(); pfd_.events = PollFD::IN; pfd_.revents = 0; add_poll (&pfd_); primary (false); ApplicationH::the().sig_missing_primary() += [this]() { queue_check_primaries(); }; } virtual bool prepare (const LoopState &state, int64 *timeout_usecs_p) { return need_check_primary || connection_.pending(); } virtual bool check (const LoopState &state) { if (UNLIKELY (last_seen_primary && !state.seen_primary && !need_check_primary)) need_check_primary = true; last_seen_primary = state.seen_primary; return need_check_primary || connection_.pending(); } virtual bool dispatch (const LoopState &state) { connection_.dispatch(); if (need_check_primary) { need_check_primary = false; queue_check_primaries(); } return true; } friend class FriendAllocator<AppSource>; public: static AppSourceP create (Rapicorn::Aida::BaseConnection &connection) { return FriendAllocator<AppSource>::make_shared (connection); } void queue_check_primaries() { if (loop_) loop_->exec_idle (Aida::slot (*this, &AppSource::check_primaries)); } }; } // Rapicorn // compile client-side API #include "clientapi.cc" #include <rcore/testutils.hh> namespace Rapicorn { MainLoopP ApplicationH::main_loop() { ApplicationH the_app = the(); assert_return (the_app != NULL, NULL); static MainLoopP app_loop = NULL; do_once { app_loop = MainLoop::create(); AppSourceP source = AppSource::create (*the_app.__aida_connection__()); app_loop->add (source); source->queue_check_primaries(); } return app_loop; } /** * Initialize Rapicorn like init_app(), and boots up the test suite framework. * Normally, Test::run() should be called next to execute all unit tests. */ ApplicationH init_test_app (const String &application_name, int *argcp, char **argv, const StringVector &args) { RapicornInternal::inject_init_args (":autonomous:testing:fatal-warnings:"); ApplicationH app = init_app (application_name, argcp, argv, args); return app; } /** * Cause the application's main loop to quit, and run() to return @a quit_code. */ void ApplicationH::quit (int quit_code) { main_loop()->quit (quit_code); } /** * Run the main event loop until all primary sources ceased to exist * (see MainLoop::finishable()) or until the loop is quit. * @returns the @a quit_code passed in to loop_quit() or 0. */ int ApplicationH::run () { return main_loop()->run(); } /** * This function runs the Application main loop via loop_run(), and exits * the running process once the loop has quit. The loop_quit() status is * passed on to exit() and thus to the parent process. */ int ApplicationH::run_and_exit () { int status = run(); shutdown(); ::exit (status); } /// Perform one loop iteration and return whether more iterations are needed. bool ApplicationH::iterate (bool block) { return main_loop()->iterate (block); } /** * This function causes proper termination of Rapicorn's concurrently running * ui-thread and needs to be called before exit(3posix), to avoid parallel * execution of the ui-thread while atexit(3posix) handlers or while global * destructors are releasing process resources. */ void ApplicationH::shutdown() { RapicornInternal::uithread_shutdown(); } } // Rapicorn namespace RapicornInternal { // internal function for tests int64 client_app_test_hook () { return ApplicationH::the().test_hook(); } } // RapicornInternal <commit_msg>UI: fix main_loop NULL check<commit_after>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0 #include "clientapi.hh" #include "internal.hh" #include "../configure.h" // RAPICORN_GETTEXT_DOMAIN #include <stdlib.h> #define SDEBUG(...) RAPICORN_KEY_DEBUG ("StartUp", __VA_ARGS__) namespace Rapicorn { static struct __StaticCTorTest { int v; __StaticCTorTest() : v (0x120caca0) { v += 0x300000; } } __staticctortest; struct AppData { ApplicationH app; Aida::BaseConnectionP connection; }; static DurableInstance<AppData> static_appdata; // use DurableInstance to ensure app stays around for static dtors /** Initialize Rapicorn and the main Application object. * * This funciton initializes the Rapicorn toolkit and starts an asynchronously * running UI thread. The UI thread creates the main Application object, * manages all UI related components and processes UI events. * . * The arguments passed in @a argcp and @a argv are parsed and any Rapicorn * specific arguments are stripped. Note that Rapicorn requires the exact argv0 * as provided by main(). If @a argv[0] as passed into this function is empty or * otherwise altered, the correct value needs to be supplied previously by a * call to program_argv0_init(). * If 'testing=1' is passed in @a args, these command line arguments are supported: * - @c --test-verbose - Execute test cases with verbose message generation. * - @c --test-slow - Execute only test cases excercising slow code paths or loops. * . * The initialization arguments currenlty supported for @a args are as follows: * - @c autonomous - Avoid loading external rc-files or other configurations that could affect test runs. * - @c cpu-affinity - The CPU# to bind the Rapicorn UI thread to. * - @c testing - Enable testing framework, used by init_core_test(), see also #$RAPICORN_TEST. * - @c test-verbose - acts like --test-verbose. * - @c test-slow - acts like --test-slow. * . * Additionally, the @c $RAPICORN environment variable affects toolkit behaviour. It supports * multiple colon (':') separated options (options can be prfixed with 'no-' to disable): * - @c debug - Enables verbose debugging output (default=off). * - @c fatal-syslog - Fatal program conditions that lead to aborting are recorded via syslog (default=on). * - @c syslog - Critical and warning conditions are recorded via syslog (default=off). * - @c fatal-warnings - Critical and warning conditions are treated as fatal conditions (default=off). * - @c logfile=FILENAME - Record all messages and conditions into FILENAME. * . * @param application_name Possibly localized string useful to display the application name in user interfaces. * @param argcp Location of the 'argc' argument to main() * @param argv Location of the 'argv' arguments to main() * @param args Rapicorn initialization arguments. */ ApplicationH init_app (const String &application_name, int *argcp, char **argv, const StringVector &args) { return_unless (static_appdata->app == NULL, static_appdata->app); // assert global_ctors work if (__staticctortest.v != 0x123caca0) fatal ("%s: link error: C++ constructors have not been executed", __func__); // full locale initialization is needed by X11, etc if (!setlocale (LC_ALL,"")) { auto sgetenv = [] (const char *var) { const char *str = getenv (var); return str ? str : ""; }; String lv = string_format ("LANGUAGE=%s;LC_ALL=%s;LC_MONETARY=%s;LC_MESSAGES=%s;LC_COLLATE=%s;LC_CTYPE=%s;LC_TIME=%s;LANG=%s", sgetenv ("LANGUAGE"), sgetenv ("LC_ALL"), sgetenv ("LC_MONETARY"), sgetenv ("LC_MESSAGES"), sgetenv ("LC_COLLATE"), sgetenv ("LC_CTYPE"), sgetenv ("LC_TIME"), sgetenv ("LANG")); SDEBUG ("environment: %s", lv.c_str()); setlocale (LC_ALL, "C"); SDEBUG ("failed to initialize locale, falling back to \"C\""); } // initialize i18n functions RapicornInternal::init_rapicorn_gettext (RAPICORN_GETTEXT_DOMAIN); // miscellaneous sub systems { const String ci = cpu_info(); // initialize cpu info (void) ci; } // initialize core parse_init_args (argcp, argv, args); // boot up UI thread const bool boot_ok = RapicornInternal::uithread_bootup (argcp, argv, args); if (!boot_ok) fatal ("%s: failed to start Rapicorn UI thread: %s", __func__, strerror (errno)); // connect to remote UIThread and fetch main handle static_appdata->connection = Aida::ClientConnection::connect ("inproc://Rapicorn-" RAPICORN_VERSION); if (!static_appdata->connection) fatal ("%s: failed to connect to Rapicorn UI thread: %s", __func__, strerror (errno)); static_appdata->app = static_appdata->connection->remote_origin<ApplicationHandle>(); if (!static_appdata->app) fatal ("%s: failed to retrieve Rapicorn::Application object: %s", __func__, strerror (errno)); if (!application_name.empty()) static_appdata->app.setup (application_name, ""); return static_appdata->app; } ApplicationH ApplicationH::the () { return static_appdata->app; } class AppSource; typedef std::shared_ptr<AppSource> AppSourceP; class AppSource : public EventSource { Rapicorn::Aida::BaseConnection &connection_; PollFD pfd_; bool last_seen_primary, need_check_primary; void check_primaries() { // seen_primary is merely a hint, need to check local and remote states if (main_loop() && main_loop()->finishable() && // local ApplicationH::the().finishable() && // remote main_loop()->finishable()) // still finishable after remote call main_loop()->quit(); } AppSource (Rapicorn::Aida::BaseConnection &connection) : connection_ (connection), last_seen_primary (false), need_check_primary (false) { pfd_.fd = connection_.notify_fd(); pfd_.events = PollFD::IN; pfd_.revents = 0; add_poll (&pfd_); primary (false); ApplicationH::the().sig_missing_primary() += [this]() { queue_check_primaries(); }; } virtual bool prepare (const LoopState &state, int64 *timeout_usecs_p) { return need_check_primary || connection_.pending(); } virtual bool check (const LoopState &state) { if (UNLIKELY (last_seen_primary && !state.seen_primary && !need_check_primary)) need_check_primary = true; last_seen_primary = state.seen_primary; return need_check_primary || connection_.pending(); } virtual bool dispatch (const LoopState &state) { connection_.dispatch(); if (need_check_primary) { need_check_primary = false; queue_check_primaries(); } return true; } friend class FriendAllocator<AppSource>; public: static AppSourceP create (Rapicorn::Aida::BaseConnection &connection) { return FriendAllocator<AppSource>::make_shared (connection); } void queue_check_primaries() { if (loop_) loop_->exec_idle (Aida::slot (*this, &AppSource::check_primaries)); } }; } // Rapicorn // compile client-side API #include "clientapi.cc" #include <rcore/testutils.hh> namespace Rapicorn { MainLoopP ApplicationH::main_loop() { ApplicationH the_app = the(); assert_return (the_app != NULL, NULL); static MainLoopP app_loop = NULL; do_once { app_loop = MainLoop::create(); AppSourceP source = AppSource::create (*the_app.__aida_connection__()); app_loop->add (source); source->queue_check_primaries(); } return app_loop; } /** * Initialize Rapicorn like init_app(), and boots up the test suite framework. * Normally, Test::run() should be called next to execute all unit tests. */ ApplicationH init_test_app (const String &application_name, int *argcp, char **argv, const StringVector &args) { RapicornInternal::inject_init_args (":autonomous:testing:fatal-warnings:"); ApplicationH app = init_app (application_name, argcp, argv, args); return app; } /** * Cause the application's main loop to quit, and run() to return @a quit_code. */ void ApplicationH::quit (int quit_code) { main_loop()->quit (quit_code); } /** * Run the main event loop until all primary sources ceased to exist * (see MainLoop::finishable()) or until the loop is quit. * @returns the @a quit_code passed in to loop_quit() or 0. */ int ApplicationH::run () { return main_loop()->run(); } /** * This function runs the Application main loop via loop_run(), and exits * the running process once the loop has quit. The loop_quit() status is * passed on to exit() and thus to the parent process. */ int ApplicationH::run_and_exit () { int status = run(); shutdown(); ::exit (status); } /// Perform one loop iteration and return whether more iterations are needed. bool ApplicationH::iterate (bool block) { return main_loop()->iterate (block); } /** * This function causes proper termination of Rapicorn's concurrently running * ui-thread and needs to be called before exit(3posix), to avoid parallel * execution of the ui-thread while atexit(3posix) handlers or while global * destructors are releasing process resources. */ void ApplicationH::shutdown() { RapicornInternal::uithread_shutdown(); } } // Rapicorn namespace RapicornInternal { // internal function for tests int64 client_app_test_hook () { return ApplicationH::the().test_hook(); } } // RapicornInternal <|endoftext|>
<commit_before># include "conf.hpp" # include "error.hpp" # include "broker-util.hpp" # include <cstdlib> using std::getenv; const char* unix_family = "UNIX"; const char* inet_family = "INET"; const char* mesg_relay_addr_env_var = "CHATTP_MESG_RELAY_ADDR"; const char* mesg_relay_family_env_var = "CHATTP_MESG_RELAY_FAMILY"; const char* mesg_relay_port_env_var = "CHATTP_MESG_RELAY_PORT"; const char* persistence_addr_env_var = "CHATTP_PERSISTENCE_LAYER_ADDR"; const char* persistence_family_env_var= "CHATTP_PERSISTENCE_LAYER_FAMILY"; const char* persistence_port_env_var = "CHATTP_PERSISTENCE_LAYER_PORT"; const unsigned int max_message_size = 8192; /** * @brief Fetch configuration from environment. * * This class configures the message broker from environment variables. * */ BrokerSettings::BrokerSettings(void) { // Message relay configuration if ( getenv(mesg_relay_addr_env_var) ) message_relay_info.address = getenv(mesg_relay_addr_env_var); else throw BrokerError(ErrorType::configurationError,string("There is no ") + mesg_relay_addr_env_var + " environment variable"); if ( getenv(mesg_relay_family_env_var) ) { string conn_type(getenv(mesg_relay_family_env_var)); if (conn_type == unix_family) message_relay_info.type = connectionType::UNIX; else if (conn_type == inet_family) { message_relay_info.type = connectionType::INET; if ( getenv(mesg_relay_port_env_var) ) message_relay_info.port = getenv(mesg_relay_port_env_var); else throw BrokerError(ErrorType::configurationError,string("The ") + mesg_relay_port_env_var + " environment variable could not be found."); } else throw BrokerError(ErrorType::configurationError,string("There's something wrong with the ") + mesg_relay_family_env_var + " environment variable"); } else throw BrokerError(ErrorType::configurationError,string("There is no ") + mesg_relay_family_env_var + " environment variable"); // Persistence layer (data source) configuration if ( getenv(persistence_addr_env_var) ) persistence_layer_info.address = getenv(persistence_addr_env_var); else throw BrokerError(ErrorType::configurationError,string("There is no ") + persistence_addr_env_var + " environment variable"); if ( getenv(persistence_family_env_var) ) { string conn_type(getenv(persistence_family_env_var)); if ( conn_type == inet_family ) { persistence_layer_info.type = connectionType::INET; if ( getenv(persistence_port_env_var) ) persistence_layer_info.port = getenv(persistence_port_env_var); else throw BrokerError(ErrorType::configurationError,string("There is no ") + persistence_port_env_var + " environment variable."); } else if ( conn_type == unix_family ) persistence_layer_info.type = connectionType::UNIX; else throw BrokerError(ErrorType::configurationError,string("There's something wrong with the ") + persistence_family_env_var + " environment variable"); } else throw BrokerError(ErrorType::configurationError,string("There is no ") + persistence_family_env_var + " environment variable"); } connectionInformation BrokerSettings::getMessageRelayAddress(void) { return message_relay_info; } connectionInformation BrokerSettings::getPersistenceLayerAddress(void) { return persistence_layer_info; } <commit_msg>anon namespace for configuration variables.<commit_after># include "conf.hpp" # include "error.hpp" # include "broker-util.hpp" # include <cstdlib> using std::getenv; namespace { const char* unix_family = "UNIX"; const char* inet_family = "INET"; const char* mesg_relay_addr_env_var = "CHATTP_MESG_RELAY_ADDR"; const char* mesg_relay_family_env_var = "CHATTP_MESG_RELAY_FAMILY"; const char* mesg_relay_port_env_var = "CHATTP_MESG_RELAY_PORT"; const char* persistence_addr_env_var = "CHATTP_PERSISTENCE_LAYER_ADDR"; const char* persistence_family_env_var= "CHATTP_PERSISTENCE_LAYER_FAMILY"; const char* persistence_port_env_var = "CHATTP_PERSISTENCE_LAYER_PORT"; } const unsigned int max_message_size = 8192; /** * @brief Fetch configuration from environment. * * This class configures the message broker from environment variables. * */ BrokerSettings::BrokerSettings(void) { // Message relay configuration if ( getenv(mesg_relay_addr_env_var) ) message_relay_info.address = getenv(mesg_relay_addr_env_var); else throw BrokerError(ErrorType::configurationError,string("There is no ") + mesg_relay_addr_env_var + " environment variable"); if ( getenv(mesg_relay_family_env_var) ) { string conn_type(getenv(mesg_relay_family_env_var)); if (conn_type == unix_family) message_relay_info.type = connectionType::UNIX; else if (conn_type == inet_family) { message_relay_info.type = connectionType::INET; if ( getenv(mesg_relay_port_env_var) ) message_relay_info.port = getenv(mesg_relay_port_env_var); else throw BrokerError(ErrorType::configurationError,string("The ") + mesg_relay_port_env_var + " environment variable could not be found."); } else throw BrokerError(ErrorType::configurationError,string("There's something wrong with the ") + mesg_relay_family_env_var + " environment variable"); } else throw BrokerError(ErrorType::configurationError,string("There is no ") + mesg_relay_family_env_var + " environment variable"); // Persistence layer (data source) configuration if ( getenv(persistence_addr_env_var) ) persistence_layer_info.address = getenv(persistence_addr_env_var); else throw BrokerError(ErrorType::configurationError,string("There is no ") + persistence_addr_env_var + " environment variable"); if ( getenv(persistence_family_env_var) ) { string conn_type(getenv(persistence_family_env_var)); if ( conn_type == inet_family ) { persistence_layer_info.type = connectionType::INET; if ( getenv(persistence_port_env_var) ) persistence_layer_info.port = getenv(persistence_port_env_var); else throw BrokerError(ErrorType::configurationError,string("There is no ") + persistence_port_env_var + " environment variable."); } else if ( conn_type == unix_family ) persistence_layer_info.type = connectionType::UNIX; else throw BrokerError(ErrorType::configurationError,string("There's something wrong with the ") + persistence_family_env_var + " environment variable"); } else throw BrokerError(ErrorType::configurationError,string("There is no ") + persistence_family_env_var + " environment variable"); } connectionInformation BrokerSettings::getMessageRelayAddress(void) { return message_relay_info; } connectionInformation BrokerSettings::getPersistenceLayerAddress(void) { return persistence_layer_info; } <|endoftext|>
<commit_before>#include "util/file_piece.hh" #include "util/file.hh" #include "util/usage.hh" #include <stdio.h> #include <fstream> #include <iostream> #include <ctime> //for timing. #include <chrono> #include "helpers/hash.hh" #include "helpers/line_splitter.hh" #include "helpers/probing_hash_utils.hh" #include "helpers/vocabid.hh" //Appends to the vector used for outputting. int vector_append(line_text *input, std::vector<char> *outputvec, bool new_entry); std::vector<char>::iterator vector_append(line_text* input, std::vector<char>* outputvec, std::vector<char>::iterator it, bool new_entry){ //Append everything to one string std::string temp = ""; int vec_size = 0; int new_string_size = 0; if (new_entry){ //If we have a new entry, add an empty line. temp += '\n'; } temp += input->target_phrase.as_string() + "\t" + input->prob.as_string() + "\t" + input->word_all1.as_string() + "\t" + input->word_all2.as_string() + "\n"; //Put into vector outputvec->insert(it, temp.begin(), temp.end()); //Return new iterator updated iterator return it+temp.length(); } int main(int argc, char* argv[]){ //Time everything std::clock_t c_start = std::clock(); auto t_start = std::chrono::high_resolution_clock::now(); if (argc != 6) { // Tell the user how to run the program std::cerr << "Provided " << argc << " arguments, needed 4." << std::endl; std::cerr << "Usage: " << argv[0] << " path_to_phrasetable number_of_uniq_lines output_bin_file output_hash_table output_vocab_id" << std::endl; return 1; } //Read the file util::FilePiece filein(argv[1]); int tablesize = atoi(argv[2]); //Init the table size_t size = Table::Size(tablesize, 1.2); char * mem = new char[size]; memset(mem, 0, size); Table table(mem, size); //Vocab id std::map<uint64_t, std::string> vocabids; //Output binary std::ofstream os (argv[3], std::ios::binary); //Vector with 10000 elements, after the 9000nd we swap to disk, we have 10000 for buffer std::vector<char> ram_container; ram_container.reserve(10000); std::vector<char>::iterator it = ram_container.begin(); unsigned int dist_from_start = 0; uint64_t extra_counter = 0; //After we reset the counter, we still want to keep track of the correct offset, so //we should keep an extra counter for that reason. line_text prev_line; //Check if the source phrase of the previous line is the same int longestchars = 0; //Keep track of what is the maximum number of characters we need to read when quering //Read everything and processs while(true){ //Calculate offset dist_from_start = distance(ram_container.begin(),it); try { //Process line read line_text line; line = splitLine(filein.ReadLine()); if (line.source_phrase != prev_line.source_phrase){ //Add to vocabid add_to_map(&vocabids, line.source_phrase); add_to_map(&vocabids, line.target_phrase); //Create an entry only for different source phrases. //Create an entry to keep track of the offset Entry pesho; pesho.value = dist_from_start + extra_counter; pesho.key = getHash(line.source_phrase); //Put into table table.Insert(pesho); prev_line = line; it = vector_append(&line, &ram_container, it, true); //Put into the array and update iterator to the new end position } else{ add_to_map(&vocabids, line.target_phrase); it = vector_append(&line, &ram_container, it, false); //Put into the array and update iterator to the new end position } //Write to disk if over 10000 if (dist_from_start > 9000) { //write to memory os.write(&ram_container[0], dist_from_start); //Clear the vector: ram_container.clear(); ram_container.reserve(10000); extra_counter += dist_from_start; it = ram_container.begin(); //Reset iterator } } catch (util::EndOfFileException e){ std::cout << "End of file" << std::endl; os.write(&ram_container[0], dist_from_start); break; } } serialize_table(mem, size, argv[4]); //clean up os.close(); ram_container.clear(); delete[] mem; //Serialize vocabids serialize_map(&vocabids, argv[5]); vocabids.clear(); //End timing std::clock_t c_end = std::clock(); auto t_end = std::chrono::high_resolution_clock::now(); //Print timing results std::cout << "CPU time used: "<< 1000.0 * (c_end-c_start) / CLOCKS_PER_SEC<< " ms\n"; std::cout << "Real time passed: "<< std::chrono::duration_cast<std::chrono::milliseconds>(t_end - t_start).count()<< " ms\n"; util::PrintUsage(std::cout); return 1; } bool test_tokenization(){ StringPiece line1 = StringPiece("! ! ! ! ||| ! ! ! ! ||| 0.0804289 0.141656 0.0804289 0.443409 2.718 ||| 0-0 1-1 2-2 3-3 ||| 1 1 1"); StringPiece line2 = StringPiece("! ! ! ) , has ||| ! ! ! ) - , a ||| 0.0804289 0.0257627 0.0804289 0.00146736 2.718 ||| 0-0 1-1 2-2 3-3 4-4 4-5 5-6 ||| 1 1 1"); StringPiece line3 = StringPiece("! ! ! ) , ||| ! ! ! ) - , ||| 0.0804289 0.075225 0.0804289 0.00310345 2.718 ||| 0-0 1-1 2-2 3-3 4-4 4-5 ||| 1 1 1"); StringPiece line4 = StringPiece("! ! ! ) ||| ! ! ! ) . ||| 0.0804289 0.177547 0.0268096 0.000872597 2.718 ||| 0-0 1-1 2-2 3-3 ||| 1 3 1"); line_text output1 = splitLine(line1); line_text output2 = splitLine(line2); line_text output3 = splitLine(line3); line_text output4 = splitLine(line4); bool test1 = output1.prob == StringPiece("0.0804289 0.141656 0.0804289 0.443409 2.718"); bool test2 = output2.word_all1 == StringPiece("0-0 1-1 2-2 3-3 4-4 4-5 5-6"); bool test3 = output2.target_phrase == StringPiece("! ! ! ) - , a"); bool test4 = output3.source_phrase == StringPiece("! ! ! ) ,"); bool test5 = output4.word_all2 == StringPiece("1 3 1"); //std::cout << test1 << " " << test2 << " " << test3 << " " << test4 << std::endl; if (test1 && test2 && test3 && test4 && test5){ return true; }else{ return false; } } bool test_vectorinsert() { StringPiece line1 = StringPiece("! ! ! ! ||| ! ! ! ! ||| 0.0804289 0.141656 0.0804289 0.443409 2.718 ||| 0-0 1-1 2-2 3-3 ||| 1 1 1"); StringPiece line2 = StringPiece("! ! ! ) , has ||| ! ! ! ) - , a ||| 0.0804289 0.0257627 0.0804289 0.00146736 2.718 ||| 0-0 1-1 2-2 3-3 4-4 4-5 5-6 ||| 1 1 1"); line_text output = splitLine(line1); line_text output2 = splitLine(line2); //Init container vector and iterator. std::vector<char> container; container.reserve(10000); //Reserve vector std::vector<char>::iterator it = container.begin(); //Put a value into the vector it = vector_append(&output, &container, it, false); it = vector_append(&output2, &container, it, false); std::string test(container.begin(), container.end()); std::string should_be = "! ! ! ! 0.0804289 0.141656 0.0804289 0.443409 2.718 0-0 1-1 2-2 3-3 1 1 1! ! ! ) - , a 0.0804289 0.0257627 0.0804289 0.00146736 2.718 0-0 1-1 2-2 3-3 4-4 4-5 5-6 1 1 1"; if (test == should_be) { return true; } else { return false; } } void test(){ bool test_res = test_tokenization(); bool test_res2 = test_vectorinsert(); if (test_res){ std::cout << "Test passes" << std::endl; } else { std::cout << "Tokenization test fails" << std::endl; } if (test_res2){ std::cout << "Test passes" << std::endl; } else { std::cout << "Vector insert test fails" << std::endl; } } <commit_msg>Longest entry binary file<commit_after>#include "util/file_piece.hh" #include "util/file.hh" #include "util/usage.hh" #include <stdio.h> #include <fstream> #include <iostream> #include <ctime> //for timing. #include <chrono> #include "helpers/hash.hh" #include "helpers/line_splitter.hh" #include "helpers/probing_hash_utils.hh" #include "helpers/vocabid.hh" //Appends to the vector used for outputting. std::pair<std::vector<char>::iterator, int> vector_append(line_text *input, std::vector<char> *outputvec, bool new_entry); std::pair<std::vector<char>::iterator, int> vector_append(line_text* input, std::vector<char>* outputvec, std::vector<char>::iterator it, bool new_entry){ //Append everything to one string std::string temp = ""; int vec_size = 0; int new_string_size = 0; if (new_entry){ //If we have a new entry, add an empty line. temp += '\n'; } temp += input->target_phrase.as_string() + "\t" + input->prob.as_string() + "\t" + input->word_all1.as_string() + "\t" + input->word_all2.as_string() + "\n"; //Put into vector outputvec->insert(it, temp.begin(), temp.end()); //Return new iterator updated iterator //Return iterator + length std::pair<std::vector<char>::iterator, int> retvalues (it+temp.length(), temp.length()); return retvalues; } int main(int argc, char* argv[]){ //Time everything std::clock_t c_start = std::clock(); auto t_start = std::chrono::high_resolution_clock::now(); if (argc != 6) { // Tell the user how to run the program std::cerr << "Provided " << argc << " arguments, needed 4." << std::endl; std::cerr << "Usage: " << argv[0] << " path_to_phrasetable number_of_uniq_lines output_bin_file output_hash_table output_vocab_id" << std::endl; return 1; } //Read the file util::FilePiece filein(argv[1]); int tablesize = atoi(argv[2]); //Init the table size_t size = Table::Size(tablesize, 1.2); char * mem = new char[size]; memset(mem, 0, size); Table table(mem, size); //Vocab id std::map<uint64_t, std::string> vocabids; //Output binary std::ofstream os (argv[3], std::ios::binary); //Vector with 10000 elements, after the 9000nd we swap to disk, we have 10000 for buffer std::vector<char> ram_container; ram_container.reserve(10000); std::vector<char>::iterator it = ram_container.begin(); std::pair<std::vector<char>::iterator, int> binary_append_ret; //Return values from vector_append unsigned int dist_from_start = 0; uint64_t extra_counter = 0; //After we reset the counter, we still want to keep track of the correct offset, so //we should keep an extra counter for that reason. line_text prev_line; //Check if the source phrase of the previous line is the same int longestchars = 0; //Keep track of what is the maximum number of characters we need to read when quering int currentlong = 0; //How long is the current //Read everything and processs while(true){ //Calculate offset dist_from_start = distance(ram_container.begin(),it); try { //Process line read line_text line; line = splitLine(filein.ReadLine()); if (line.source_phrase != prev_line.source_phrase){ //Add to vocabid add_to_map(&vocabids, line.source_phrase); add_to_map(&vocabids, line.target_phrase); //Create an entry only for different source phrases. //Create an entry to keep track of the offset Entry pesho; pesho.value = dist_from_start + extra_counter; pesho.key = getHash(line.source_phrase); //Put into table table.Insert(pesho); prev_line = line; binary_append_ret = vector_append(&line, &ram_container, it, true); //Put into the array and update iterator to the new end position it = binary_append_ret.first; //Keep track how long the vector append string for the current source entry is. currentlong = currentlong + binary_append_ret.second; } else{ add_to_map(&vocabids, line.target_phrase); binary_append_ret = vector_append(&line, &ram_container, it, false); //Put into the array and update iterator to the new end position it = binary_append_ret.first; //Keep track how long the vector append string for the current source entry is. //We have started a new entry so we check if the old one is longer than the previous longest if (currentlong > longestchars) { longestchars = currentlong; } currentlong = binary_append_ret.second; } //Write to disk if over 10000 if (dist_from_start > 9000) { //write to memory os.write(&ram_container[0], dist_from_start); //Clear the vector: ram_container.clear(); ram_container.reserve(10000); extra_counter += dist_from_start; it = ram_container.begin(); //Reset iterator } } catch (util::EndOfFileException e){ std::cout << "End of file" << std::endl; os.write(&ram_container[0], dist_from_start); break; } } serialize_table(mem, size, argv[4]); //clean up os.close(); ram_container.clear(); delete[] mem; //Serialize vocabids serialize_map(&vocabids, argv[5]); vocabids.clear(); //End timing std::clock_t c_end = std::clock(); auto t_end = std::chrono::high_resolution_clock::now(); //Show how long is the longest entry: std::cout << "Longest entry is " << longestchars << " character long!" << std::endl; //Print timing results std::cout << "CPU time used: "<< 1000.0 * (c_end-c_start) / CLOCKS_PER_SEC<< " ms\n"; std::cout << "Real time passed: "<< std::chrono::duration_cast<std::chrono::milliseconds>(t_end - t_start).count()<< " ms\n"; util::PrintUsage(std::cout); return 1; } bool test_tokenization(){ StringPiece line1 = StringPiece("! ! ! ! ||| ! ! ! ! ||| 0.0804289 0.141656 0.0804289 0.443409 2.718 ||| 0-0 1-1 2-2 3-3 ||| 1 1 1"); StringPiece line2 = StringPiece("! ! ! ) , has ||| ! ! ! ) - , a ||| 0.0804289 0.0257627 0.0804289 0.00146736 2.718 ||| 0-0 1-1 2-2 3-3 4-4 4-5 5-6 ||| 1 1 1"); StringPiece line3 = StringPiece("! ! ! ) , ||| ! ! ! ) - , ||| 0.0804289 0.075225 0.0804289 0.00310345 2.718 ||| 0-0 1-1 2-2 3-3 4-4 4-5 ||| 1 1 1"); StringPiece line4 = StringPiece("! ! ! ) ||| ! ! ! ) . ||| 0.0804289 0.177547 0.0268096 0.000872597 2.718 ||| 0-0 1-1 2-2 3-3 ||| 1 3 1"); line_text output1 = splitLine(line1); line_text output2 = splitLine(line2); line_text output3 = splitLine(line3); line_text output4 = splitLine(line4); bool test1 = output1.prob == StringPiece("0.0804289 0.141656 0.0804289 0.443409 2.718"); bool test2 = output2.word_all1 == StringPiece("0-0 1-1 2-2 3-3 4-4 4-5 5-6"); bool test3 = output2.target_phrase == StringPiece("! ! ! ) - , a"); bool test4 = output3.source_phrase == StringPiece("! ! ! ) ,"); bool test5 = output4.word_all2 == StringPiece("1 3 1"); //std::cout << test1 << " " << test2 << " " << test3 << " " << test4 << std::endl; if (test1 && test2 && test3 && test4 && test5){ return true; }else{ return false; } } bool test_vectorinsert() { StringPiece line1 = StringPiece("! ! ! ! ||| ! ! ! ! ||| 0.0804289 0.141656 0.0804289 0.443409 2.718 ||| 0-0 1-1 2-2 3-3 ||| 1 1 1"); StringPiece line2 = StringPiece("! ! ! ) , has ||| ! ! ! ) - , a ||| 0.0804289 0.0257627 0.0804289 0.00146736 2.718 ||| 0-0 1-1 2-2 3-3 4-4 4-5 5-6 ||| 1 1 1"); line_text output = splitLine(line1); line_text output2 = splitLine(line2); //Init container vector and iterator. std::vector<char> container; container.reserve(10000); //Reserve vector std::vector<char>::iterator it = container.begin(); std::pair<std::vector<char>::iterator, int> binary_append_ret; //Return values from vector_append //Put a value into the vector binary_append_ret = vector_append(&output, &container, it, false); it = binary_append_ret.first; binary_append_ret = vector_append(&output2, &container, it, false); it = binary_append_ret.first; std::string test(container.begin(), container.end()); std::string should_be = "! ! ! ! 0.0804289 0.141656 0.0804289 0.443409 2.718 0-0 1-1 2-2 3-3 1 1 1! ! ! ) - , a 0.0804289 0.0257627 0.0804289 0.00146736 2.718 0-0 1-1 2-2 3-3 4-4 4-5 5-6 1 1 1"; if (test == should_be) { return true; } else { return false; } } void test(){ bool test_res = test_tokenization(); bool test_res2 = test_vectorinsert(); if (test_res){ std::cout << "Test passes" << std::endl; } else { std::cout << "Tokenization test fails" << std::endl; } if (test_res2){ std::cout << "Test passes" << std::endl; } else { std::cout << "Vector insert test fails" << std::endl; } } <|endoftext|>
<commit_before><commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.370); FILE MERGED 2005/09/05 13:50:37 rt 1.1.1.1.370.1: #i54170# Change license header: remove SISSL<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "source/fuzz/fuzzer_pass_apply_id_synonyms.h" #include "source/fuzz/id_use_descriptor.h" #include "source/fuzz/transformation_replace_id_with_synonym.h" namespace spvtools { namespace fuzz { FuzzerPassApplyIdSynonyms::FuzzerPassApplyIdSynonyms( opt::IRContext* ir_context, FactManager* fact_manager, FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations) : FuzzerPass(ir_context, fact_manager, fuzzer_context, transformations) {} FuzzerPassApplyIdSynonyms::~FuzzerPassApplyIdSynonyms() = default; void FuzzerPassApplyIdSynonyms::Apply() { std::vector<TransformationReplaceIdWithSynonym> transformations_to_apply; for (auto id_with_known_synonyms : GetFactManager()->GetIdsForWhichSynonymsAreKnown()) { GetIRContext()->get_def_use_mgr()->ForEachUse( id_with_known_synonyms, [this, id_with_known_synonyms, &transformations_to_apply]( opt::Instruction* use_inst, uint32_t use_index) -> void { auto block_containing_use = GetIRContext()->get_instr_block(use_inst); // The use might not be in a block; e.g. it could be a decoration. if (!block_containing_use) { return; } if (!GetFuzzerContext()->ChoosePercentage( GetFuzzerContext()->GetChanceOfReplacingIdWithSynonym())) { return; } std::vector<const protobufs::DataDescriptor*> synonyms_to_try; for (auto& data_descriptor : GetFactManager()->GetSynonymsForId(id_with_known_synonyms)) { synonyms_to_try.push_back(&data_descriptor); } while (!synonyms_to_try.empty()) { auto synonym_index = GetFuzzerContext()->RandomIndex(synonyms_to_try); auto synonym_to_try = synonyms_to_try[synonym_index]; synonyms_to_try.erase(synonyms_to_try.begin() + synonym_index); assert(synonym_to_try->index().empty() && "Right now we only support id == id synonyms; supporting " "e.g. id == index-into-vector will come later"); if (!TransformationReplaceIdWithSynonym:: ReplacingUseWithSynonymIsOk(GetIRContext(), use_inst, use_index, *synonym_to_try)) { continue; } // |use_index| is the absolute index of the operand. We require // the index of the operand restricted to input operands only, so // we subtract the number of non-input operands from |use_index|. uint32_t number_of_non_input_operands = use_inst->NumOperands() - use_inst->NumInOperands(); TransformationReplaceIdWithSynonym replace_id_transformation( transformation::MakeIdUseDescriptorFromUse( GetIRContext(), use_inst, use_index - number_of_non_input_operands), *synonym_to_try, 0); // The transformation should be applicable by construction. assert(replace_id_transformation.IsApplicable(GetIRContext(), *GetFactManager())); // We cannot actually apply the transformation here, as this would // change the analysis results that are being depended on for usage // iteration. We instead store them up and apply them at the end // of the method. transformations_to_apply.push_back(replace_id_transformation); break; } }); } for (auto& replace_id_transformation : transformations_to_apply) { // Even though replacing id uses with synonyms may lead to new instructions // (to compute indices into composites), as these instructions will generate // ids, their presence should not affect the id use descriptors that were // computed during the creation of transformations. Thus transformations // should not disable one another. assert(replace_id_transformation.IsApplicable(GetIRContext(), *GetFactManager())); replace_id_transformation.Apply(GetIRContext(), GetFactManager()); *GetTransformations()->add_transformation() = replace_id_transformation.ToMessage(); } } } // namespace fuzz } // namespace spvtools <commit_msg>Fix operand index in spirv-fuzz (#2895)<commit_after>// Copyright (c) 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "source/fuzz/fuzzer_pass_apply_id_synonyms.h" #include "source/fuzz/id_use_descriptor.h" #include "source/fuzz/transformation_replace_id_with_synonym.h" namespace spvtools { namespace fuzz { FuzzerPassApplyIdSynonyms::FuzzerPassApplyIdSynonyms( opt::IRContext* ir_context, FactManager* fact_manager, FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations) : FuzzerPass(ir_context, fact_manager, fuzzer_context, transformations) {} FuzzerPassApplyIdSynonyms::~FuzzerPassApplyIdSynonyms() = default; void FuzzerPassApplyIdSynonyms::Apply() { std::vector<TransformationReplaceIdWithSynonym> transformations_to_apply; for (auto id_with_known_synonyms : GetFactManager()->GetIdsForWhichSynonymsAreKnown()) { GetIRContext()->get_def_use_mgr()->ForEachUse( id_with_known_synonyms, [this, id_with_known_synonyms, &transformations_to_apply]( opt::Instruction* use_inst, uint32_t use_index) -> void { auto block_containing_use = GetIRContext()->get_instr_block(use_inst); // The use might not be in a block; e.g. it could be a decoration. if (!block_containing_use) { return; } if (!GetFuzzerContext()->ChoosePercentage( GetFuzzerContext()->GetChanceOfReplacingIdWithSynonym())) { return; } // |use_index| is the absolute index of the operand. We require // the index of the operand restricted to input operands only, so // we subtract the number of non-input operands from |use_index|. uint32_t use_in_operand_index = use_index - use_inst->NumOperands() + use_inst->NumInOperands(); std::vector<const protobufs::DataDescriptor*> synonyms_to_try; for (auto& data_descriptor : GetFactManager()->GetSynonymsForId(id_with_known_synonyms)) { synonyms_to_try.push_back(&data_descriptor); } while (!synonyms_to_try.empty()) { auto synonym_index = GetFuzzerContext()->RandomIndex(synonyms_to_try); auto synonym_to_try = synonyms_to_try[synonym_index]; synonyms_to_try.erase(synonyms_to_try.begin() + synonym_index); assert(synonym_to_try->index().empty() && "Right now we only support id == id synonyms; supporting " "e.g. id == index-into-vector will come later"); if (!TransformationReplaceIdWithSynonym:: ReplacingUseWithSynonymIsOk(GetIRContext(), use_inst, use_in_operand_index, *synonym_to_try)) { continue; } TransformationReplaceIdWithSynonym replace_id_transformation( transformation::MakeIdUseDescriptorFromUse( GetIRContext(), use_inst, use_in_operand_index), *synonym_to_try, 0); // The transformation should be applicable by construction. assert(replace_id_transformation.IsApplicable(GetIRContext(), *GetFactManager())); // We cannot actually apply the transformation here, as this would // change the analysis results that are being depended on for usage // iteration. We instead store them up and apply them at the end // of the method. transformations_to_apply.push_back(replace_id_transformation); break; } }); } for (auto& replace_id_transformation : transformations_to_apply) { // Even though replacing id uses with synonyms may lead to new instructions // (to compute indices into composites), as these instructions will generate // ids, their presence should not affect the id use descriptors that were // computed during the creation of transformations. Thus transformations // should not disable one another. assert(replace_id_transformation.IsApplicable(GetIRContext(), *GetFactManager())); replace_id_transformation.Apply(GetIRContext(), GetFactManager()); *GetTransformations()->add_transformation() = replace_id_transformation.ToMessage(); } } } // namespace fuzz } // namespace spvtools <|endoftext|>
<commit_before>/* 1837. Isenbaev's Number Time limit: 0.5 second Memory limit: 64 MB [Description] Vladislav Isenbaev is a two-time champion of Ural, vice champion of TopCoder Open 2009, and absolute champion of ACM ICPC 2009. In the time you will spend reading this problem statement Vladislav would have solved a problem. Maybe, even two… Since Vladislav Isenbaev graduated from the Specialized Educational and Scientific Center at Ural State University, many of the former and present contestants at USU have known him for quite a few years. Some of them are proud to say that they either played in the same team with him or played in the same team with one of his teammates… Let us define Isenbaev's number as follows. This number for Vladislav himself is 0. For people who played in the same team with him, the number is 1. For people who weren't his teammates but played in the same team with one or more of his teammates, the number is 2, and so on. Your task is to automate the process of calculating Isenbaev's numbers so that each contestant at USU would know their proximity to the ACM ICPC champion. [Input] The first line contains the number of teams n (1 ≤ n ≤ 100). In each of the following n lines you are given the names of the three members of the corres- ponding team. The names are separated with a space. Each name is a nonempty line consisting of English letters, and its length is at most 20 symbols. The first letter of a name is capital and the other letters are lowercase. [Output] For each contestant mentioned in the input data output a line with their name and Isenbaev's number. If the number is undefined, output “undefined” instead of it. The contestants must be ordered lexicographically. */ #include <cassert> #include <cstdio> #include <cstdlib> #include <cinttypes> #include <cmath> #include <memory> #include <iostream> #include <sstream> #include <string> #include <vector> #include <list> #include <map> #include <set> #include <queue> #include <stack> #include <algorithm> using namespace std; // Get a single input from stdin template<typename T> static void get_single_input(T& x) { string line; getline(cin, line); istringstream input(line); input >> x; } // Get a line input from stdin // Add the values as elements in Container template<typename Container> static void get_inputs(Container& c) { typedef typename Container::value_type T; string line; while (getline(cin, line)) { istringstream input(line); T x; while (input >> x) { c.push_back(x); } } } enum NODE_COLOR { COLOR_WHITE, // never visited COLOR_GREY, // discovered COLOR_BLACK // visit from current node finished }; template <typename Node> struct NodeHolder { Node node; shared_ptr<NodeHolder> parent; NODE_COLOR color; int32_t distance; // used for BFS, recording distance to source int32_t discover_time; // used for DFS, recording time when this node is discovered int32_t finish_time; // used for DFS, recording time when DFS from this node is finished NodeHolder() : color(COLOR_WHITE) , distance(-1) , discover_time(-1) , finish_time(-1) {} explicit NodeHolder(const Node& n) : node(n) , color(COLOR_WHITE) , distance(-1) , discover_time(-1) , finish_time(-1) {} NodeHolder(const NodeHolder& other) : node(other.node) , parent(other.parent) , color(other.color) , distance(other.distance) , discover_time(-1) , finish_time(-1) {} void reset() { parent.reset(); color = COLOR_WHITE; distance = -1; discover_time = -1; finish_time = -1; } NodeHolder& operator=(const NodeHolder& other) { if (this != &other) { node = other.node; parent = other.parent; color = other.color; distance = other.distance; discover_time = other.discover_time; finish_time = other.finish_time; } return *this; } bool operator==(const NodeHolder& other) const { return (node == other.node); } bool operator<(const NodeHolder& other) const { return (node < other.node); } }; template <typename Node> class AdjacentList { private: typedef shared_ptr<NodeHolder<Node> > _Node; typedef set<_Node> NodeList; typedef typename NodeList::iterator NodeIter; typedef typename NodeList::const_iterator NodeConstIter; typedef map<_Node, NodeList> NodeListMap; typedef typename NodeListMap::iterator NodeMapIter; typedef typename NodeListMap::const_iterator NodeMapConstIter; public: set<shared_ptr<NodeHolder<Node> > > getVertexs() const { NodeList vertexs; for (NodeMapConstIter it = list_.cbegin(); it != list_.cend(); ++it) { const _Node& node = it->first; if (node) { vertexs.insert(node); } } return vertexs; } shared_ptr<NodeHolder<Node> > addVertex(const Node& n) { for (NodeMapConstIter it = list_.cbegin(); it != list_.cend(); ++it) { const _Node& node = it->first; if (node && node->node == n) { return node; } } _Node node = make_shared<NodeHolder<Node> >(n); if (node) { list_[node] = NodeList(); } return node; } void addEdge(const Node& from, const Node& to) { _Node _from = addVertex(from); _Node _to = addVertex(to); if (_from && _to) { list_[_from].insert(_to); } } void bfs(const Node& n) { _Node node = resetSource(n); if (!node) { return; } node->color = COLOR_GREY; node->distance = 0; queue<_Node> q; q.push(node); while (!q.empty()) { _Node u = q.front(); q.pop(); if (!u || list_.find(u) == list_.end()) { continue; } for (NodeIter v = list_[u].begin(); v != list_[u].end(); ++v) { const _Node& _v = *v; if (!_v) { continue; } if (_v->color == COLOR_WHITE) { _v->color = COLOR_GREY; _v->distance = u->distance + 1; _v->parent = u; q.push(_v); } } u->color = COLOR_BLACK; } } void dfs() { for (NodeMapIter x = list_.begin(); x != list_.end(); ++x) { const _Node& node = x->first; if (!node) { continue; } node->reset(); } int32_t t = 0; for (NodeMapIter x = list_.begin(); x != list_.end(); ++x) { const _Node& node = x->first; if (!node) { continue; } if (node->color == COLOR_WHITE) { dfsVisit(node, t); } } } void dump() const { for (NodeMapConstIter x = list_.cbegin(); x != list_.cend(); ++x) { const _Node& n = x->first; const NodeList l = x->second; if (!n) { continue; } cout << n->node << ": [ "; for (NodeConstIter y = l.cbegin(); y != l.cend(); ++y) { const _Node& n = *y; if (n) { cout << n->node << " "; } } cout << "]\n"; } } private: _Node resetSource(const Node& n) { bool found = false; _Node node; for (NodeMapIter it = list_.begin(); it != list_.end(); ++it) { const _Node& _node = it->first; if (!_node) { continue; } _node->reset(); if (!found && _node->node == n) { node = _node; found = true; } } return node; } void dfsVisit(const _Node& n, int32_t& t) { assert(n); // node n has just been discovered ++t; n->discover_time = t; n->color = COLOR_GREY; // explore edge (n, v) for (NodeIter x = list_[n].begin(); x != list_[n].end(); ++x) { const _Node& node = *x; if (node->color == COLOR_WHITE) { node->parent = n; dfsVisit(node, t); } } // blacken n, it is finished n->color = COLOR_BLACK; ++t; n->finish_time = t; } private: NodeListMap list_; }; template <typename Node, class Impl = AdjacentList<Node> > class Graph { public: explicit Graph(bool directed = true) : directed_(directed) {} set<shared_ptr<NodeHolder<Node> > > getVertexs() const { return graph_.getVertexs(); } shared_ptr<NodeHolder<Node> > addVertex(const Node& n) { return graph_.addVertex(n); } void addEdge(const Node& from, const Node& to) { graph_.addEdge(from, to); if (!directed_) { graph_.addEdge(to, from); } } void bfs(const Node& n) { graph_.bfs(n); } void dfs() { graph_.dfs(); } void dump() const { graph_.dump(); } private: Impl graph_; bool directed_; }; template <typename Node> void getInput(Graph<Node>& g) { int n = 0; get_single_input(n); //cout << "n = " << n << endl; if (n <= 0) { return; } while (n-- > 0) { string line; getline(cin, line); //cout << "get line = " << line << endl; vector<string> members; string name; istringstream input(line); while (input >> name) { //cout << "get name = " << name << endl; members.push_back(name); } assert(members.size() == 3); g.addEdge(members[0], members[1]); g.addEdge(members[0], members[2]); g.addEdge(members[1], members[2]); } g.dump(); } template <typename Node> map<Node, int> calc(const Node& champion, Graph<Node>& graph) { map<Node, int> result; graph.bfs(champion); set<shared_ptr<NodeHolder<Node> > > vertexs = graph.getVertexs(); for (auto it = vertexs.begin(); it != vertexs.end(); ++it) { result[(*it)->node] = (*it)->distance; } return result; } template <typename Node> void showResult(const map<Node, int>& result) { size_t n = result.size(); for (typename map<Node, int>::const_iterator it = result.cbegin(); it != result.cend(); ++it) { cout << it->first << ' '; if (it->second == -1) { cout << "undefined"; } else { cout << it->second; } if (n > 1) { cout << endl; } --n; } } int main(int argc, char* argv[]) { Graph<string> graph(false /* directed */); getInput(graph); /* const string champion = "Isenbaev"; map<string, int> result = calc(champion, graph); showResult(result); */ graph.dfs(); set<shared_ptr<NodeHolder<string> > > vertexs = graph.getVertexs(); for (auto it = vertexs.begin(); it != vertexs.end(); ++it) { cout << (*it)->node << " [ " << (*it)->discover_time << " / " << (*it)->finish_time << " ]\n"; } return 0; } <commit_msg>Update 1837<commit_after>/* 1837. Isenbaev's Number Time limit: 0.5 second Memory limit: 64 MB [Description] Vladislav Isenbaev is a two-time champion of Ural, vice champion of TopCoder Open 2009, and absolute champion of ACM ICPC 2009. In the time you will spend reading this problem statement Vladislav would have solved a problem. Maybe, even two… Since Vladislav Isenbaev graduated from the Specialized Educational and Scientific Center at Ural State University, many of the former and present contestants at USU have known him for quite a few years. Some of them are proud to say that they either played in the same team with him or played in the same team with one of his teammates… Let us define Isenbaev's number as follows. This number for Vladislav himself is 0. For people who played in the same team with him, the number is 1. For people who weren't his teammates but played in the same team with one or more of his teammates, the number is 2, and so on. Your task is to automate the process of calculating Isenbaev's numbers so that each contestant at USU would know their proximity to the ACM ICPC champion. [Input] The first line contains the number of teams n (1 ≤ n ≤ 100). In each of the following n lines you are given the names of the three members of the corres- ponding team. The names are separated with a space. Each name is a nonempty line consisting of English letters, and its length is at most 20 symbols. The first letter of a name is capital and the other letters are lowercase. [Output] For each contestant mentioned in the input data output a line with their name and Isenbaev's number. If the number is undefined, output “undefined” instead of it. The contestants must be ordered lexicographically. */ #include <cassert> #include <cstdio> #include <cstdlib> #include <cinttypes> #include <cmath> #include <memory> #include <iostream> #include <sstream> #include <string> #include <vector> #include <list> #include <map> #include <set> #include <queue> #include <stack> #include <algorithm> #include <stdexcept> using namespace std; // Get a single input from stdin template<typename T> static void get_single_input(T& x) { string line; getline(cin, line); istringstream input(line); input >> x; } // Get a line input from stdin // Add the values as elements in Container template<typename Container> static void get_inputs(Container& c) { typedef typename Container::value_type T; string line; while (getline(cin, line)) { istringstream input(line); T x; while (input >> x) { c.push_back(x); } } } enum NODE_COLOR { COLOR_WHITE, // never visited COLOR_GREY, // discovered COLOR_BLACK // visit from current node finished }; template <typename Node> struct NodeHolder { Node node; shared_ptr<NodeHolder> parent; NODE_COLOR color; int32_t distance; // used for BFS, recording distance to source int32_t discover_time; // used for DFS, recording time when this node is discovered int32_t finish_time; // used for DFS, recording time when DFS from this node is finished NodeHolder() : color(COLOR_WHITE) , distance(-1) , discover_time(-1) , finish_time(-1) {} explicit NodeHolder(const Node& n) : node(n) , color(COLOR_WHITE) , distance(-1) , discover_time(-1) , finish_time(-1) {} NodeHolder(const NodeHolder& other) : node(other.node) , parent(other.parent) , color(other.color) , distance(other.distance) , discover_time(-1) , finish_time(-1) {} void reset() { parent.reset(); color = COLOR_WHITE; distance = -1; discover_time = -1; finish_time = -1; } NodeHolder& operator=(const NodeHolder& other) { if (this != &other) { node = other.node; parent = other.parent; color = other.color; distance = other.distance; discover_time = other.discover_time; finish_time = other.finish_time; } return *this; } bool operator==(const NodeHolder& other) const { return (node == other.node); } bool operator<(const NodeHolder& other) const { return (node < other.node); } }; template <typename Node> class AdjacentList { private: typedef shared_ptr<NodeHolder<Node> > _Node; typedef set<_Node> NodeList; typedef typename NodeList::iterator NodeIter; typedef typename NodeList::const_iterator NodeConstIter; typedef map<_Node, NodeList> NodeListMap; typedef typename NodeListMap::iterator NodeMapIter; typedef typename NodeListMap::const_iterator NodeMapConstIter; public: set<shared_ptr<NodeHolder<Node> > > getVertexs() const { NodeList vertexs; for (NodeMapConstIter it = list_.cbegin(); it != list_.cend(); ++it) { const _Node& node = it->first; if (node) { vertexs.insert(node); } } return vertexs; } shared_ptr<NodeHolder<Node> > addVertex(const Node& n) { for (NodeMapConstIter it = list_.cbegin(); it != list_.cend(); ++it) { const _Node& node = it->first; if (node && node->node == n) { return node; } } _Node node = make_shared<NodeHolder<Node> >(n); if (node) { list_[node] = NodeList(); } return node; } void addEdge(const Node& from, const Node& to) { _Node _from = addVertex(from); _Node _to = addVertex(to); if (_from && _to) { list_[_from].insert(_to); } } void bfs(const Node& n) { resetStates(); _Node node = convertNode(n); if (!node) { return; } node->color = COLOR_GREY; node->distance = 0; queue<_Node> q; q.push(node); while (!q.empty()) { _Node u = q.front(); q.pop(); if (!u || list_.find(u) == list_.end()) { continue; } for (NodeIter v = list_[u].begin(); v != list_[u].end(); ++v) { const _Node& _v = *v; if (!_v) { continue; } if (_v->color == COLOR_WHITE) { _v->color = COLOR_GREY; _v->distance = u->distance + 1; _v->parent = u; q.push(_v); } } u->color = COLOR_BLACK; } } void dfs() { resetStates(); int32_t t = 0; for (NodeMapIter x = list_.begin(); x != list_.end(); ++x) { const _Node& node = x->first; if (!node) { continue; } if (node->color == COLOR_WHITE) { dfsVisit(node, t); } } } void dfs(const Node& n) { resetStates(); _Node node = convertNode(n); if (!node) { return; } int32_t t = 0; dfsVisit(node, t); } list<shared_ptr<NodeHolder<Node> > > topologicalSort() { dfs(); return topological_list_; } bool hasLoop() { dfs(); return loop_detected_; } void dump() const { for (NodeMapConstIter x = list_.cbegin(); x != list_.cend(); ++x) { const _Node& n = x->first; const NodeList l = x->second; if (!n) { continue; } cout << n->node << ": [ "; for (NodeConstIter y = l.cbegin(); y != l.cend(); ++y) { const _Node& n = *y; if (n) { cout << n->node << " "; } } cout << "]\n"; } } private: _Node convertNode(const Node& n) { _Node _node; for (NodeMapIter it = list_.begin(); it != list_.end(); ++it) { const _Node& _n = it->first; if (!_n && _n->node == n) { _node = _n; break; } } return _node; } void resetStates() { loop_detected_ = false; for (NodeMapIter it = list_.begin(); it != list_.end(); ++it) { const _Node& _node = it->first; if (!_node) { continue; } _node->reset(); } } void dfsVisit(const _Node& n, int32_t& t) { assert(n); // node n has just been discovered ++t; n->discover_time = t; n->color = COLOR_GREY; // explore edge (n, v) for (NodeIter x = list_[n].begin(); x != list_[n].end(); ++x) { const _Node& node = *x; if (node->color == COLOR_WHITE) { node->parent = n; dfsVisit(node, t); } else if (node->color == COLOR_GREY) { loop_detected_ = true; } } // blacken n, it is finished n->color = COLOR_BLACK; ++t; n->finish_time = t; // insert n at the front of topological list topological_list_.insert(topological_list_.begin(), n); } private: NodeListMap list_; bool loop_detected_; list<_Node> topological_list_; }; class IllegalOperation : public runtime_error { public: explicit IllegalOperation(const string& msg) : runtime_error(msg) {} }; template <typename Node, class Impl = AdjacentList<Node> > class Graph { public: explicit Graph(bool directed = true) : directed_(directed) {} set<shared_ptr<NodeHolder<Node> > > getVertexs() const { return graph_.getVertexs(); } shared_ptr<NodeHolder<Node> > addVertex(const Node& n) { return graph_.addVertex(n); } void addEdge(const Node& from, const Node& to) { graph_.addEdge(from, to); if (!directed_) { graph_.addEdge(to, from); } } void bfs(const Node& n) { graph_.bfs(n); } void dfs() { graph_.dfs(); } void dfs(const Node& n) { graph_.dfs(n); } bool hasLoop() { return graph_.hasLoop(); } list<shared_ptr<NodeHolder<Node> > > topologicalSort() { if (!directed_ || graph_.hasLoop()) { throw IllegalOperation("Topological sort can only be used on a directed non-loop graph"); } return graph_.topologicalSort(); } void dump() const { graph_.dump(); } private: Impl graph_; bool directed_; }; template <typename Node> void getInput(Graph<Node>& g) { int n = 0; get_single_input(n); //cout << "n = " << n << endl; if (n <= 0) { return; } while (n-- > 0) { string line; getline(cin, line); //cout << "get line = " << line << endl; vector<string> members; string name; istringstream input(line); while (input >> name) { //cout << "get name = " << name << endl; members.push_back(name); } assert(members.size() == 3); g.addEdge(members[0], members[1]); g.addEdge(members[0], members[2]); g.addEdge(members[1], members[2]); } g.dump(); } template <typename Node> map<Node, int> calc(const Node& champion, Graph<Node>& graph) { map<Node, int> result; graph.bfs(champion); set<shared_ptr<NodeHolder<Node> > > vertexs = graph.getVertexs(); for (auto it = vertexs.begin(); it != vertexs.end(); ++it) { result[(*it)->node] = (*it)->distance; } return result; } template <typename Node> void showResult(const map<Node, int>& result) { size_t n = result.size(); for (typename map<Node, int>::const_iterator it = result.cbegin(); it != result.cend(); ++it) { cout << it->first << ' '; if (it->second == -1) { cout << "undefined"; } else { cout << it->second; } if (n > 1) { cout << endl; } --n; } } int main(int argc, char* argv[]) { Graph<string> graph(false /* directed */); getInput(graph); /* const string champion = "Isenbaev"; map<string, int> result = calc(champion, graph); showResult(result); */ try { list<shared_ptr<NodeHolder<string> > > topological_list = graph.topologicalSort(); for (auto it = topological_list.begin(); it != topological_list.end(); ++it) { cout << (*it)->node << " [ " << (*it)->discover_time << ", " << (*it)->finish_time << " ] \n"; } } catch (const IllegalOperation& e) { cout << e.what() << endl; } return 0; } <|endoftext|>
<commit_before>#include "drape_frontend/gps_track_renderer.hpp" #include "drape_frontend/visual_params.hpp" #include "drape/glsl_func.hpp" #include "drape/shader_def.hpp" #include "drape/vertex_array_buffer.hpp" #include "indexer/scales.hpp" #include "geometry/rect_intersect.hpp" #include "base/logging.hpp" #include "std/algorithm.hpp" namespace df { namespace { //#define SHOW_RAW_POINTS int const kMinVisibleZoomLevel = 10; size_t const kAveragePointsCount = 512; // Radius of circles depending on zoom levels. float const kRadiusInPixel[] = { // 1 2 3 4 5 6 7 8 9 10 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 3.0f, 3.0f, //11 12 13 14 15 16 17 18 19 20 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 4.0f, 5.0f, 5.0f, 5.0f, 6.0f }; double const kMinSpeed = 1.4; // meters per second double const kAvgSpeed = 3.3; // meters per second double const kMaxSpeed = 5.5; // meters per second dp::Color const kMinSpeedColor = dp::Color(255, 0, 0, 255); dp::Color const kAvgSpeedColor = dp::Color(251, 192, 45, 255); dp::Color const kMaxSpeedColor = dp::Color(44, 120, 47, 255); uint8_t const kMinAlpha = 50; uint8_t const kMaxAlpha = 255; float const kOutlineRadiusScalar = 0.3f; double const kUnknownDistanceTime = 5 * 60; // seconds dp::Color const kUnknownDistanceColor = dp::Color(127, 127, 127, 127); bool GpsPointsSortPredicate(GpsTrackPoint const & pt1, GpsTrackPoint const & pt2) { return pt1.m_id < pt2.m_id; } dp::Color InterpolateColors(dp::Color const & color1, dp::Color const & color2, double t) { double const r = color1.GetRed() * (1.0 - t) + color2.GetRed() * t; double const g = color1.GetGreen() * (1.0 - t) + color2.GetGreen() * t; double const b = color1.GetBlue() * (1.0 - t) + color2.GetBlue() * t; double const a = color1.GetAlfa() * (1.0 - t) + color2.GetAlfa() * t; return dp::Color(r, g, b, a); } } // namespace GpsTrackRenderer::GpsTrackRenderer(TRenderDataRequestFn const & dataRequestFn) : m_dataRequestFn(dataRequestFn) , m_needUpdate(false) , m_waitForRenderData(false) , m_startSpeed(0.0) , m_endSpeed(0.0) , m_startColor(kMaxSpeedColor) , m_radius(0.0f) { ASSERT(m_dataRequestFn != nullptr, ()); m_points.reserve(kAveragePointsCount); m_handlesCache.reserve(8); } float GpsTrackRenderer::CalculateRadius(ScreenBase const & screen) const { double const kLog2 = log(2.0); double const zoomLevel = my::clamp(fabs(log(screen.GetScale()) / kLog2), 1.0, scales::UPPER_STYLE_SCALE + 1.0); double zoom = trunc(zoomLevel); int const index = zoom - 1.0; float const lerpCoef = zoomLevel - zoom; float radius = 0.0f; if (index < scales::UPPER_STYLE_SCALE) radius = kRadiusInPixel[index] + lerpCoef * (kRadiusInPixel[index + 1] - kRadiusInPixel[index]); else radius = kRadiusInPixel[scales::UPPER_STYLE_SCALE]; return radius * VisualParams::Instance().GetVisualScale(); } void GpsTrackRenderer::AddRenderData(ref_ptr<dp::GpuProgramManager> mng, drape_ptr<GpsTrackRenderData> && renderData) { drape_ptr<GpsTrackRenderData> data = move(renderData); ref_ptr<dp::GpuProgram> program = mng->GetProgram(gpu::TRACK_POINT_PROGRAM); program->Bind(); data->m_bucket->GetBuffer()->Build(program); m_renderData.push_back(move(data)); m_waitForRenderData = false; } void GpsTrackRenderer::UpdatePoints(vector<GpsTrackPoint> const & toAdd, vector<uint32_t> const & toRemove) { if (!toRemove.empty()) { auto removePredicate = [&toRemove](GpsTrackPoint const & pt) { return find(toRemove.begin(), toRemove.end(), pt.m_id) != toRemove.end(); }; m_points.erase(remove_if(m_points.begin(), m_points.end(), removePredicate), m_points.end()); } if (!toAdd.empty()) { ASSERT(is_sorted(toAdd.begin(), toAdd.end(), GpsPointsSortPredicate), ()); if (!m_points.empty()) ASSERT(GpsPointsSortPredicate(m_points.back(), toAdd.front()), ()); m_points.insert(m_points.end(), toAdd.begin(), toAdd.end()); } m_needUpdate = true; } double GpsTrackRenderer::CalculateTrackLength() const { double len = 0.0; for (size_t i = 0; i + 1 < m_points.size(); i++) len += (m_points[i + 1].m_point - m_points[i].m_point).Length(); return len; } void GpsTrackRenderer::UpdateSpeedsAndColors() { m_startSpeed = 0.0; m_endSpeed = 0.0; for (size_t i = 0; i < m_points.size(); i++) { if (m_points[i].m_speedMPS < m_startSpeed) m_startSpeed = m_points[i].m_speedMPS; if (m_points[i].m_speedMPS > m_endSpeed) m_endSpeed = m_points[i].m_speedMPS; } m_startSpeed = max(m_startSpeed, 0.0); m_endSpeed = max(m_endSpeed, 0.0); double const delta = m_endSpeed - m_startSpeed; if (delta <= kMinSpeed) m_startColor = kMaxSpeedColor; else if (delta <= kAvgSpeed) m_startColor = kAvgSpeedColor; else m_startColor = kMinSpeedColor; m_startSpeed = max(m_startSpeed, kMinSpeed); m_endSpeed = min(m_endSpeed, kMaxSpeed); double const kBias = 0.01; if (fabs(m_endSpeed - m_startSpeed) < 1e-5) m_endSpeed += kBias; } size_t GpsTrackRenderer::GetAvailablePointsCount() const { size_t pointsCount = 0; for (size_t i = 0; i < m_renderData.size(); i++) pointsCount += m_renderData[i]->m_pointsCount; return pointsCount; } double GpsTrackRenderer::PlacePoints(size_t & cacheIndex, GpsTrackPoint const & start, GpsTrackPoint const & end, double clipStart, double clipEnd, float radius, double diameterMercator, double offset, double trackLengthMercator, double lengthFromStart, bool & gap) { double const kDistanceScalar = 0.65; bool const unknownDistance = (end.m_timestamp - start.m_timestamp) > kUnknownDistanceTime; m2::PointD const delta = end.m_point - start.m_point; double const length = delta.Length(); m2::PointD const dir = delta.Normalize(); double pos = offset; while (pos < length) { if (gap && pos >= clipStart && pos <= clipEnd) { double const dist = pos + diameterMercator * 0.5; dp::Color color = kUnknownDistanceColor; if (!unknownDistance) { double const td = my::clamp(dist / length, 0.0, 1.0); double const speed = max(start.m_speedMPS * (1.0 - td) + end.m_speedMPS * td, 0.0); double const ts = my::clamp((speed - m_startSpeed) / (m_endSpeed - m_startSpeed), 0.0, 1.0); color = InterpolateColors(m_startColor, kMaxSpeedColor, ts); double const ta = my::clamp((lengthFromStart + dist) / trackLengthMercator, 0.0, 1.0); double const alpha = kMinAlpha * (1.0 - ta) + kMaxAlpha * ta; color = dp::Color(color.GetRed(), color.GetGreen(), color.GetBlue(), alpha); } m2::PointD const p = start.m_point + dir * dist; m_handlesCache[cacheIndex].first->SetPoint(m_handlesCache[cacheIndex].second, p, radius, color); m_handlesCache[cacheIndex].second++; if (m_handlesCache[cacheIndex].second >= m_handlesCache[cacheIndex].first->GetPointsCount()) cacheIndex++; if (cacheIndex >= m_handlesCache.size()) { m_dataRequestFn(kAveragePointsCount); m_waitForRenderData = true; return -1.0; } } gap = !gap; pos += (diameterMercator * kDistanceScalar); } return pos - length; } void GpsTrackRenderer::RenderTrack(ScreenBase const & screen, int zoomLevel, ref_ptr<dp::GpuProgramManager> mng, dp::UniformValuesStorage const & commonUniforms) { if (zoomLevel < kMinVisibleZoomLevel) return; if (m_needUpdate) { // Skip rendering if there is no any point. if (m_points.empty()) { m_needUpdate = false; return; } // Check if there are render data. if (m_renderData.empty() && !m_waitForRenderData) { m_dataRequestFn(kAveragePointsCount); m_waitForRenderData = true; } if (m_waitForRenderData) return; m_radius = CalculateRadius(screen); float const diameter = 2.0f * m_radius; float const currentScaleGtoP = 1.0f / screen.GetScale(); double const trackLengthMercator = CalculateTrackLength(); // Update points' positions and colors. ASSERT(!m_renderData.empty(), ()); m_handlesCache.clear(); for (size_t i = 0; i < m_renderData.size(); i++) { ASSERT_EQUAL(m_renderData[i]->m_bucket->GetOverlayHandlesCount(), 1, ()); GpsTrackHandle * handle = static_cast<GpsTrackHandle*>(m_renderData[i]->m_bucket->GetOverlayHandle(0).get()); handle->Clear(); m_handlesCache.push_back(make_pair(handle, 0)); } UpdateSpeedsAndColors(); size_t cacheIndex = 0; double lengthFromStart = 0.0; if (m_points.size() == 1) { m_handlesCache[cacheIndex].first->SetPoint(0, m_points.front().m_point, m_radius, kMaxSpeedColor); m_handlesCache[cacheIndex].second++; } else { bool gap = true; double const diameterMercator = diameter / currentScaleGtoP; double offset = 0.0; for (size_t i = 0; i + 1 < m_points.size(); i++) { // Clip points outside visible rect. m2::PointD p1 = m_points[i].m_point; m2::PointD p2 = m_points[i + 1].m_point; double const dist = (m_points[i + 1].m_point - m_points[i].m_point).Length(); if (!m2::Intersect(screen.ClipRect(), p1, p2)) { lengthFromStart += dist; offset = 0.0; continue; } // Check points equality. if (p1.EqualDxDy(p2, 1e-5)) { lengthFromStart += dist; continue; } // Place points. double const clipStart = (p1 - m_points[i].m_point).Length(); double const clipEnd = (p2 - m_points[i].m_point).Length(); offset = PlacePoints(cacheIndex, m_points[i], m_points[i + 1], clipStart, clipEnd, m_radius, diameterMercator, offset, trackLengthMercator, lengthFromStart, gap); if (offset < 0.0) return; lengthFromStart += dist; } #ifdef SHOW_RAW_POINTS for (size_t i = 0; i < m_points.size(); i++) { m_handlesCache[cacheIndex].first->SetPoint(m_handlesCache[cacheIndex].second, m_points[i].m_point, m_radius * 1.2, dp::Color(0, 0, 255, 255)); m_handlesCache[cacheIndex].second++; if (m_handlesCache[cacheIndex].second >= m_handlesCache[cacheIndex].first->GetPointsCount()) cacheIndex++; if (cacheIndex >= m_handlesCache.size()) { m_dataRequestFn(kAveragePointsCount); m_waitForRenderData = true; return; } } #endif } m_needUpdate = false; } if (m_handlesCache.empty() || m_handlesCache.front().second == 0) return; GLFunctions::glClearDepth(); ASSERT_LESS_OR_EQUAL(m_renderData.size(), m_handlesCache.size(), ()); // Render points. dp::UniformValuesStorage uniforms = commonUniforms; uniforms.SetFloatValue("u_opacity", 1.0f); uniforms.SetFloatValue("u_radiusShift", m_radius * kOutlineRadiusScalar); ref_ptr<dp::GpuProgram> program = mng->GetProgram(gpu::TRACK_POINT_PROGRAM); program->Bind(); ASSERT_GREATER(m_renderData.size(), 0, ()); dp::ApplyState(m_renderData.front()->m_state, program); dp::ApplyUniforms(uniforms, program); for (size_t i = 0; i < m_renderData.size(); i++) if (m_handlesCache[i].second != 0) m_renderData[i]->m_bucket->Render(screen); } void GpsTrackRenderer::Update() { m_needUpdate = true; } void GpsTrackRenderer::Clear() { m_points.clear(); m_needUpdate = true; } } // namespace df <commit_msg>Added filtering of unknown points in color calculation<commit_after>#include "drape_frontend/gps_track_renderer.hpp" #include "drape_frontend/visual_params.hpp" #include "drape/glsl_func.hpp" #include "drape/shader_def.hpp" #include "drape/vertex_array_buffer.hpp" #include "indexer/scales.hpp" #include "geometry/rect_intersect.hpp" #include "base/logging.hpp" #include "std/algorithm.hpp" namespace df { namespace { //#define SHOW_RAW_POINTS int const kMinVisibleZoomLevel = 5; size_t const kAveragePointsCount = 512; // Radius of circles depending on zoom levels. float const kRadiusInPixel[] = { // 1 2 3 4 5 6 7 8 9 10 1.0f, 1.0f, 1.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, //11 12 13 14 15 16 17 18 19 20 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 4.0f, 5.0f, 5.0f, 5.0f, 6.0f }; double const kMinSpeed = 1.4; // meters per second double const kAvgSpeed = 3.3; // meters per second double const kMaxSpeed = 5.5; // meters per second dp::Color const kMinSpeedColor = dp::Color(255, 0, 0, 255); dp::Color const kAvgSpeedColor = dp::Color(251, 192, 45, 255); dp::Color const kMaxSpeedColor = dp::Color(44, 120, 47, 255); uint8_t const kMinAlpha = 50; uint8_t const kMaxAlpha = 255; float const kOutlineRadiusScalar = 0.3f; double const kUnknownDistanceTime = 5 * 60; // seconds dp::Color const kUnknownDistanceColor = dp::Color(127, 127, 127, 127); bool GpsPointsSortPredicate(GpsTrackPoint const & pt1, GpsTrackPoint const & pt2) { return pt1.m_id < pt2.m_id; } dp::Color InterpolateColors(dp::Color const & color1, dp::Color const & color2, double t) { double const r = color1.GetRed() * (1.0 - t) + color2.GetRed() * t; double const g = color1.GetGreen() * (1.0 - t) + color2.GetGreen() * t; double const b = color1.GetBlue() * (1.0 - t) + color2.GetBlue() * t; double const a = color1.GetAlfa() * (1.0 - t) + color2.GetAlfa() * t; return dp::Color(r, g, b, a); } } // namespace GpsTrackRenderer::GpsTrackRenderer(TRenderDataRequestFn const & dataRequestFn) : m_dataRequestFn(dataRequestFn) , m_needUpdate(false) , m_waitForRenderData(false) , m_startSpeed(0.0) , m_endSpeed(0.0) , m_startColor(kMaxSpeedColor) , m_radius(0.0f) { ASSERT(m_dataRequestFn != nullptr, ()); m_points.reserve(kAveragePointsCount); m_handlesCache.reserve(8); } float GpsTrackRenderer::CalculateRadius(ScreenBase const & screen) const { double const kLog2 = log(2.0); double const zoomLevel = my::clamp(fabs(log(screen.GetScale()) / kLog2), 1.0, scales::UPPER_STYLE_SCALE + 1.0); double zoom = trunc(zoomLevel); int const index = zoom - 1.0; float const lerpCoef = zoomLevel - zoom; float radius = 0.0f; if (index < scales::UPPER_STYLE_SCALE) radius = kRadiusInPixel[index] + lerpCoef * (kRadiusInPixel[index + 1] - kRadiusInPixel[index]); else radius = kRadiusInPixel[scales::UPPER_STYLE_SCALE]; return radius * VisualParams::Instance().GetVisualScale(); } void GpsTrackRenderer::AddRenderData(ref_ptr<dp::GpuProgramManager> mng, drape_ptr<GpsTrackRenderData> && renderData) { drape_ptr<GpsTrackRenderData> data = move(renderData); ref_ptr<dp::GpuProgram> program = mng->GetProgram(gpu::TRACK_POINT_PROGRAM); program->Bind(); data->m_bucket->GetBuffer()->Build(program); m_renderData.push_back(move(data)); m_waitForRenderData = false; } void GpsTrackRenderer::UpdatePoints(vector<GpsTrackPoint> const & toAdd, vector<uint32_t> const & toRemove) { if (!toRemove.empty()) { auto removePredicate = [&toRemove](GpsTrackPoint const & pt) { return find(toRemove.begin(), toRemove.end(), pt.m_id) != toRemove.end(); }; m_points.erase(remove_if(m_points.begin(), m_points.end(), removePredicate), m_points.end()); } if (!toAdd.empty()) { ASSERT(is_sorted(toAdd.begin(), toAdd.end(), GpsPointsSortPredicate), ()); if (!m_points.empty()) ASSERT(GpsPointsSortPredicate(m_points.back(), toAdd.front()), ()); m_points.insert(m_points.end(), toAdd.begin(), toAdd.end()); } m_needUpdate = true; } double GpsTrackRenderer::CalculateTrackLength() const { double len = 0.0; for (size_t i = 0; i + 1 < m_points.size(); i++) len += (m_points[i + 1].m_point - m_points[i].m_point).Length(); return len; } void GpsTrackRenderer::UpdateSpeedsAndColors() { m_startSpeed = 0.0; m_endSpeed = 0.0; for (size_t i = 0; i < m_points.size(); i++) { // Filter unknown points. if (i > 0 && (m_points[i].m_timestamp - m_points[i - 1].m_timestamp) > kUnknownDistanceTime) continue; if (m_points[i].m_speedMPS < m_startSpeed) m_startSpeed = m_points[i].m_speedMPS; if (m_points[i].m_speedMPS > m_endSpeed) m_endSpeed = m_points[i].m_speedMPS; } m_startSpeed = max(m_startSpeed, 0.0); m_endSpeed = max(m_endSpeed, 0.0); double const delta = m_endSpeed - m_startSpeed; if (delta <= kMinSpeed) m_startColor = kMaxSpeedColor; else if (delta <= kAvgSpeed) m_startColor = kAvgSpeedColor; else m_startColor = kMinSpeedColor; m_startSpeed = max(m_startSpeed, kMinSpeed); m_endSpeed = min(m_endSpeed, kMaxSpeed); double const kBias = 0.01; if (fabs(m_endSpeed - m_startSpeed) < 1e-5) m_endSpeed += kBias; } size_t GpsTrackRenderer::GetAvailablePointsCount() const { size_t pointsCount = 0; for (size_t i = 0; i < m_renderData.size(); i++) pointsCount += m_renderData[i]->m_pointsCount; return pointsCount; } double GpsTrackRenderer::PlacePoints(size_t & cacheIndex, GpsTrackPoint const & start, GpsTrackPoint const & end, double clipStart, double clipEnd, float radius, double diameterMercator, double offset, double trackLengthMercator, double lengthFromStart, bool & gap) { double const kDistanceScalar = 0.65; bool const unknownDistance = (end.m_timestamp - start.m_timestamp) > kUnknownDistanceTime; m2::PointD const delta = end.m_point - start.m_point; double const length = delta.Length(); m2::PointD const dir = delta.Normalize(); double pos = offset; while (pos < length) { if (gap && pos >= clipStart && pos <= clipEnd) { double const dist = pos + diameterMercator * 0.5; dp::Color color = kUnknownDistanceColor; if (!unknownDistance) { double const td = my::clamp(dist / length, 0.0, 1.0); double const speed = max(start.m_speedMPS * (1.0 - td) + end.m_speedMPS * td, 0.0); double const ts = my::clamp((speed - m_startSpeed) / (m_endSpeed - m_startSpeed), 0.0, 1.0); color = InterpolateColors(m_startColor, kMaxSpeedColor, ts); double const ta = my::clamp((lengthFromStart + dist) / trackLengthMercator, 0.0, 1.0); double const alpha = kMinAlpha * (1.0 - ta) + kMaxAlpha * ta; color = dp::Color(color.GetRed(), color.GetGreen(), color.GetBlue(), alpha); } m2::PointD const p = start.m_point + dir * dist; m_handlesCache[cacheIndex].first->SetPoint(m_handlesCache[cacheIndex].second, p, radius, color); m_handlesCache[cacheIndex].second++; if (m_handlesCache[cacheIndex].second >= m_handlesCache[cacheIndex].first->GetPointsCount()) cacheIndex++; if (cacheIndex >= m_handlesCache.size()) { m_dataRequestFn(kAveragePointsCount); m_waitForRenderData = true; return -1.0; } } gap = !gap; pos += (diameterMercator * kDistanceScalar); } return pos - length; } void GpsTrackRenderer::RenderTrack(ScreenBase const & screen, int zoomLevel, ref_ptr<dp::GpuProgramManager> mng, dp::UniformValuesStorage const & commonUniforms) { if (zoomLevel < kMinVisibleZoomLevel) return; if (m_needUpdate) { // Skip rendering if there is no any point. if (m_points.empty()) { m_needUpdate = false; return; } // Check if there are render data. if (m_renderData.empty() && !m_waitForRenderData) { m_dataRequestFn(kAveragePointsCount); m_waitForRenderData = true; } if (m_waitForRenderData) return; m_radius = CalculateRadius(screen); float const diameter = 2.0f * m_radius; float const currentScaleGtoP = 1.0f / screen.GetScale(); double const trackLengthMercator = CalculateTrackLength(); // Update points' positions and colors. ASSERT(!m_renderData.empty(), ()); m_handlesCache.clear(); for (size_t i = 0; i < m_renderData.size(); i++) { ASSERT_EQUAL(m_renderData[i]->m_bucket->GetOverlayHandlesCount(), 1, ()); GpsTrackHandle * handle = static_cast<GpsTrackHandle*>(m_renderData[i]->m_bucket->GetOverlayHandle(0).get()); handle->Clear(); m_handlesCache.push_back(make_pair(handle, 0)); } UpdateSpeedsAndColors(); size_t cacheIndex = 0; double lengthFromStart = 0.0; if (m_points.size() == 1) { m_handlesCache[cacheIndex].first->SetPoint(0, m_points.front().m_point, m_radius, kMaxSpeedColor); m_handlesCache[cacheIndex].second++; } else { bool gap = true; double const diameterMercator = diameter / currentScaleGtoP; double offset = 0.0; for (size_t i = 0; i + 1 < m_points.size(); i++) { // Clip points outside visible rect. m2::PointD p1 = m_points[i].m_point; m2::PointD p2 = m_points[i + 1].m_point; double const dist = (m_points[i + 1].m_point - m_points[i].m_point).Length(); if (!m2::Intersect(screen.ClipRect(), p1, p2)) { lengthFromStart += dist; offset = 0.0; continue; } // Check points equality. if (p1.EqualDxDy(p2, 1e-5)) { lengthFromStart += dist; continue; } // Place points. double const clipStart = (p1 - m_points[i].m_point).Length(); double const clipEnd = (p2 - m_points[i].m_point).Length(); offset = PlacePoints(cacheIndex, m_points[i], m_points[i + 1], clipStart, clipEnd, m_radius, diameterMercator, offset, trackLengthMercator, lengthFromStart, gap); if (offset < 0.0) return; lengthFromStart += dist; } #ifdef SHOW_RAW_POINTS for (size_t i = 0; i < m_points.size(); i++) { m_handlesCache[cacheIndex].first->SetPoint(m_handlesCache[cacheIndex].second, m_points[i].m_point, m_radius * 1.2, dp::Color(0, 0, 255, 255)); m_handlesCache[cacheIndex].second++; if (m_handlesCache[cacheIndex].second >= m_handlesCache[cacheIndex].first->GetPointsCount()) cacheIndex++; if (cacheIndex >= m_handlesCache.size()) { m_dataRequestFn(kAveragePointsCount); m_waitForRenderData = true; return; } } #endif } m_needUpdate = false; } if (m_handlesCache.empty() || m_handlesCache.front().second == 0) return; GLFunctions::glClearDepth(); ASSERT_LESS_OR_EQUAL(m_renderData.size(), m_handlesCache.size(), ()); // Render points. dp::UniformValuesStorage uniforms = commonUniforms; uniforms.SetFloatValue("u_opacity", 1.0f); uniforms.SetFloatValue("u_radiusShift", m_radius * kOutlineRadiusScalar); ref_ptr<dp::GpuProgram> program = mng->GetProgram(gpu::TRACK_POINT_PROGRAM); program->Bind(); ASSERT_GREATER(m_renderData.size(), 0, ()); dp::ApplyState(m_renderData.front()->m_state, program); dp::ApplyUniforms(uniforms, program); for (size_t i = 0; i < m_renderData.size(); i++) if (m_handlesCache[i].second != 0) m_renderData[i]->m_bucket->Render(screen); } void GpsTrackRenderer::Update() { m_needUpdate = true; } void GpsTrackRenderer::Clear() { m_points.clear(); m_needUpdate = true; } } // namespace df <|endoftext|>
<commit_before>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <thread> // NOLINT #include "paddle/fluid/framework/channel.h" #include "paddle/fluid/operators/reader/reader_op_registry.h" namespace paddle { namespace operators { namespace reader { // 'Double buffer' means we shall maintain two batches of input data at the same // time. So the kCacheSize shoul be at least 2. static constexpr size_t kCacheSize = 2; // There will be two bacthes out of the channel during training: // 1. the one waiting to be sent to the channel // 2. the one just be received from the channel, which is also being used by // subsequent operators. // So the channel size should be kChacheSize - 2 static constexpr size_t kChannelSize = 0; // kCacheSize - 2 class DoubleBufferReader : public framework::DecoratedReader { public: explicit DoubleBufferReader( ReaderBase* reader, platform::Place target_place = platform::CPUPlace()) : DecoratedReader(reader), place_(target_place) { cpu_tensor_cache_.resize(kCacheSize); gpu_tensor_cache_.resize(kCacheSize); #ifdef PADDLE_WITH_CUDA if (platform::is_gpu_place(place_)) { for (size_t i = 0; i < kCacheSize; ++i) { ctxs_.emplace_back(new platform::CUDADeviceContext( boost::get<platform::CUDAPlace>(place_))); } } #endif StartPrefetcher(); } void ReadNext(std::vector<framework::LoDTensor>* out) override; void ReInit() override; ~DoubleBufferReader() { EndPrefetcher(); } private: bool HasNext() const; void StartPrefetcher() { channel_ = framework::MakeChannel<size_t>(kChannelSize); prefetcher_ = std::thread([this] { PrefetchThreadFunc(); }); } void EndPrefetcher() { channel_->Close(); if (prefetcher_.joinable()) { prefetcher_.join(); } delete channel_; channel_ = nullptr; } void PrefetchThreadFunc(); std::thread prefetcher_; framework::Channel<size_t>* channel_; platform::Place place_; std::vector<std::vector<framework::LoDTensor>> cpu_tensor_cache_; std::vector<std::vector<framework::LoDTensor>> gpu_tensor_cache_; std::vector<std::unique_ptr<platform::DeviceContext>> ctxs_; }; class CreateDoubleBufferReaderOp : public framework::OperatorBase { public: using framework::OperatorBase::OperatorBase; private: void RunImpl(const framework::Scope& scope, const platform::Place& dev_place) const override { auto* out = scope.FindVar(Output("Out")) ->template GetMutable<framework::ReaderHolder>(); if (out->Get() != nullptr) { return; } const auto& underlying_reader = scope.FindVar(Input("UnderlyingReader")) ->Get<framework::ReaderHolder>(); auto place_str = Attr<std::string>("place"); platform::Place place; if (place_str == "AUTO") { place = dev_place; } else if (place_str == "CPU") { place = platform::CPUPlace(); } else { std::istringstream sin(place_str); sin.seekg(std::string("CUDA:").size(), std::ios::beg); size_t num; sin >> num; place = platform::CUDAPlace(static_cast<int>(num)); } out->Reset(new DoubleBufferReader(underlying_reader.Get(), place)); } }; class CreateDoubleBufferReaderOpMaker : public DecoratedReaderMakerBase { public: CreateDoubleBufferReaderOpMaker(OpProto* op_proto, OpAttrChecker* op_checker) : DecoratedReaderMakerBase(op_proto, op_checker) { AddComment(R"DOC( CreateDoubleBufferReader Operator A double buffer reader takes another reader as its 'underlying reader'. It launches another thread to execute the 'underlying reader' asynchronously, which prevents reading process from blocking subsequent training. )DOC"); std::unordered_set<std::string> enum_range; constexpr size_t kMaxCUDADevs = 128; for (size_t i = 0; i < kMaxCUDADevs; ++i) { enum_range.insert(string::Sprintf("CUDA:%d", i)); } enum_range.insert("CPU"); enum_range.insert("AUTO"); AddAttr<std::string>("place", "The double buffer place") .SetDefault("AUTO") .InEnum({enum_range}); } }; void DoubleBufferReader::ReadNext(std::vector<framework::LoDTensor>* out) { out->clear(); if (HasNext()) { size_t cached_tensor_id; channel_->Receive(&cached_tensor_id); if (platform::is_gpu_place(place_)) { *out = gpu_tensor_cache_[cached_tensor_id]; ctxs_[cached_tensor_id]->Wait(); } else { // CPU place *out = cpu_tensor_cache_[cached_tensor_id]; } } } void DoubleBufferReader::ReInit() { reader_->ReInit(); EndPrefetcher(); StartPrefetcher(); } bool DoubleBufferReader::HasNext() const { while (!channel_->IsClosed() && !channel_->CanReceive()) { } return channel_->CanReceive(); } void DoubleBufferReader::PrefetchThreadFunc() { VLOG(5) << "A new prefetch thread starts."; size_t cached_tensor_id = 0; while (true) { auto& cpu_batch = cpu_tensor_cache_[cached_tensor_id]; reader_->ReadNext(&cpu_batch); if (cpu_batch.empty()) { // The underlying reader have no next data. break; } if (platform::is_gpu_place(place_)) { auto& gpu_batch = gpu_tensor_cache_[cached_tensor_id]; auto* gpu_ctx = ctxs_[cached_tensor_id].get(); gpu_batch.resize(cpu_batch.size()); for (size_t i = 0; i < cpu_batch.size(); ++i) { framework::TensorCopy(cpu_batch[i], place_, *gpu_ctx, &gpu_batch[i], true); gpu_batch[i].set_lod(cpu_batch[i].lod()); } } try { size_t tmp = cached_tensor_id; channel_->Send(&tmp); } catch (paddle::platform::EnforceNotMet e) { VLOG(5) << "WARNING: The double buffer channel has been closed. The " "prefetch thread will terminate."; break; } ++cached_tensor_id; cached_tensor_id %= kCacheSize; } channel_->Close(); VLOG(5) << "Prefetch thread terminates."; } } // namespace reader } // namespace operators } // namespace paddle namespace ops = paddle::operators::reader; REGISTER_DECORATED_READER_OPERATOR(create_double_buffer_reader, ops::CreateDoubleBufferReaderOp, ops::CreateDoubleBufferReaderOpMaker); <commit_msg>Replace Channel in DoubleBufferReader with BlockingQueue<commit_after>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <thread> // NOLINT #include "paddle/fluid/operators/reader/blocking_queue.h" #include "paddle/fluid/operators/reader/reader_op_registry.h" namespace paddle { namespace operators { namespace reader { // 'Double buffer' means we shall maintain two batches of input data at the same // time. So the kCacheSize shoul be at least 2. static constexpr size_t kCacheSize = 3; // There will be two bacthes out of the channel during training: // 1. the one waiting to be sent to the channel // 2. the one just be received from the channel, which is also being used by // subsequent operators. // So the channel size should be kChacheSize - 2 static constexpr size_t kChannelSize = 1; // kCacheSize - 2 class DoubleBufferReader : public framework::DecoratedReader { public: explicit DoubleBufferReader( ReaderBase* reader, platform::Place target_place = platform::CPUPlace()) : DecoratedReader(reader), place_(target_place) { cpu_tensor_cache_.resize(kCacheSize); gpu_tensor_cache_.resize(kCacheSize); #ifdef PADDLE_WITH_CUDA if (platform::is_gpu_place(place_)) { for (size_t i = 0; i < kCacheSize; ++i) { ctxs_.emplace_back(new platform::CUDADeviceContext( boost::get<platform::CUDAPlace>(place_))); } } #endif StartPrefetcher(); } void ReadNext(std::vector<framework::LoDTensor>* out) override; void ReInit() override; ~DoubleBufferReader() { EndPrefetcher(); } private: bool HasNext() const; void StartPrefetcher() { channel_ = new reader::BlockingQueue<size_t>(kChannelSize); prefetcher_ = std::thread([this] { PrefetchThreadFunc(); }); } void EndPrefetcher() { channel_->Close(); if (prefetcher_.joinable()) { prefetcher_.join(); } delete channel_; channel_ = nullptr; } void PrefetchThreadFunc(); std::thread prefetcher_; reader::BlockingQueue<size_t>* channel_; platform::Place place_; std::vector<std::vector<framework::LoDTensor>> cpu_tensor_cache_; std::vector<std::vector<framework::LoDTensor>> gpu_tensor_cache_; std::vector<std::unique_ptr<platform::DeviceContext>> ctxs_; }; class CreateDoubleBufferReaderOp : public framework::OperatorBase { public: using framework::OperatorBase::OperatorBase; private: void RunImpl(const framework::Scope& scope, const platform::Place& dev_place) const override { auto* out = scope.FindVar(Output("Out")) ->template GetMutable<framework::ReaderHolder>(); if (out->Get() != nullptr) { return; } const auto& underlying_reader = scope.FindVar(Input("UnderlyingReader")) ->Get<framework::ReaderHolder>(); auto place_str = Attr<std::string>("place"); platform::Place place; if (place_str == "AUTO") { place = dev_place; } else if (place_str == "CPU") { place = platform::CPUPlace(); } else { std::istringstream sin(place_str); sin.seekg(std::string("CUDA:").size(), std::ios::beg); size_t num; sin >> num; place = platform::CUDAPlace(static_cast<int>(num)); } out->Reset(new DoubleBufferReader(underlying_reader.Get(), place)); } }; class CreateDoubleBufferReaderOpMaker : public DecoratedReaderMakerBase { public: CreateDoubleBufferReaderOpMaker(OpProto* op_proto, OpAttrChecker* op_checker) : DecoratedReaderMakerBase(op_proto, op_checker) { AddComment(R"DOC( CreateDoubleBufferReader Operator A double buffer reader takes another reader as its 'underlying reader'. It launches another thread to execute the 'underlying reader' asynchronously, which prevents reading process from blocking subsequent training. )DOC"); std::unordered_set<std::string> enum_range; constexpr size_t kMaxCUDADevs = 128; for (size_t i = 0; i < kMaxCUDADevs; ++i) { enum_range.insert(string::Sprintf("CUDA:%d", i)); } enum_range.insert("CPU"); enum_range.insert("AUTO"); AddAttr<std::string>("place", "The double buffer place") .SetDefault("AUTO") .InEnum({enum_range}); } }; void DoubleBufferReader::ReadNext(std::vector<framework::LoDTensor>* out) { out->clear(); if (HasNext()) { size_t cached_tensor_id; channel_->Receive(&cached_tensor_id); if (platform::is_gpu_place(place_)) { *out = gpu_tensor_cache_[cached_tensor_id]; ctxs_[cached_tensor_id]->Wait(); } else { // CPU place *out = cpu_tensor_cache_[cached_tensor_id]; } } } void DoubleBufferReader::ReInit() { reader_->ReInit(); EndPrefetcher(); StartPrefetcher(); } bool DoubleBufferReader::HasNext() const { while (!channel_->IsClosed() && !channel_->CanReceive()) { } return channel_->CanReceive(); } void DoubleBufferReader::PrefetchThreadFunc() { VLOG(5) << "A new prefetch thread starts."; size_t cached_tensor_id = 0; while (true) { auto& cpu_batch = cpu_tensor_cache_[cached_tensor_id]; reader_->ReadNext(&cpu_batch); if (cpu_batch.empty()) { // The underlying reader have no next data. break; } if (platform::is_gpu_place(place_)) { auto& gpu_batch = gpu_tensor_cache_[cached_tensor_id]; auto* gpu_ctx = ctxs_[cached_tensor_id].get(); gpu_batch.resize(cpu_batch.size()); for (size_t i = 0; i < cpu_batch.size(); ++i) { framework::TensorCopy(cpu_batch[i], place_, *gpu_ctx, &gpu_batch[i], true); gpu_batch[i].set_lod(cpu_batch[i].lod()); } } if (!channel_->Send(cached_tensor_id)) { VLOG(5) << "WARNING: The double buffer channel has been closed. The " "prefetch thread will terminate."; break; } ++cached_tensor_id; cached_tensor_id %= kCacheSize; } channel_->Close(); VLOG(5) << "Prefetch thread terminates."; } } // namespace reader } // namespace operators } // namespace paddle namespace ops = paddle::operators::reader; REGISTER_DECORATED_READER_OPERATOR(create_double_buffer_reader, ops::CreateDoubleBufferReaderOp, ops::CreateDoubleBufferReaderOpMaker); <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: Pattern.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2004-04-02 10:55:08 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _FORMS_PATTERN_HXX_ #include "Pattern.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif //......................................................................... namespace frm { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdb; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::com::sun::star::form; using namespace ::com::sun::star::awt; using namespace ::com::sun::star::io; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::util; //================================================================== // OPatternControl //================================================================== //------------------------------------------------------------------ OPatternControl::OPatternControl(const Reference<XMultiServiceFactory>& _rxFactory) :OBoundControl(_rxFactory, VCL_CONTROL_PATTERNFIELD) { } //------------------------------------------------------------------ InterfaceRef SAL_CALL OPatternControl_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory) { return *(new OPatternControl(_rxFactory)); } //------------------------------------------------------------------------------ Sequence<Type> OPatternControl::_getTypes() { return OBoundControl::_getTypes(); } //------------------------------------------------------------------------------ StringSequence OPatternControl::getSupportedServiceNames() throw() { StringSequence aSupported = OBoundControl::getSupportedServiceNames(); aSupported.realloc(aSupported.getLength() + 1); ::rtl::OUString*pArray = aSupported.getArray(); pArray[aSupported.getLength()-1] = FRM_SUN_CONTROL_PATTERNFIELD; return aSupported; } //================================================================== // OPatternModel //================================================================== //------------------------------------------------------------------ InterfaceRef SAL_CALL OPatternModel_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory) { return *(new OPatternModel(_rxFactory)); } //------------------------------------------------------------------------------ Sequence<Type> OPatternModel::_getTypes() { return OEditBaseModel::_getTypes(); } //------------------------------------------------------------------ DBG_NAME( OPatternModel ) //------------------------------------------------------------------ OPatternModel::OPatternModel(const Reference<XMultiServiceFactory>& _rxFactory) :OEditBaseModel( _rxFactory, VCL_CONTROLMODEL_PATTERNFIELD, FRM_CONTROL_PATTERNFIELD, sal_False, sal_False ) // use the old control name for compytibility reasons { DBG_CTOR( OPatternModel, NULL ); m_nClassId = FormComponentType::PATTERNFIELD; initValueProperty( PROPERTY_TEXT, PROPERTY_ID_TEXT ); } //------------------------------------------------------------------ OPatternModel::OPatternModel( const OPatternModel* _pOriginal, const Reference<XMultiServiceFactory>& _rxFactory ) :OEditBaseModel( _pOriginal, _rxFactory ) { DBG_CTOR( OPatternModel, NULL ); } //------------------------------------------------------------------ OPatternModel::~OPatternModel() { DBG_DTOR( OPatternModel, NULL ); } // XCloneable //------------------------------------------------------------------------------ IMPLEMENT_DEFAULT_CLONING( OPatternModel ) // XServiceInfo //------------------------------------------------------------------------------ StringSequence SAL_CALL OPatternModel::getSupportedServiceNames() throw() { StringSequence aSupported = OBoundControlModel::getSupportedServiceNames(); aSupported.realloc(aSupported.getLength() + 2); ::rtl::OUString*pArray = aSupported.getArray(); pArray[aSupported.getLength()-2] = FRM_SUN_COMPONENT_DATABASE_PATTERNFIELD; pArray[aSupported.getLength()-1] = FRM_SUN_COMPONENT_PATTERNFIELD; return aSupported; } //------------------------------------------------------------------------------ Reference<XPropertySetInfo> SAL_CALL OPatternModel::getPropertySetInfo() throw( RuntimeException ) { Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) ); return xInfo; } //------------------------------------------------------------------------------ void OPatternModel::fillProperties( Sequence< Property >& _rProps, Sequence< Property >& _rAggregateProps ) const { BEGIN_DESCRIBE_PROPERTIES( 4, OEditBaseModel ) DECL_PROP2(DEFAULT_TEXT, ::rtl::OUString, BOUND, MAYBEDEFAULT); DECL_BOOL_PROP1(EMPTY_IS_NULL, BOUND); DECL_PROP1(TABINDEX, sal_Int16, BOUND); DECL_PROP2(FILTERPROPOSAL, sal_Bool, BOUND, MAYBEDEFAULT); END_DESCRIBE_PROPERTIES(); } //------------------------------------------------------------------------------ ::cppu::IPropertyArrayHelper& OPatternModel::getInfoHelper() { return *const_cast<OPatternModel*>(this)->getArrayHelper(); } //------------------------------------------------------------------------------ ::rtl::OUString SAL_CALL OPatternModel::getServiceName() throw ( ::com::sun::star::uno::RuntimeException) { return FRM_COMPONENT_PATTERNFIELD; // old (non-sun) name for compatibility ! } //------------------------------------------------------------------------------ sal_Bool OPatternModel::commitControlValueToDbColumn( bool _bPostReset ) { ::rtl::OUString sNewValue; m_xAggregateFastSet->getFastPropertyValue( getValuePropertyAggHandle() ) >>= sNewValue; if ( sNewValue != m_aSaveValue ) { if ( !sNewValue.getLength() && !m_bRequired && m_bEmptyIsNull ) m_xColumnUpdate->updateNull(); else { try { m_xColumnUpdate->updateString( sNewValue ); } catch(Exception&) { return sal_False; } } m_aSaveValue = sNewValue; } return sal_True; } // XPropertyChangeListener //------------------------------------------------------------------------------ Any OPatternModel::translateDbColumnToControlValue() { m_aSaveValue = m_xColumn->getString(); return makeAny( m_aSaveValue ); } // XReset //------------------------------------------------------------------------------ Any OPatternModel::getDefaultForReset() const { return makeAny( m_aDefaultText ); } //......................................................................... } // namespace frm //......................................................................... <commit_msg>INTEGRATION: CWS dba09 (1.9.44); FILE MERGED 2004/04/27 06:14:36 fs 1.9.44.2: RESYNC: (1.9-1.10); FILE MERGED 2004/03/17 11:51:07 fs 1.9.44.1: #92831# at runtime, don't use 'stardiv.one.form.control.*' service names - translate when writing old (binary) format<commit_after>/************************************************************************* * * $RCSfile: Pattern.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: hr $ $Date: 2004-05-10 12:46:56 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _FORMS_PATTERN_HXX_ #include "Pattern.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif //......................................................................... namespace frm { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdb; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::com::sun::star::form; using namespace ::com::sun::star::awt; using namespace ::com::sun::star::io; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::util; //================================================================== // OPatternControl //================================================================== //------------------------------------------------------------------ OPatternControl::OPatternControl(const Reference<XMultiServiceFactory>& _rxFactory) :OBoundControl(_rxFactory, VCL_CONTROL_PATTERNFIELD) { } //------------------------------------------------------------------ InterfaceRef SAL_CALL OPatternControl_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory) { return *(new OPatternControl(_rxFactory)); } //------------------------------------------------------------------------------ Sequence<Type> OPatternControl::_getTypes() { return OBoundControl::_getTypes(); } //------------------------------------------------------------------------------ StringSequence OPatternControl::getSupportedServiceNames() throw() { StringSequence aSupported = OBoundControl::getSupportedServiceNames(); aSupported.realloc(aSupported.getLength() + 1); ::rtl::OUString*pArray = aSupported.getArray(); pArray[aSupported.getLength()-1] = FRM_SUN_CONTROL_PATTERNFIELD; return aSupported; } //================================================================== // OPatternModel //================================================================== //------------------------------------------------------------------ InterfaceRef SAL_CALL OPatternModel_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory) { return *(new OPatternModel(_rxFactory)); } //------------------------------------------------------------------------------ Sequence<Type> OPatternModel::_getTypes() { return OEditBaseModel::_getTypes(); } //------------------------------------------------------------------ DBG_NAME( OPatternModel ) //------------------------------------------------------------------ OPatternModel::OPatternModel(const Reference<XMultiServiceFactory>& _rxFactory) :OEditBaseModel( _rxFactory, VCL_CONTROLMODEL_PATTERNFIELD, FRM_SUN_CONTROL_PATTERNFIELD, sal_False, sal_False ) // use the old control name for compytibility reasons { DBG_CTOR( OPatternModel, NULL ); m_nClassId = FormComponentType::PATTERNFIELD; initValueProperty( PROPERTY_TEXT, PROPERTY_ID_TEXT ); } //------------------------------------------------------------------ OPatternModel::OPatternModel( const OPatternModel* _pOriginal, const Reference<XMultiServiceFactory>& _rxFactory ) :OEditBaseModel( _pOriginal, _rxFactory ) { DBG_CTOR( OPatternModel, NULL ); } //------------------------------------------------------------------ OPatternModel::~OPatternModel() { DBG_DTOR( OPatternModel, NULL ); } // XCloneable //------------------------------------------------------------------------------ IMPLEMENT_DEFAULT_CLONING( OPatternModel ) // XServiceInfo //------------------------------------------------------------------------------ StringSequence SAL_CALL OPatternModel::getSupportedServiceNames() throw() { StringSequence aSupported = OBoundControlModel::getSupportedServiceNames(); aSupported.realloc(aSupported.getLength() + 2); ::rtl::OUString*pArray = aSupported.getArray(); pArray[aSupported.getLength()-2] = FRM_SUN_COMPONENT_DATABASE_PATTERNFIELD; pArray[aSupported.getLength()-1] = FRM_SUN_COMPONENT_PATTERNFIELD; return aSupported; } //------------------------------------------------------------------------------ Reference<XPropertySetInfo> SAL_CALL OPatternModel::getPropertySetInfo() throw( RuntimeException ) { Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) ); return xInfo; } //------------------------------------------------------------------------------ void OPatternModel::fillProperties( Sequence< Property >& _rProps, Sequence< Property >& _rAggregateProps ) const { BEGIN_DESCRIBE_PROPERTIES( 4, OEditBaseModel ) DECL_PROP2(DEFAULT_TEXT, ::rtl::OUString, BOUND, MAYBEDEFAULT); DECL_BOOL_PROP1(EMPTY_IS_NULL, BOUND); DECL_PROP1(TABINDEX, sal_Int16, BOUND); DECL_PROP2(FILTERPROPOSAL, sal_Bool, BOUND, MAYBEDEFAULT); END_DESCRIBE_PROPERTIES(); } //------------------------------------------------------------------------------ ::cppu::IPropertyArrayHelper& OPatternModel::getInfoHelper() { return *const_cast<OPatternModel*>(this)->getArrayHelper(); } //------------------------------------------------------------------------------ ::rtl::OUString SAL_CALL OPatternModel::getServiceName() throw ( ::com::sun::star::uno::RuntimeException) { return FRM_COMPONENT_PATTERNFIELD; // old (non-sun) name for compatibility ! } //------------------------------------------------------------------------------ sal_Bool OPatternModel::commitControlValueToDbColumn( bool _bPostReset ) { ::rtl::OUString sNewValue; m_xAggregateFastSet->getFastPropertyValue( getValuePropertyAggHandle() ) >>= sNewValue; if ( sNewValue != m_aSaveValue ) { if ( !sNewValue.getLength() && !m_bRequired && m_bEmptyIsNull ) m_xColumnUpdate->updateNull(); else { try { m_xColumnUpdate->updateString( sNewValue ); } catch(Exception&) { return sal_False; } } m_aSaveValue = sNewValue; } return sal_True; } // XPropertyChangeListener //------------------------------------------------------------------------------ Any OPatternModel::translateDbColumnToControlValue() { m_aSaveValue = m_xColumn->getString(); return makeAny( m_aSaveValue ); } // XReset //------------------------------------------------------------------------------ Any OPatternModel::getDefaultForReset() const { return makeAny( m_aDefaultText ); } //......................................................................... } // namespace frm //......................................................................... <|endoftext|>
<commit_before>#include "cache_hash.hpp" #include "os.hpp" #include "compiler.hpp" #include <stdio.h> Error get_compiler_id(Buf **result) { static Buf saved_compiler_id = BUF_INIT; if (saved_compiler_id.list.length != 0) { *result = &saved_compiler_id; return ErrorNone; } Error err; Buf *manifest_dir = buf_alloc(); os_path_join(get_global_cache_dir(), buf_create_from_str("exe"), manifest_dir); CacheHash cache_hash; CacheHash *ch = &cache_hash; cache_init(ch, manifest_dir); Buf self_exe_path = BUF_INIT; if ((err = os_self_exe_path(&self_exe_path))) return err; cache_file(ch, &self_exe_path); buf_resize(&saved_compiler_id, 0); if ((err = cache_hit(ch, &saved_compiler_id))) { if (err != ErrorInvalidFormat) return err; } if (buf_len(&saved_compiler_id) != 0) { cache_release(ch); *result = &saved_compiler_id; return ErrorNone; } ZigList<Buf *> lib_paths = {}; if ((err = os_self_exe_shared_libs(lib_paths))) return err; for (size_t i = 0; i < lib_paths.length; i += 1) { Buf *lib_path = lib_paths.at(i); if ((err = cache_add_file(ch, lib_path))) return err; } if ((err = cache_final(ch, &saved_compiler_id))) return err; cache_release(ch); *result = &saved_compiler_id; return ErrorNone; } static bool test_zig_install_prefix(Buf *test_path, Buf *out_zig_lib_dir) { { Buf *test_zig_dir = buf_sprintf("%s" OS_SEP "lib" OS_SEP "zig", buf_ptr(test_path)); Buf *test_index_file = buf_sprintf("%s" OS_SEP "std" OS_SEP "std.zig", buf_ptr(test_zig_dir)); int err; bool exists; if ((err = os_file_exists(test_index_file, &exists))) { exists = false; } if (exists) { buf_init_from_buf(out_zig_lib_dir, test_zig_dir); return true; } } // Also try without "zig" { Buf *test_zig_dir = buf_sprintf("%s" OS_SEP "lib", buf_ptr(test_path)); Buf *test_index_file = buf_sprintf("%s" OS_SEP "std" OS_SEP "std.zig", buf_ptr(test_zig_dir)); int err; bool exists; if ((err = os_file_exists(test_index_file, &exists))) { exists = false; } if (exists) { buf_init_from_buf(out_zig_lib_dir, test_zig_dir); return true; } } return false; } static int find_zig_lib_dir(Buf *out_path) { int err; Buf self_exe_path = BUF_INIT; buf_resize(&self_exe_path, 0); if (!(err = os_self_exe_path(&self_exe_path))) { Buf *cur_path = &self_exe_path; for (;;) { Buf *test_dir = buf_alloc(); os_path_dirname(cur_path, test_dir); if (buf_eql_buf(test_dir, cur_path)) { break; } if (test_zig_install_prefix(test_dir, out_path)) { return 0; } cur_path = test_dir; } } return ErrorFileNotFound; } Buf *get_zig_lib_dir(void) { static Buf saved_lib_dir = BUF_INIT; if (saved_lib_dir.list.length != 0) return &saved_lib_dir; buf_resize(&saved_lib_dir, 0); int err; if ((err = find_zig_lib_dir(&saved_lib_dir))) { fprintf(stderr, "Unable to find zig lib directory\n"); exit(EXIT_FAILURE); } return &saved_lib_dir; } Buf *get_zig_std_dir(Buf *zig_lib_dir) { static Buf saved_std_dir = BUF_INIT; if (saved_std_dir.list.length != 0) return &saved_std_dir; buf_resize(&saved_std_dir, 0); os_path_join(zig_lib_dir, buf_create_from_str("std"), &saved_std_dir); return &saved_std_dir; } Buf *get_zig_special_dir(Buf *zig_lib_dir) { static Buf saved_special_dir = BUF_INIT; if (saved_special_dir.list.length != 0) return &saved_special_dir; buf_resize(&saved_special_dir, 0); os_path_join(get_zig_std_dir(zig_lib_dir), buf_sprintf("special"), &saved_special_dir); return &saved_special_dir; } Buf *get_global_cache_dir(void) { static Buf saved_global_cache_dir = BUF_INIT; if (saved_global_cache_dir.list.length != 0) return &saved_global_cache_dir; buf_resize(&saved_global_cache_dir, 0); Buf app_data_dir = BUF_INIT; Error err; if ((err = os_get_app_data_dir(&app_data_dir, "zig"))) { fprintf(stderr, "Unable to get application data dir: %s\n", err_str(err)); exit(1); } os_path_join(&app_data_dir, buf_create_from_str("stage1"), &saved_global_cache_dir); buf_deinit(&app_data_dir); return &saved_global_cache_dir; } FileExt classify_file_ext(const char *filename_ptr, size_t filename_len) { if (mem_ends_with_str(filename_ptr, filename_len, ".c")) { return FileExtC; } else if (mem_ends_with_str(filename_ptr, filename_len, ".C") || mem_ends_with_str(filename_ptr, filename_len, ".cc") || mem_ends_with_str(filename_ptr, filename_len, ".cpp") || mem_ends_with_str(filename_ptr, filename_len, ".cxx")) { return FileExtCpp; } else if (mem_ends_with_str(filename_ptr, filename_len, ".ll")) { return FileExtLLVMIr; } else if (mem_ends_with_str(filename_ptr, filename_len, ".bc")) { return FileExtLLVMBitCode; } else if (mem_ends_with_str(filename_ptr, filename_len, ".s") || mem_ends_with_str(filename_ptr, filename_len, ".S")) { return FileExtAsm; } // TODO look for .so, .so.X, .so.X.Y, .so.X.Y.Z return FileExtUnknown; } <commit_msg>On darwin, only add the self exe to the cache hash for compiler id (#5880)<commit_after>#include "cache_hash.hpp" #include "os.hpp" #include "compiler.hpp" #include <stdio.h> Error get_compiler_id(Buf **result) { static Buf saved_compiler_id = BUF_INIT; if (saved_compiler_id.list.length != 0) { *result = &saved_compiler_id; return ErrorNone; } Error err; Buf *manifest_dir = buf_alloc(); os_path_join(get_global_cache_dir(), buf_create_from_str("exe"), manifest_dir); CacheHash cache_hash; CacheHash *ch = &cache_hash; cache_init(ch, manifest_dir); Buf self_exe_path = BUF_INIT; if ((err = os_self_exe_path(&self_exe_path))) return err; cache_file(ch, &self_exe_path); buf_resize(&saved_compiler_id, 0); if ((err = cache_hit(ch, &saved_compiler_id))) { if (err != ErrorInvalidFormat) return err; } if (buf_len(&saved_compiler_id) != 0) { cache_release(ch); *result = &saved_compiler_id; return ErrorNone; } ZigList<Buf *> lib_paths = {}; if ((err = os_self_exe_shared_libs(lib_paths))) return err; #if defined(ZIG_OS_DARWIN) // only add the self exe path on mac os Buf *lib_path = lib_paths.at(0); if ((err = cache_add_file(ch, lib_path))) return err; #else for (size_t i = 0; i < lib_paths.length; i += 1) { Buf *lib_path = lib_paths.at(i); if ((err = cache_add_file(ch, lib_path))) return err; } #endif if ((err = cache_final(ch, &saved_compiler_id))) return err; cache_release(ch); *result = &saved_compiler_id; return ErrorNone; } static bool test_zig_install_prefix(Buf *test_path, Buf *out_zig_lib_dir) { { Buf *test_zig_dir = buf_sprintf("%s" OS_SEP "lib" OS_SEP "zig", buf_ptr(test_path)); Buf *test_index_file = buf_sprintf("%s" OS_SEP "std" OS_SEP "std.zig", buf_ptr(test_zig_dir)); int err; bool exists; if ((err = os_file_exists(test_index_file, &exists))) { exists = false; } if (exists) { buf_init_from_buf(out_zig_lib_dir, test_zig_dir); return true; } } // Also try without "zig" { Buf *test_zig_dir = buf_sprintf("%s" OS_SEP "lib", buf_ptr(test_path)); Buf *test_index_file = buf_sprintf("%s" OS_SEP "std" OS_SEP "std.zig", buf_ptr(test_zig_dir)); int err; bool exists; if ((err = os_file_exists(test_index_file, &exists))) { exists = false; } if (exists) { buf_init_from_buf(out_zig_lib_dir, test_zig_dir); return true; } } return false; } static int find_zig_lib_dir(Buf *out_path) { int err; Buf self_exe_path = BUF_INIT; buf_resize(&self_exe_path, 0); if (!(err = os_self_exe_path(&self_exe_path))) { Buf *cur_path = &self_exe_path; for (;;) { Buf *test_dir = buf_alloc(); os_path_dirname(cur_path, test_dir); if (buf_eql_buf(test_dir, cur_path)) { break; } if (test_zig_install_prefix(test_dir, out_path)) { return 0; } cur_path = test_dir; } } return ErrorFileNotFound; } Buf *get_zig_lib_dir(void) { static Buf saved_lib_dir = BUF_INIT; if (saved_lib_dir.list.length != 0) return &saved_lib_dir; buf_resize(&saved_lib_dir, 0); int err; if ((err = find_zig_lib_dir(&saved_lib_dir))) { fprintf(stderr, "Unable to find zig lib directory\n"); exit(EXIT_FAILURE); } return &saved_lib_dir; } Buf *get_zig_std_dir(Buf *zig_lib_dir) { static Buf saved_std_dir = BUF_INIT; if (saved_std_dir.list.length != 0) return &saved_std_dir; buf_resize(&saved_std_dir, 0); os_path_join(zig_lib_dir, buf_create_from_str("std"), &saved_std_dir); return &saved_std_dir; } Buf *get_zig_special_dir(Buf *zig_lib_dir) { static Buf saved_special_dir = BUF_INIT; if (saved_special_dir.list.length != 0) return &saved_special_dir; buf_resize(&saved_special_dir, 0); os_path_join(get_zig_std_dir(zig_lib_dir), buf_sprintf("special"), &saved_special_dir); return &saved_special_dir; } Buf *get_global_cache_dir(void) { static Buf saved_global_cache_dir = BUF_INIT; if (saved_global_cache_dir.list.length != 0) return &saved_global_cache_dir; buf_resize(&saved_global_cache_dir, 0); Buf app_data_dir = BUF_INIT; Error err; if ((err = os_get_app_data_dir(&app_data_dir, "zig"))) { fprintf(stderr, "Unable to get application data dir: %s\n", err_str(err)); exit(1); } os_path_join(&app_data_dir, buf_create_from_str("stage1"), &saved_global_cache_dir); buf_deinit(&app_data_dir); return &saved_global_cache_dir; } FileExt classify_file_ext(const char *filename_ptr, size_t filename_len) { if (mem_ends_with_str(filename_ptr, filename_len, ".c")) { return FileExtC; } else if (mem_ends_with_str(filename_ptr, filename_len, ".C") || mem_ends_with_str(filename_ptr, filename_len, ".cc") || mem_ends_with_str(filename_ptr, filename_len, ".cpp") || mem_ends_with_str(filename_ptr, filename_len, ".cxx")) { return FileExtCpp; } else if (mem_ends_with_str(filename_ptr, filename_len, ".ll")) { return FileExtLLVMIr; } else if (mem_ends_with_str(filename_ptr, filename_len, ".bc")) { return FileExtLLVMBitCode; } else if (mem_ends_with_str(filename_ptr, filename_len, ".s") || mem_ends_with_str(filename_ptr, filename_len, ".S")) { return FileExtAsm; } // TODO look for .so, .so.X, .so.X.Y, .so.X.Y.Z return FileExtUnknown; } <|endoftext|>
<commit_before>/* * File: BackpropeagationLearner.cpp * Author: janvojt * * Created on July 13, 2014, 12:10 AM */ #include "BackpropagationLearner.h" #include "Network.h" #include "LabeledDataset.h" #include <cstring> #include <string> #include <stdexcept> #include "log/LoggerFactory.h" #include "log4cpp/Category.hh" BackpropagationLearner::BackpropagationLearner(Network *network) { this->network = network; learningRate = 1; epochCounter = 0; epochLimit = 1000000; targetMse = .0001; errorTotal = std::numeric_limits<double>::infinity(); allocateCache(); } BackpropagationLearner::BackpropagationLearner(const BackpropagationLearner &orig) { } BackpropagationLearner::~BackpropagationLearner() { } void BackpropagationLearner::allocateCache() { weightDiffs = new double[network->getWeightsOffset(network->getConfiguration()->getLayers())]; localGradients = new double[network->getAllNeurons()]; useBias = network->getConfiguration()->getBias(); biasDiff = useBias ? new double[network->getAllNeurons()] : NULL; } void BackpropagationLearner::train(LabeledDataset *dataset) { double mse; LOG()->info("Started training with limits of %d epochs and target MSE of %f.", epochLimit, targetMse); do { epochCounter++; LOG()->debug("Starting epoch %d.", epochCounter); dataset->reset(); int datasetSize = 0; mse = 0; while (dataset->hasNext()) { datasetSize++; double *pattern = dataset->next(); double *expOutput = pattern + dataset->getInputDimension(); LOG()->debug("Learning pattern [%f, %f] -> [%f].", pattern[0], pattern[1], expOutput[0]); doForwardPhase(pattern); doBackwardPhase(expOutput); mse += errorComputer->compute(network, expOutput); } mse = mse / datasetSize; LOG()->debug("Finished epoch %d with MSE: %f.", epochCounter, mse); } while (mse > targetMse && epochCounter < epochLimit); if (mse <= targetMse) { LOG()->info("Training successful after %d epochs with MSE of %f.", epochCounter, mse); } else { LOG()->info("Training interrupted after %d epochs with MSE of %f.", epochCounter, mse); } } void BackpropagationLearner::doForwardPhase(double *input) { network->setInput(input); network->run(); } void BackpropagationLearner::doBackwardPhase(double *expectedOutput) { computeOutputGradients(expectedOutput); computeWeightDifferentials(); adjustWeights(); if (network->getConfiguration()->getBias()) { adjustBias(); } } void BackpropagationLearner::computeOutputGradients(double *expectedOutput) { int on = network->getOutputNeurons(); int noLayers = network->getConfiguration()->getLayers(); double *localGradient = localGradients + network->getInputOffset(noLayers-1); double *output = network->getOutput(); void (*daf) (double*,double*,int) = network->getConfiguration()->dActivationFnc; // compute local gradients double *dv = new double[network->getOutputNeurons()]; daf(network->getInput() + network->getInputOffset(noLayers-1), dv, on); for (int i = 0; i<on; i++) { localGradient[i] = (output[i] - expectedOutput[i]) * dv[i]; } } void BackpropagationLearner::computeWeightDifferentials() { int noLayers = network->getConfiguration()->getLayers(); void (*daf) (double*,double*,int) = network->getConfiguration()->dActivationFnc; for (int l = noLayers-1; l>0; l--) { // INITIALIZE HELPER VARIABLES int thisInputIdx = network->getInputOffset(l-1); double *thisLocalGradient = localGradients + thisInputIdx; int nextInputIdx = network->getInputOffset(l); double *nextLocalGradient = localGradients + nextInputIdx; int thisNeurons = network->getConfiguration()->getNeurons(l-1); int nextNeurons = network->getConfiguration()->getNeurons(l); double *thisInput = network->getInput() + thisInputIdx; double *weights = network->getWeights() + network->getWeightsOffset(l-1); // COMPUTE TOTAL DERIVATIVES for weights between layer l and l+1 int wc = network->getWeightsOffset(l+1) - network->getWeightsOffset(l); double *wdiff = weightDiffs + network->getWeightsOffset(l); for (int i = 0; i<wc; i++) { wdiff[i] = -learningRate * nextLocalGradient[i%nextNeurons] * thisInput[i/nextNeurons]; } // COMPUTE BIAS DERIVATIVES for layer l+1 if (useBias) { for (int i = 0; i<nextNeurons; i++) { biasDiff[nextInputIdx + i] = -learningRate * nextLocalGradient[i]; } } // COMPUTE LOCAL GRADIENTS for layer l // compute derivatives of neuron inputs in layer l double *thisInputDerivatives = new double[thisNeurons]; daf(thisInput, thisInputDerivatives, thisNeurons); // compute local gradients for layer l for (int i = 0; i<thisNeurons; i++) { double sumNextGradient = 0; for (int j = 0; j<nextNeurons; j++) { sumNextGradient += nextLocalGradient[j] * weights[i * thisNeurons + j]; } thisLocalGradient[i] = sumNextGradient * thisInputDerivatives[i]; } } } void BackpropagationLearner::adjustWeights() { int wc = network->getWeightsOffset(network->getConfiguration()->getLayers()); double *weights = network->getWeights(); LOG()->debug("Adjusting weights by: [[%f, %f], [%f, %f]], [[%f, %f]].", weightDiffs[2], weightDiffs[3], weightDiffs[4], weightDiffs[5], weightDiffs[6], weightDiffs[7]); // we should skip the garbage in zero-layer weights for(int i = network->getWeightsOffset(1); i<wc; i++) { weights[i] += weightDiffs[i]; } } void BackpropagationLearner::adjustBias() { double *bias = network->getBiasValues(); int noNeurons = network->getAllNeurons(); LOG()->debug("Adjusting bias by: [%f, %f], [%f, %f], [%f].", biasDiff[0], biasDiff[1], biasDiff[2], biasDiff[3], biasDiff[4]); for (int i = 0; i<noNeurons; i++) { bias[i] += biasDiff[i]; } } void BackpropagationLearner::clearLayer(double *inputPtr, int layerSize) { std::fill_n(inputPtr, layerSize, 0); } void BackpropagationLearner::validate(LabeledDataset *dataset) { if (dataset->getInputDimension() != network->getInputNeurons()) { throw new std::invalid_argument("Provided dataset must have the same input dimension as the number of input neurons!"); } if (dataset->getOutputDimension() != network->getOutputNeurons()) { throw new std::invalid_argument("Provided dataset must have the same output dimension as the number of output neurons!"); } } void BackpropagationLearner::setEpochLimit(int limit) { epochLimit = limit; } void BackpropagationLearner::setErrorComputer(ErrorComputer* errorComputer) { this->errorComputer = errorComputer; } void BackpropagationLearner::setTargetMse(double mse) { targetMse = mse; } <commit_msg>Fixed weight offset calculation in BP learner.<commit_after>/* * File: BackpropeagationLearner.cpp * Author: janvojt * * Created on July 13, 2014, 12:10 AM */ #include "BackpropagationLearner.h" #include "Network.h" #include "LabeledDataset.h" #include <cstring> #include <string> #include <stdexcept> #include "log/LoggerFactory.h" #include "log4cpp/Category.hh" BackpropagationLearner::BackpropagationLearner(Network *network) { this->network = network; learningRate = 1; epochCounter = 0; epochLimit = 1000000; targetMse = .0001; errorTotal = std::numeric_limits<double>::infinity(); allocateCache(); } BackpropagationLearner::BackpropagationLearner(const BackpropagationLearner &orig) { } BackpropagationLearner::~BackpropagationLearner() { } void BackpropagationLearner::allocateCache() { weightDiffs = new double[network->getWeightsOffset(network->getConfiguration()->getLayers())]; localGradients = new double[network->getAllNeurons()]; useBias = network->getConfiguration()->getBias(); biasDiff = useBias ? new double[network->getAllNeurons()] : NULL; } void BackpropagationLearner::train(LabeledDataset *dataset) { double mse; LOG()->info("Started training with limits of %d epochs and target MSE of %f.", epochLimit, targetMse); do { epochCounter++; LOG()->debug("Starting epoch %d.", epochCounter); dataset->reset(); int datasetSize = 0; mse = 0; while (dataset->hasNext()) { datasetSize++; double *pattern = dataset->next(); double *expOutput = pattern + dataset->getInputDimension(); LOG()->debug("Learning pattern [%f, %f] -> [%f].", pattern[0], pattern[1], expOutput[0]); doForwardPhase(pattern); doBackwardPhase(expOutput); mse += errorComputer->compute(network, expOutput); } mse = mse / datasetSize; LOG()->debug("Finished epoch %d with MSE: %f.", epochCounter, mse); } while (mse > targetMse && epochCounter < epochLimit); if (mse <= targetMse) { LOG()->info("Training successful after %d epochs with MSE of %f.", epochCounter, mse); } else { LOG()->info("Training interrupted after %d epochs with MSE of %f.", epochCounter, mse); } } void BackpropagationLearner::doForwardPhase(double *input) { network->setInput(input); network->run(); } void BackpropagationLearner::doBackwardPhase(double *expectedOutput) { computeOutputGradients(expectedOutput); computeWeightDifferentials(); adjustWeights(); if (network->getConfiguration()->getBias()) { adjustBias(); } } void BackpropagationLearner::computeOutputGradients(double *expectedOutput) { int on = network->getOutputNeurons(); int noLayers = network->getConfiguration()->getLayers(); double *localGradient = localGradients + network->getInputOffset(noLayers-1); double *output = network->getOutput(); void (*daf) (double*,double*,int) = network->getConfiguration()->dActivationFnc; // compute local gradients double *dv = new double[network->getOutputNeurons()]; daf(network->getInput() + network->getInputOffset(noLayers-1), dv, on); for (int i = 0; i<on; i++) { localGradient[i] = (output[i] - expectedOutput[i]) * dv[i]; } } void BackpropagationLearner::computeWeightDifferentials() { int noLayers = network->getConfiguration()->getLayers(); void (*daf) (double*,double*,int) = network->getConfiguration()->dActivationFnc; for (int l = noLayers-1; l>0; l--) { // INITIALIZE HELPER VARIABLES int thisInputIdx = network->getInputOffset(l-1); double *thisLocalGradient = localGradients + thisInputIdx; int nextInputIdx = network->getInputOffset(l); double *nextLocalGradient = localGradients + nextInputIdx; int thisNeurons = network->getConfiguration()->getNeurons(l-1); int nextNeurons = network->getConfiguration()->getNeurons(l); double *thisInput = network->getInput() + thisInputIdx; double *weights = network->getWeights() + network->getWeightsOffset(l); // COMPUTE TOTAL DERIVATIVES for weights between layer l and l+1 int wc = network->getWeightsOffset(l+1) - network->getWeightsOffset(l); double *wdiff = weightDiffs + network->getWeightsOffset(l); for (int i = 0; i<wc; i++) { wdiff[i] = -learningRate * nextLocalGradient[i%nextNeurons] * thisInput[i/nextNeurons]; } // COMPUTE BIAS DERIVATIVES for layer l+1 if (useBias) { for (int i = 0; i<nextNeurons; i++) { biasDiff[nextInputIdx + i] = -learningRate * nextLocalGradient[i]; } } // COMPUTE LOCAL GRADIENTS for layer l // compute derivatives of neuron inputs in layer l double *thisInputDerivatives = new double[thisNeurons]; daf(thisInput, thisInputDerivatives, thisNeurons); // compute local gradients for layer l for (int i = 0; i<thisNeurons; i++) { double sumNextGradient = 0; for (int j = 0; j<nextNeurons; j++) { sumNextGradient += nextLocalGradient[j] * weights[i * thisNeurons + j]; } thisLocalGradient[i] = sumNextGradient * thisInputDerivatives[i]; } } } void BackpropagationLearner::adjustWeights() { int wc = network->getWeightsOffset(network->getConfiguration()->getLayers()); double *weights = network->getWeights(); LOG()->debug("Adjusting weights by: [[%f, %f], [%f, %f]], [[%f, %f]].", weightDiffs[2], weightDiffs[3], weightDiffs[4], weightDiffs[5], weightDiffs[6], weightDiffs[7]); // we should skip the garbage in zero-layer weights for(int i = network->getWeightsOffset(1); i<wc; i++) { weights[i] += weightDiffs[i]; } } void BackpropagationLearner::adjustBias() { double *bias = network->getBiasValues(); int noNeurons = network->getAllNeurons(); LOG()->debug("Adjusting bias by: [%f, %f], [%f, %f], [%f].", biasDiff[0], biasDiff[1], biasDiff[2], biasDiff[3], biasDiff[4]); for (int i = 0; i<noNeurons; i++) { bias[i] += biasDiff[i]; } } void BackpropagationLearner::clearLayer(double *inputPtr, int layerSize) { std::fill_n(inputPtr, layerSize, 0); } void BackpropagationLearner::validate(LabeledDataset *dataset) { if (dataset->getInputDimension() != network->getInputNeurons()) { throw new std::invalid_argument("Provided dataset must have the same input dimension as the number of input neurons!"); } if (dataset->getOutputDimension() != network->getOutputNeurons()) { throw new std::invalid_argument("Provided dataset must have the same output dimension as the number of output neurons!"); } } void BackpropagationLearner::setEpochLimit(int limit) { epochLimit = limit; } void BackpropagationLearner::setErrorComputer(ErrorComputer* errorComputer) { this->errorComputer = errorComputer; } void BackpropagationLearner::setTargetMse(double mse) { targetMse = mse; } <|endoftext|>
<commit_before>#include "MarchingCubesPainter.h" #include <reflectionzeug/property/extensions/GlmProperties.h> #include <globjects/globjects.h> #include <gloperate/base/RenderTargetType.h> #include <gloperate/painter/TargetFramebufferCapability.h> #include <gloperate/painter/ViewportCapability.h> #include <gloperate/painter/PerspectiveProjectionCapability.h> #include <gloperate/painter/CameraCapability.h> #include <gloperate/painter/TypedRenderTargetCapability.h> #include <gloperate/painter/InputCapability.h> #include <gloperate/resources/ResourceManager.h> #include <gloperate/navigation/CoordinateProvider.h> #include <glbinding/gl/enum.h> using namespace gl; using namespace glm; using namespace globjects; MarchingCubes::MarchingCubes(gloperate::ResourceManager & resourceManager, const std::string & relDataPath) : PipelinePainter("MarchingCubesExample", resourceManager, relDataPath, m_pipeline) , m_targetFramebufferCapability{ addCapability(new gloperate::TargetFramebufferCapability()) } , m_viewportCapability{addCapability(new gloperate::ViewportCapability())} , m_projectionCapability{addCapability(new gloperate::PerspectiveProjectionCapability(m_viewportCapability))} , m_cameraCapability{addCapability(new gloperate::CameraCapability())} , m_inputCapability{ addCapability(new gloperate::InputCapability()) } , m_renderTargetCapability{ addCapability(new gloperate::TypedRenderTargetCapability()) } { globjects::init(); m_coordinateProvider = new gloperate::CoordinateProvider( m_cameraCapability, m_projectionCapability, m_viewportCapability, m_renderTargetCapability); m_pipeline.targetFBO.setData(m_targetFramebufferCapability); m_pipeline.viewport.setData(m_viewportCapability); m_pipeline.camera.setData(m_cameraCapability); m_pipeline.projection.setData(m_projectionCapability); m_pipeline.resourceManager.setData(&m_resourceManager); m_pipeline.renderTargets.setData(m_renderTargetCapability); m_pipeline.input.setData(m_inputCapability); m_pipeline.coordinateProvider.setData(m_coordinateProvider); m_targetFramebufferCapability->changed.connect([this]() { m_pipeline.targetFBO.invalidate(); }); m_viewportCapability->changed.connect([this]() { m_pipeline.viewport.invalidate(); }); m_cameraCapability->changed.connect([this]() { m_pipeline.camera.invalidate(); }); m_projectionCapability->changed.connect([this]() { m_pipeline.projection.invalidate(); }); m_renderTargetCapability->changed.connect([this]() { m_pipeline.renderTargets.invalidate(); }); m_inputCapability->changed.connect([this]() { m_pipeline.input.invalidate(); }); //m_pipeline.targetFBO.invalidated //m_renderTargetCapability->changed.connect([this]() { this->onTargetFramebufferChanged(); }); //m_cameraCapability->changed.connect([this]() { this->onTargetFramebufferChanged(); }); auto debugGroup = addGroup("Debugging"); debugGroup->addProperty(createProperty("Show Wireframe", m_pipeline.showWireframe)); debugGroup->addProperty(createProperty("Freeze Chunk Loading", m_pipeline.freezeChunkLoading)); auto terrainGroup = addGroup("Terrain Generation"); terrainGroup->addProperty(createProperty("Terrain Type", m_pipeline.terrainType)); terrainGroup->addProperty(createProperty("Base Texture", m_pipeline.userBaseTextureFilePath)); terrainGroup->addProperty(createProperty("Extra Texture", m_pipeline.userExtraTextureFilePath)); terrainGroup->addProperty(createProperty("Rotation Vector 1", m_pipeline.rotationVector1)); terrainGroup->addProperty(createProperty("Rotation Vector 2", m_pipeline.rotationVector2)); terrainGroup->addProperty(createProperty("Warp Factor", m_pipeline.warpFactor)); terrainGroup->addProperty(createProperty("Remove Floaters", m_pipeline.removeFloaters)); auto prettyTerrainGroup = addGroup("Pretty Terrain"); prettyTerrainGroup->addProperty(createProperty("Light", m_pipeline.useShadow)); prettyTerrainGroup->addProperty(createProperty("Occlusion", m_pipeline.useOcclusion)); prettyTerrainGroup->addProperty(createProperty("Use Ground Texture", m_pipeline.useGroundTexture)); prettyTerrainGroup->addProperty(createProperty("Mip Mapping", m_pipeline.useMipMap)); prettyTerrainGroup->addProperty(createProperty("Use Striation Texture", m_pipeline.useStriationTexture)); auto terrainModificationGroup = addGroup("Terrain Modification"); auto radiusProperty = createProperty("Modification Radius", m_pipeline.modificationRadius); radiusProperty->setOptions({ { "minimum", reflectionzeug::Variant(0.05f) }, { "maximum", reflectionzeug::Variant(1.0f) }, { "step", reflectionzeug::Variant(0.05f) } }); terrainModificationGroup->addProperty(radiusProperty); } MarchingCubes::~MarchingCubes() = default;<commit_msg>Add to painter<commit_after>#include "MarchingCubesPainter.h" #include <reflectionzeug/property/extensions/GlmProperties.h> #include <globjects/globjects.h> #include <gloperate/base/RenderTargetType.h> #include <gloperate/painter/TargetFramebufferCapability.h> #include <gloperate/painter/ViewportCapability.h> #include <gloperate/painter/PerspectiveProjectionCapability.h> #include <gloperate/painter/CameraCapability.h> #include <gloperate/painter/TypedRenderTargetCapability.h> #include <gloperate/painter/InputCapability.h> #include <gloperate/resources/ResourceManager.h> #include <gloperate/navigation/CoordinateProvider.h> #include <glbinding/gl/enum.h> using namespace gl; using namespace glm; using namespace globjects; MarchingCubes::MarchingCubes(gloperate::ResourceManager & resourceManager, const std::string & relDataPath) : PipelinePainter("MarchingCubesExample", resourceManager, relDataPath, m_pipeline) , m_targetFramebufferCapability{ addCapability(new gloperate::TargetFramebufferCapability()) } , m_viewportCapability{addCapability(new gloperate::ViewportCapability())} , m_projectionCapability{addCapability(new gloperate::PerspectiveProjectionCapability(m_viewportCapability))} , m_cameraCapability{addCapability(new gloperate::CameraCapability())} , m_inputCapability{ addCapability(new gloperate::InputCapability()) } , m_renderTargetCapability{ addCapability(new gloperate::TypedRenderTargetCapability()) } { globjects::init(); m_coordinateProvider = new gloperate::CoordinateProvider( m_cameraCapability, m_projectionCapability, m_viewportCapability, m_renderTargetCapability); m_pipeline.targetFBO.setData(m_targetFramebufferCapability); m_pipeline.viewport.setData(m_viewportCapability); m_pipeline.camera.setData(m_cameraCapability); m_pipeline.projection.setData(m_projectionCapability); m_pipeline.resourceManager.setData(&m_resourceManager); m_pipeline.renderTargets.setData(m_renderTargetCapability); m_pipeline.input.setData(m_inputCapability); m_pipeline.coordinateProvider.setData(m_coordinateProvider); m_targetFramebufferCapability->changed.connect([this]() { m_pipeline.targetFBO.invalidate(); }); m_viewportCapability->changed.connect([this]() { m_pipeline.viewport.invalidate(); }); m_cameraCapability->changed.connect([this]() { m_pipeline.camera.invalidate(); }); m_projectionCapability->changed.connect([this]() { m_pipeline.projection.invalidate(); }); m_renderTargetCapability->changed.connect([this]() { m_pipeline.renderTargets.invalidate(); }); m_inputCapability->changed.connect([this]() { m_pipeline.input.invalidate(); }); //m_pipeline.targetFBO.invalidated //m_renderTargetCapability->changed.connect([this]() { this->onTargetFramebufferChanged(); }); //m_cameraCapability->changed.connect([this]() { this->onTargetFramebufferChanged(); }); auto debugGroup = addGroup("Debugging"); debugGroup->addProperty(createProperty("Show Wireframe", m_pipeline.showWireframe)); debugGroup->addProperty(createProperty("Freeze Chunk Loading", m_pipeline.freezeChunkLoading)); auto terrainGroup = addGroup("Terrain Generation"); terrainGroup->addProperty(createProperty("Terrain Type", m_pipeline.terrainType)); terrainGroup->addProperty(createProperty("Base Texture", m_pipeline.userBaseTextureFilePath)); terrainGroup->addProperty(createProperty("Extra Texture", m_pipeline.userExtraTextureFilePath)); terrainGroup->addProperty(createProperty("Density Generation Shader", m_pipeline.userDensityGenererationShaderFilePath)); terrainGroup->addProperty(createProperty("Fragment Shader", m_pipeline.userFragmentShaderFilePath)); terrainGroup->addProperty(createProperty("Rotation Vector 1", m_pipeline.rotationVector1)); terrainGroup->addProperty(createProperty("Rotation Vector 2", m_pipeline.rotationVector2)); terrainGroup->addProperty(createProperty("Warp Factor", m_pipeline.warpFactor)); terrainGroup->addProperty(createProperty("Remove Floaters", m_pipeline.removeFloaters)); auto prettyTerrainGroup = addGroup("Pretty Terrain"); prettyTerrainGroup->addProperty(createProperty("Light", m_pipeline.useShadow)); prettyTerrainGroup->addProperty(createProperty("Occlusion", m_pipeline.useOcclusion)); prettyTerrainGroup->addProperty(createProperty("Use Ground Texture", m_pipeline.useGroundTexture)); prettyTerrainGroup->addProperty(createProperty("Mip Mapping", m_pipeline.useMipMap)); prettyTerrainGroup->addProperty(createProperty("Use Striation Texture", m_pipeline.useStriationTexture)); auto terrainModificationGroup = addGroup("Terrain Modification"); auto radiusProperty = createProperty("Modification Radius", m_pipeline.modificationRadius); radiusProperty->setOptions({ { "minimum", reflectionzeug::Variant(0.05f) }, { "maximum", reflectionzeug::Variant(1.0f) }, { "step", reflectionzeug::Variant(0.05f) } }); terrainModificationGroup->addProperty(radiusProperty); } MarchingCubes::~MarchingCubes() = default;<|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/nw/src/browser/nw_autofill_client.h" #include "base/logging.h" #include "base/prefs/pref_service.h" #include "components/autofill/content/browser/content_autofill_driver.h" #include "components/autofill/content/common/autofill_messages.h" #include "components/autofill/core/common/autofill_pref_names.h" #include "content/nw/src/browser/autofill_popup_controller_impl.h" #include "content/nw/src/browser/nw_form_database_service.h" #include "content/nw/src/shell_browser_context.h" #include "content/public/browser/render_view_host.h" #include "ui/gfx/geometry/rect.h" #if defined(OS_ANDROID) #include "chrome/browser/ui/android/autofill/autofill_logger_android.h" #endif DEFINE_WEB_CONTENTS_USER_DATA_KEY(autofill::NWAutofillClient); namespace autofill { NWAutofillClient::NWAutofillClient(content::WebContents* web_contents) : content::WebContentsObserver(web_contents), web_contents_(web_contents) { DCHECK(web_contents); #if defined(OS_MACOSX) && !defined(OS_IOS) RegisterForKeystoneNotifications(); #endif // defined(OS_MACOSX) && !defined(OS_IOS) } NWAutofillClient::~NWAutofillClient() { // NOTE: It is too late to clean up the autofill popup; that cleanup process // requires that the WebContents instance still be valid and it is not at // this point (in particular, the WebContentsImpl destructor has already // finished running and we are now in the base class destructor). DCHECK(!popup_controller_); #if defined(OS_MACOSX) && !defined(OS_IOS) UnregisterFromKeystoneNotifications(); #endif // defined(OS_MACOSX) && !defined(OS_IOS) } void NWAutofillClient::TabActivated() { } PersonalDataManager* NWAutofillClient::GetPersonalDataManager() { return NULL; } scoped_refptr<AutofillWebDataService> NWAutofillClient::GetDatabase() { nw::NwFormDatabaseService* service = static_cast<content::ShellBrowserContext*>( web_contents_->GetBrowserContext())->GetFormDatabaseService(); return service->get_autofill_webdata_service(); } PrefService* NWAutofillClient::GetPrefs() { return NULL; } void NWAutofillClient::ShowAutofillSettings() { NOTIMPLEMENTED(); } void NWAutofillClient::ConfirmSaveCreditCard( const base::Closure& save_card_callback) { NOTIMPLEMENTED(); } void NWAutofillClient::ShowRequestAutocompleteDialog( const FormData& form, content::RenderFrameHost* render_frame_host, const ResultCallback& callback) { NOTIMPLEMENTED(); } void NWAutofillClient::ShowAutofillPopup( const gfx::RectF& element_bounds, base::i18n::TextDirection text_direction, const std::vector<autofill::Suggestion>& suggestions, base::WeakPtr<AutofillPopupDelegate> delegate) { // Convert element_bounds to be in screen space. gfx::Rect client_area = web_contents_->GetContainerBounds(); gfx::RectF element_bounds_in_screen_space = element_bounds + client_area.OffsetFromOrigin(); // Will delete or reuse the old |popup_controller_|. popup_controller_ = AutofillPopupControllerImpl::GetOrCreate(popup_controller_, delegate, web_contents(), web_contents()->GetNativeView(), element_bounds_in_screen_space, text_direction); popup_controller_->Show(suggestions); } void NWAutofillClient::UpdateAutofillPopupDataListValues( const std::vector<base::string16>& values, const std::vector<base::string16>& labels) { if (popup_controller_.get()) popup_controller_->UpdateDataListValues(values, labels); } void NWAutofillClient::HideAutofillPopup() { if (popup_controller_.get()) popup_controller_->Hide(); } bool NWAutofillClient::IsAutocompleteEnabled() { return true; } void NWAutofillClient::HideRequestAutocompleteDialog() { NOTIMPLEMENTED(); } void NWAutofillClient::WebContentsDestroyed() { HideAutofillPopup(); } void NWAutofillClient::DetectAccountCreationForms( content::RenderFrameHost* rfh, const std::vector<autofill::FormStructure*>& forms) { NOTIMPLEMENTED(); } void NWAutofillClient::DidFillOrPreviewField( const base::string16& autofilled_value, const base::string16& profile_full_name) { } bool NWAutofillClient::HasCreditCardScanFeature() { return false; } void NWAutofillClient::ScanCreditCard(const CreditCardScanCallback& callback) { NOTIMPLEMENTED(); } void NWAutofillClient::ShowUnmaskPrompt( const autofill::CreditCard& card, base::WeakPtr<autofill::CardUnmaskDelegate> delegate) { NOTIMPLEMENTED(); } void NWAutofillClient::OnUnmaskVerificationResult(bool success) { NOTIMPLEMENTED(); } void NWAutofillClient::OnFirstUserGestureObserved() { NOTIMPLEMENTED(); } } // namespace autofill <commit_msg>suppress NOTIMPL message in nw autofill client<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/nw/src/browser/nw_autofill_client.h" #include "base/logging.h" #include "base/prefs/pref_service.h" #include "components/autofill/content/browser/content_autofill_driver.h" #include "components/autofill/content/common/autofill_messages.h" #include "components/autofill/core/common/autofill_pref_names.h" #include "content/nw/src/browser/autofill_popup_controller_impl.h" #include "content/nw/src/browser/nw_form_database_service.h" #include "content/nw/src/shell_browser_context.h" #include "content/public/browser/render_view_host.h" #include "ui/gfx/geometry/rect.h" #if defined(OS_ANDROID) #include "chrome/browser/ui/android/autofill/autofill_logger_android.h" #endif DEFINE_WEB_CONTENTS_USER_DATA_KEY(autofill::NWAutofillClient); namespace autofill { NWAutofillClient::NWAutofillClient(content::WebContents* web_contents) : content::WebContentsObserver(web_contents), web_contents_(web_contents) { DCHECK(web_contents); #if defined(OS_MACOSX) && !defined(OS_IOS) RegisterForKeystoneNotifications(); #endif // defined(OS_MACOSX) && !defined(OS_IOS) } NWAutofillClient::~NWAutofillClient() { // NOTE: It is too late to clean up the autofill popup; that cleanup process // requires that the WebContents instance still be valid and it is not at // this point (in particular, the WebContentsImpl destructor has already // finished running and we are now in the base class destructor). DCHECK(!popup_controller_); #if defined(OS_MACOSX) && !defined(OS_IOS) UnregisterFromKeystoneNotifications(); #endif // defined(OS_MACOSX) && !defined(OS_IOS) } void NWAutofillClient::TabActivated() { } PersonalDataManager* NWAutofillClient::GetPersonalDataManager() { return NULL; } scoped_refptr<AutofillWebDataService> NWAutofillClient::GetDatabase() { nw::NwFormDatabaseService* service = static_cast<content::ShellBrowserContext*>( web_contents_->GetBrowserContext())->GetFormDatabaseService(); return service->get_autofill_webdata_service(); } PrefService* NWAutofillClient::GetPrefs() { return NULL; } void NWAutofillClient::ShowAutofillSettings() { NOTIMPLEMENTED(); } void NWAutofillClient::ConfirmSaveCreditCard( const base::Closure& save_card_callback) { NOTIMPLEMENTED(); } void NWAutofillClient::ShowRequestAutocompleteDialog( const FormData& form, content::RenderFrameHost* render_frame_host, const ResultCallback& callback) { NOTIMPLEMENTED(); } void NWAutofillClient::ShowAutofillPopup( const gfx::RectF& element_bounds, base::i18n::TextDirection text_direction, const std::vector<autofill::Suggestion>& suggestions, base::WeakPtr<AutofillPopupDelegate> delegate) { // Convert element_bounds to be in screen space. gfx::Rect client_area = web_contents_->GetContainerBounds(); gfx::RectF element_bounds_in_screen_space = element_bounds + client_area.OffsetFromOrigin(); // Will delete or reuse the old |popup_controller_|. popup_controller_ = AutofillPopupControllerImpl::GetOrCreate(popup_controller_, delegate, web_contents(), web_contents()->GetNativeView(), element_bounds_in_screen_space, text_direction); popup_controller_->Show(suggestions); } void NWAutofillClient::UpdateAutofillPopupDataListValues( const std::vector<base::string16>& values, const std::vector<base::string16>& labels) { if (popup_controller_.get()) popup_controller_->UpdateDataListValues(values, labels); } void NWAutofillClient::HideAutofillPopup() { if (popup_controller_.get()) popup_controller_->Hide(); } bool NWAutofillClient::IsAutocompleteEnabled() { return true; } void NWAutofillClient::HideRequestAutocompleteDialog() { NOTIMPLEMENTED(); } void NWAutofillClient::WebContentsDestroyed() { HideAutofillPopup(); } void NWAutofillClient::DetectAccountCreationForms( content::RenderFrameHost* rfh, const std::vector<autofill::FormStructure*>& forms) { NOTIMPLEMENTED(); } void NWAutofillClient::DidFillOrPreviewField( const base::string16& autofilled_value, const base::string16& profile_full_name) { } bool NWAutofillClient::HasCreditCardScanFeature() { return false; } void NWAutofillClient::ScanCreditCard(const CreditCardScanCallback& callback) { NOTIMPLEMENTED(); } void NWAutofillClient::ShowUnmaskPrompt( const autofill::CreditCard& card, base::WeakPtr<autofill::CardUnmaskDelegate> delegate) { NOTIMPLEMENTED(); } void NWAutofillClient::OnUnmaskVerificationResult(bool success) { NOTIMPLEMENTED(); } void NWAutofillClient::OnFirstUserGestureObserved() { //NOTIMPLEMENTED(); } } // namespace autofill <|endoftext|>
<commit_before><commit_msg>trim thread interval<commit_after><|endoftext|>
<commit_before>/**************************************************************************** * Copyright (C) 2014-2015 by Savoir-Faire Linux * * Author : Emmanuel Lepage Vallee <[email protected]> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "sourcesmodel.h" #include <QtCore/QUrl> #include <QtCore/QCoreApplication> #include "../dbus/videomanager.h" #include "devicemodel.h" namespace Video { class SourcesModelPrivate { public: SourcesModelPrivate(); //Constants class ProtocolPrefix { public: constexpr static const char* NONE = "" ; constexpr static const char* DISPLAY = "display://"; constexpr static const char* FILE = "file://" ; constexpr static const char* V4L2 = "v4l2://" ; }; struct Display { Display() : rect(0,0,0,0),index(0){} QRect rect; int index ; /* X11 display ID, usually 0 */ }; QUrl m_CurrentFile; Display m_Display; int m_CurrentSelection; }; } Video::SourcesModelPrivate::SourcesModelPrivate() : m_CurrentSelection(-1) { } Video::SourcesModel* Video::SourcesModel::m_spInstance = nullptr; Video::SourcesModel::SourcesModel() : QAbstractListModel(QCoreApplication::instance()), d_ptr(new Video::SourcesModelPrivate()) { d_ptr->m_Display.rect = QRect(0,0,0,0); } Video::SourcesModel::~SourcesModel() { delete d_ptr; } Video::SourcesModel* Video::SourcesModel::instance() { if (!m_spInstance) m_spInstance = new Video::SourcesModel(); return m_spInstance; } QHash<int,QByteArray> Video::SourcesModel::roleNames() const { static QHash<int, QByteArray> roles = QAbstractItemModel::roleNames(); static bool initRoles = false; if (!initRoles) { initRoles = true; } return roles; } QVariant Video::SourcesModel::data( const QModelIndex& index, int role ) const { switch (index.row()) { case ExtendedDeviceList::NONE: switch(role) { case Qt::DisplayRole: return tr("NONE"); }; break; case ExtendedDeviceList::SCREEN: switch(role) { case Qt::DisplayRole: return tr("SCREEN"); }; break; case ExtendedDeviceList::FILE: switch(role) { case Qt::DisplayRole: return tr("FILE"); }; break; default: return Video::DeviceModel::instance()->data(Video::DeviceModel::instance()->index(index.row()-ExtendedDeviceList::COUNT__,0),role); }; return QVariant(); } int Video::SourcesModel::rowCount( const QModelIndex& parent ) const { Q_UNUSED(parent) return Video::DeviceModel::instance()->rowCount() + ExtendedDeviceList::COUNT__; } Qt::ItemFlags Video::SourcesModel::flags( const QModelIndex& idx ) const { switch (idx.row()) { case ExtendedDeviceList::NONE : case ExtendedDeviceList::SCREEN: case ExtendedDeviceList::FILE : return QAbstractItemModel::flags(idx) | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable; break; default: return Video::DeviceModel::instance()->flags(Video::DeviceModel::instance()->index(idx.row()-ExtendedDeviceList::COUNT__,0)); }; } bool Video::SourcesModel::setData( const QModelIndex& index, const QVariant &value, int role) { Q_UNUSED(index) Q_UNUSED(value) Q_UNUSED(role) return false; } void Video::SourcesModel::switchTo(const QModelIndex& idx) { switchTo(idx.row()); } ///This model is designed for "live" switching rather than configuration void Video::SourcesModel::switchTo(const int idx) { switch (idx) { case ExtendedDeviceList::NONE: DBus::VideoManager::instance().switchInput(Video::SourcesModelPrivate::ProtocolPrefix::NONE); break; case ExtendedDeviceList::SCREEN: DBus::VideoManager::instance().switchInput( QString(Video::SourcesModelPrivate::ProtocolPrefix::DISPLAY)+QString(":%1 %2x%3") .arg(d_ptr->m_Display.index) .arg(d_ptr->m_Display.rect.width()) .arg(d_ptr->m_Display.rect.height())); break; case ExtendedDeviceList::FILE: DBus::VideoManager::instance().switchInput( !d_ptr->m_CurrentFile.isEmpty()?+Video::SourcesModelPrivate::ProtocolPrefix::FILE+d_ptr->m_CurrentFile.path():Video::SourcesModelPrivate::ProtocolPrefix::NONE ); break; default: DBus::VideoManager::instance().switchInput(Video::SourcesModelPrivate::ProtocolPrefix::V4L2 + Video::DeviceModel::instance()->index(idx-ExtendedDeviceList::COUNT__,0).data(Qt::DisplayRole).toString()); break; }; d_ptr->m_CurrentSelection = (ExtendedDeviceList) idx; } void Video::SourcesModel::switchTo(Video::Device* device) { DBus::VideoManager::instance().switchInput(Video::SourcesModelPrivate::ProtocolPrefix::V4L2 + device->id()); } Video::Device* Video::SourcesModel::deviceAt(const QModelIndex& idx) const { if (!idx.isValid()) return nullptr; switch (idx.row()) { case ExtendedDeviceList::NONE: case ExtendedDeviceList::SCREEN: case ExtendedDeviceList::FILE: return nullptr; default: return Video::DeviceModel::instance()->devices()[idx.row()-ExtendedDeviceList::COUNT__]; }; } int Video::SourcesModel::activeIndex() const { if (d_ptr->m_CurrentSelection == -1) { return ExtendedDeviceList::COUNT__ + Video::DeviceModel::instance()->activeIndex(); } return d_ptr->m_CurrentSelection; } void Video::SourcesModel::setFile(const QUrl& url) { d_ptr->m_CurrentFile = url; switchTo(ExtendedDeviceList::FILE); } void Video::SourcesModel::setDisplay(int index, QRect rect) { d_ptr->m_Display.index = index ; d_ptr->m_Display.rect = rect ; switchTo(ExtendedDeviceList::SCREEN); } <commit_msg>video: improve screen extended device type<commit_after>/**************************************************************************** * Copyright (C) 2014-2015 by Savoir-Faire Linux * * Author : Emmanuel Lepage Vallee <[email protected]> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "sourcesmodel.h" #include <QtCore/QUrl> #include <QtCore/QCoreApplication> #include "../dbus/videomanager.h" #include "devicemodel.h" namespace Video { class SourcesModelPrivate { public: SourcesModelPrivate(); //Constants class ProtocolPrefix { public: constexpr static const char* NONE = "" ; constexpr static const char* DISPLAY = "display://"; constexpr static const char* FILE = "file://" ; constexpr static const char* V4L2 = "v4l2://" ; }; struct Display { Display() : rect(0,0,0,0),index(0){} QRect rect; int index ; /* X11 display ID, usually 0 */ }; QUrl m_CurrentFile; Display m_Display; int m_CurrentSelection; }; } Video::SourcesModelPrivate::SourcesModelPrivate() : m_CurrentSelection(-1) { } Video::SourcesModel* Video::SourcesModel::m_spInstance = nullptr; Video::SourcesModel::SourcesModel() : QAbstractListModel(QCoreApplication::instance()), d_ptr(new Video::SourcesModelPrivate()) { d_ptr->m_Display.rect = QRect(0,0,0,0); } Video::SourcesModel::~SourcesModel() { delete d_ptr; } Video::SourcesModel* Video::SourcesModel::instance() { if (!m_spInstance) m_spInstance = new Video::SourcesModel(); return m_spInstance; } QHash<int,QByteArray> Video::SourcesModel::roleNames() const { static QHash<int, QByteArray> roles = QAbstractItemModel::roleNames(); static bool initRoles = false; if (!initRoles) { initRoles = true; } return roles; } QVariant Video::SourcesModel::data( const QModelIndex& index, int role ) const { switch (index.row()) { case ExtendedDeviceList::NONE: switch(role) { case Qt::DisplayRole: return tr("NONE"); }; break; case ExtendedDeviceList::SCREEN: switch(role) { case Qt::DisplayRole: return tr("SCREEN"); }; break; case ExtendedDeviceList::FILE: switch(role) { case Qt::DisplayRole: return tr("FILE"); }; break; default: return Video::DeviceModel::instance()->data(Video::DeviceModel::instance()->index(index.row()-ExtendedDeviceList::COUNT__,0),role); }; return QVariant(); } int Video::SourcesModel::rowCount( const QModelIndex& parent ) const { Q_UNUSED(parent) return Video::DeviceModel::instance()->rowCount() + ExtendedDeviceList::COUNT__; } Qt::ItemFlags Video::SourcesModel::flags( const QModelIndex& idx ) const { switch (idx.row()) { case ExtendedDeviceList::NONE : case ExtendedDeviceList::SCREEN: case ExtendedDeviceList::FILE : return QAbstractItemModel::flags(idx) | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable; break; default: return Video::DeviceModel::instance()->flags(Video::DeviceModel::instance()->index(idx.row()-ExtendedDeviceList::COUNT__,0)); }; } bool Video::SourcesModel::setData( const QModelIndex& index, const QVariant &value, int role) { Q_UNUSED(index) Q_UNUSED(value) Q_UNUSED(role) return false; } void Video::SourcesModel::switchTo(const QModelIndex& idx) { switchTo(idx.row()); } ///This model is designed for "live" switching rather than configuration void Video::SourcesModel::switchTo(const int idx) { switch (idx) { case ExtendedDeviceList::NONE: DBus::VideoManager::instance().switchInput(Video::SourcesModelPrivate::ProtocolPrefix::NONE); break; case ExtendedDeviceList::SCREEN: DBus::VideoManager::instance().switchInput( QString(Video::SourcesModelPrivate::ProtocolPrefix::DISPLAY)+QString(":%1+%2,%3 %4x%5") .arg(d_ptr->m_Display.index) .arg(d_ptr->m_Display.rect.x()) .arg(d_ptr->m_Display.rect.y()) .arg(d_ptr->m_Display.rect.width()) .arg(d_ptr->m_Display.rect.height())); break; case ExtendedDeviceList::FILE: DBus::VideoManager::instance().switchInput( !d_ptr->m_CurrentFile.isEmpty()?+Video::SourcesModelPrivate::ProtocolPrefix::FILE+d_ptr->m_CurrentFile.path():Video::SourcesModelPrivate::ProtocolPrefix::NONE ); break; default: DBus::VideoManager::instance().switchInput(Video::SourcesModelPrivate::ProtocolPrefix::V4L2 + Video::DeviceModel::instance()->index(idx-ExtendedDeviceList::COUNT__,0).data(Qt::DisplayRole).toString()); break; }; d_ptr->m_CurrentSelection = (ExtendedDeviceList) idx; } void Video::SourcesModel::switchTo(Video::Device* device) { DBus::VideoManager::instance().switchInput(Video::SourcesModelPrivate::ProtocolPrefix::V4L2 + device->id()); } Video::Device* Video::SourcesModel::deviceAt(const QModelIndex& idx) const { if (!idx.isValid()) return nullptr; switch (idx.row()) { case ExtendedDeviceList::NONE: case ExtendedDeviceList::SCREEN: case ExtendedDeviceList::FILE: return nullptr; default: return Video::DeviceModel::instance()->devices()[idx.row()-ExtendedDeviceList::COUNT__]; }; } int Video::SourcesModel::activeIndex() const { if (d_ptr->m_CurrentSelection == -1) { return ExtendedDeviceList::COUNT__ + Video::DeviceModel::instance()->activeIndex(); } return d_ptr->m_CurrentSelection; } void Video::SourcesModel::setFile(const QUrl& url) { d_ptr->m_CurrentFile = url; switchTo(ExtendedDeviceList::FILE); } void Video::SourcesModel::setDisplay(int index, QRect rect) { d_ptr->m_Display.index = index ; d_ptr->m_Display.rect = rect ; switchTo(ExtendedDeviceList::SCREEN); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: jobexecutor.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 00:23:05 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef __FRAMEWORK_JOBS_JOBEXECUTOR_HXX_ #define __FRAMEWORK_JOBS_JOBEXECUTOR_HXX_ //_______________________________________ // my own includes #ifndef __FRAMEWORK_CONFIG_CONFIGACCESS_HXX_ #include <jobs/configaccess.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_ #include <macros/xinterface.hxx> #endif #ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_ #include <macros/xtypeprovider.hxx> #endif #ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_ #include <macros/xserviceinfo.hxx> #endif #ifndef __FRAMEWORK_MACROS_DEBUG_HXX_ #include <macros/debug.hxx> #endif #ifndef __FRAMEWORK_STDTYPES_H_ #include <stdtypes.h> #endif #ifndef __FRAMEWORK_GENERAL_H_ #include <general.h> #endif //_______________________________________ // interface includes #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_TASK_XJOBEXECUTOR_HPP_ #include <com/sun/star/task/XJobExecutor.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCONTAINERLISTENER_HPP_ #include <com/sun/star/container/XContainerListener.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_ #include <com/sun/star/lang/XEventListener.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEVENTLISTENER_HPP_ #include <com/sun/star/document/XEventListener.hpp> #endif //_______________________________________ // other includes #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif //_______________________________________ // namespace namespace framework{ //_______________________________________ // public const //_______________________________________ /** @short implements a job executor, which can be triggered from any code @descr It uses the given trigger event to locate any registered job service inside the configuration and execute it. Of course it controls the liftime of such jobs too. */ class JobExecutor : public css::lang::XTypeProvider , public css::lang::XServiceInfo , public css::task::XJobExecutor , public css::container::XContainerListener // => lang.XEventListener , public css::document::XEventListener , private ThreadHelpBase , public ::cppu::OWeakObject { //___________________________________ // member private: /** reference to the uno service manager */ css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR; /** cached list of all registered event names of cfg for call optimization. */ OUStringList m_lEvents; /** we listen at the configuration for changes at the event list. */ ConfigAccess m_aConfig; //___________________________________ // native interface methods public: JobExecutor( const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ); virtual ~JobExecutor( ); //___________________________________ // uno interface methods public: // XInterface, XTypeProvider, XServiceInfo DECLARE_XINTERFACE DECLARE_XTYPEPROVIDER DECLARE_XSERVICEINFO // task.XJobExecutor virtual void SAL_CALL trigger( const ::rtl::OUString& sEvent ) throw(css::uno::RuntimeException); // document.XEventListener virtual void SAL_CALL notifyEvent( const css::document::EventObject& aEvent ) throw(css::uno::RuntimeException); // container.XContainerListener virtual void SAL_CALL elementInserted( const css::container::ContainerEvent& aEvent ) throw(css::uno::RuntimeException); virtual void SAL_CALL elementRemoved ( const css::container::ContainerEvent& aEvent ) throw(css::uno::RuntimeException); virtual void SAL_CALL elementReplaced( const css::container::ContainerEvent& aEvent ) throw(css::uno::RuntimeException); // lang.XEventListener virtual void SAL_CALL disposing( const css::lang::EventObject& aEvent ) throw(css::uno::RuntimeException); }; } // namespace framework #endif // __FRAMEWORK_JOBS_JOBEXECUTOR_HXX_ <commit_msg>INTEGRATION: CWS warnings01 (1.4.32); FILE MERGED 2005/10/28 14:48:13 cd 1.4.32.1: #i55991# Warning free code changes for gcc<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: jobexecutor.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2006-06-19 10:56:47 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef __FRAMEWORK_JOBS_JOBEXECUTOR_HXX_ #define __FRAMEWORK_JOBS_JOBEXECUTOR_HXX_ //_______________________________________ // my own includes #ifndef __FRAMEWORK_CONFIG_CONFIGACCESS_HXX_ #include <jobs/configaccess.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_ #include <macros/xinterface.hxx> #endif #ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_ #include <macros/xtypeprovider.hxx> #endif #ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_ #include <macros/xserviceinfo.hxx> #endif #ifndef __FRAMEWORK_MACROS_DEBUG_HXX_ #include <macros/debug.hxx> #endif #ifndef __FRAMEWORK_STDTYPES_H_ #include <stdtypes.h> #endif #ifndef __FRAMEWORK_GENERAL_H_ #include <general.h> #endif //_______________________________________ // interface includes #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_TASK_XJOBEXECUTOR_HPP_ #include <com/sun/star/task/XJobExecutor.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCONTAINERLISTENER_HPP_ #include <com/sun/star/container/XContainerListener.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_ #include <com/sun/star/lang/XEventListener.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEVENTLISTENER_HPP_ #include <com/sun/star/document/XEventListener.hpp> #endif //_______________________________________ // other includes #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif //_______________________________________ // namespace namespace framework{ //_______________________________________ // public const //_______________________________________ /** @short implements a job executor, which can be triggered from any code @descr It uses the given trigger event to locate any registered job service inside the configuration and execute it. Of course it controls the liftime of such jobs too. */ class JobExecutor : public css::lang::XTypeProvider , public css::lang::XServiceInfo , public css::task::XJobExecutor , public css::container::XContainerListener // => lang.XEventListener , public css::document::XEventListener , private ThreadHelpBase , public ::cppu::OWeakObject { //___________________________________ // member private: /** reference to the uno service manager */ css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR; /** cached list of all registered event names of cfg for call optimization. */ OUStringList m_lEvents; /** we listen at the configuration for changes at the event list. */ ConfigAccess m_aConfig; //___________________________________ // native interface methods public: JobExecutor( const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ); virtual ~JobExecutor( ); //___________________________________ // uno interface methods public: // XInterface, XTypeProvider, XServiceInfo FWK_DECLARE_XINTERFACE FWK_DECLARE_XTYPEPROVIDER DECLARE_XSERVICEINFO // task.XJobExecutor virtual void SAL_CALL trigger( const ::rtl::OUString& sEvent ) throw(css::uno::RuntimeException); // document.XEventListener virtual void SAL_CALL notifyEvent( const css::document::EventObject& aEvent ) throw(css::uno::RuntimeException); // container.XContainerListener virtual void SAL_CALL elementInserted( const css::container::ContainerEvent& aEvent ) throw(css::uno::RuntimeException); virtual void SAL_CALL elementRemoved ( const css::container::ContainerEvent& aEvent ) throw(css::uno::RuntimeException); virtual void SAL_CALL elementReplaced( const css::container::ContainerEvent& aEvent ) throw(css::uno::RuntimeException); // lang.XEventListener virtual void SAL_CALL disposing( const css::lang::EventObject& aEvent ) throw(css::uno::RuntimeException); }; } // namespace framework #endif // __FRAMEWORK_JOBS_JOBEXECUTOR_HXX_ <|endoftext|>
<commit_before>#include "Messaging/RpcHandler.hpp" #include "Transports/AddressFactory.hpp" #include "Connection.hpp" #include "ConnectionManager.hpp" using Dissent::Transports::AddressFactory; namespace Dissent { namespace Connections { ConnectionManager::ConnectionManager(const Id &local_id, RpcHandler &rpc) : _inquire(this, &ConnectionManager::Inquire), _inquired(this, &ConnectionManager::Inquired), _close(this, &ConnectionManager::Close), _connect(this, &ConnectionManager::Connect), _disconnect(this, &ConnectionManager::Disconnect), _con_tab(local_id), _local_id(local_id), _rpc(rpc), _closed(false) { _rpc.Register(&_inquire, "CM::Inquire"); _rpc.Register(&_close, "CM::Close"); _rpc.Register(&_connect, "CM::Connect"); _rpc.Register(&_disconnect, "CM::Disconnect"); Connection *con = _con_tab.GetConnection(_local_id); con->SetSink(&_rpc); QObject::connect(con->GetEdge().data(), SIGNAL(Closed(const QString &)), this, SLOT(HandleEdgeClose(const QString &))); QObject::connect(con, SIGNAL(CalledDisconnect()), this, SLOT(HandleDisconnect())); QObject::connect(con, SIGNAL(Disconnected(const QString &)), this, SLOT(HandleDisconnected(const QString &))); } ConnectionManager::~ConnectionManager() { _rpc.Unregister("CM::Inquire"); _rpc.Unregister("CM::Close"); _rpc.Unregister("CM::Connect"); _rpc.Unregister("CM::Disconnect"); } void ConnectionManager::AddEdgeListener(QSharedPointer<EdgeListener> el) { if(_closed) { qWarning() << "Attempting to add an EdgeListener after calling Disconnect."; return; } _edge_factory.AddEdgeListener(el); QObject::connect(el.data(), SIGNAL(NewEdge(QSharedPointer<Edge>)), this, SLOT(HandleNewEdge(QSharedPointer<Edge>))); QObject::connect(el.data(), SIGNAL(EdgeCreationFailure(const Address &, const QString &)), this, SLOT(HandleEdgeCreationFailure(const Address &, const QString&))); } void ConnectionManager::ConnectTo(const Address &addr) { if(_closed) { qWarning() << "Attempting to Connect to a remote node after calling Disconnect."; return; } if(_outstanding_con_attempts.contains(addr)) { qDebug() << "Attempting to connect multiple times to the same address:" << addr.ToString(); return; } _outstanding_con_attempts[addr] = true; if(!_edge_factory.CreateEdgeTo(addr)) { _outstanding_con_attempts.remove(addr); emit ConnectionAttemptFailure(addr, "No EdgeListener to handle request"); } } void ConnectionManager::Disconnect() { if(_closed) { qWarning() << "Called Disconnect twice on ConnectionManager."; return; } _closed = true; bool emit_dis = (_con_tab.GetEdges().count() == 0); foreach(Connection *con, _con_tab.GetConnections()) { con->Disconnect(); } foreach(QSharedPointer<Edge> edge, _con_tab.GetEdges()) { if(!edge->IsClosed()) { edge->Close("Disconnecting"); } } _edge_factory.Stop(); if(emit_dis) { emit Disconnected(); } } void ConnectionManager::HandleNewEdge(QSharedPointer<Edge> edge) { _con_tab.AddEdge(edge); edge->SetSink(&_rpc); QObject::connect(edge.data(), SIGNAL(Closed(const QString &)), this, SLOT(HandleEdgeClose(const QString &))); if(!edge->Outbound()) { return; } if(_outstanding_con_attempts.remove(edge->GetRemoteAddress()) == 0) { qDebug() << "No record of attempting connection to" << edge->GetRemoteAddress().ToString(); } QVariantMap request; request["method"] = "CM::Inquire"; request["peer_id"] = _local_id.GetByteArray(); QString type = edge->GetLocalAddress().GetType(); QSharedPointer<EdgeListener> el = _edge_factory.GetEdgeListener(type); request["persistent"] = el->GetAddress().ToString(); _rpc.SendRequest(request, edge.data(), &_inquired); } void ConnectionManager::HandleEdgeCreationFailure(const Address &to, const QString &reason) { _outstanding_con_attempts.remove(to); emit ConnectionAttemptFailure(to, reason); } void ConnectionManager::Inquire(RpcRequest &request) { Dissent::Messaging::ISender *from = request.GetFrom(); Edge *edge = dynamic_cast<Edge *>(from); if(edge == 0) { qWarning() << "Received an inquired from a non-Edge: " << from->ToString(); return; } else if(edge->Outbound()) { qWarning() << "We should never receive an inquire call on an outbound edge: " << from->ToString(); return; } QByteArray brem_id = request.GetMessage()["peer_id"].toByteArray(); if(brem_id.isEmpty()) { qWarning() << "Invalid Inqiure, no id"; return; } Id rem_id(brem_id); QVariantMap response; response["peer_id"] = _local_id.GetByteArray(); request.Respond(response); QString saddr = request.GetMessage()["persistent"].toString(); Address addr = AddressFactory::GetInstance().CreateAddress(saddr); edge->SetRemotePersistentAddress(addr); if(_local_id < rem_id) { BindEdge(edge, rem_id); } else if(_local_id == rem_id) { edge->Close("Attempting to connect to ourself"); } } void ConnectionManager::Inquired(RpcRequest &response) { Dissent::Messaging::ISender *from = response.GetFrom(); Edge *edge = dynamic_cast<Edge *>(from); if(edge == 0) { qWarning() << "Received an inquired from a non-Edge: " << from->ToString(); return; } else if(!edge->Outbound()) { qWarning() << "We would never make an inquire call on an incoming edge: " << from->ToString(); return; } QByteArray brem_id = response.GetMessage()["peer_id"].toByteArray(); if(brem_id.isEmpty()) { qWarning() << "Invalid ConnectionEstablished, no id"; return; } Id rem_id(brem_id); if(_local_id < rem_id) { BindEdge(edge, rem_id); } else if(rem_id == _local_id) { Address addr = edge->GetRemoteAddress(); qDebug() << "Attempting to connect to ourself"; edge->Close("Attempting to connect to ourself"); emit ConnectionAttemptFailure(addr, "Attempting to connect to ourself"); return; } } void ConnectionManager::BindEdge(Edge *edge, const Id &rem_id) { /// @TODO add an extra variable to the connection message such as a session ///token so that quick reconnects can be enabled. if(_con_tab.GetConnection(rem_id) != 0) { qWarning() << "Already have a connection to: " << rem_id.ToString() << " closing Edge: " << edge->ToString(); QVariantMap notification; notification["method"] = "CM::Close"; _rpc.SendNotification(notification, edge); Address addr = edge->GetRemoteAddress(); edge->Close("Duplicate connection"); emit ConnectionAttemptFailure(addr, "Duplicate connection"); return; } QSharedPointer<Edge> pedge = _con_tab.GetEdge(edge); if(pedge.isNull()) { qCritical() << "An edge attempted to create a connection, but there " "is no record of it" << edge->ToString(); return; } QVariantMap notification; notification["method"] = "CM::Connect"; notification["peer_id"] = _local_id.GetByteArray(); _rpc.SendNotification(notification, edge); CreateConnection(pedge, rem_id); } void ConnectionManager::Connect(RpcRequest &notification) { Edge *edge = dynamic_cast<Edge *>(notification.GetFrom()); if(edge == 0) { qWarning() << "Connection attempt not from an Edge: " << notification.GetFrom()->ToString(); return; } QByteArray brem_id = notification.GetMessage()["peer_id"].toByteArray(); if(brem_id.isEmpty()) { qWarning() << "Invalid ConnectionEstablished, no id"; return; } Id rem_id(brem_id); if(_local_id < rem_id) { qWarning() << "We should be sending CM::Connect, not the remote side."; return; } Connection *old_con = _con_tab.GetConnection(rem_id); // XXX if there is an old connection and the node doesn't want it, we need // to close it if(old_con != 0) { qDebug() << "Disconnecting old connection"; old_con->Disconnect(); } QSharedPointer<Edge> pedge = _con_tab.GetEdge(edge); if(pedge.isNull()) { qCritical() << "An edge attempted to create a connection, but there " "is no record of it" << edge->ToString(); return; } CreateConnection(pedge, rem_id); } void ConnectionManager::CreateConnection(QSharedPointer<Edge> pedge, const Id &rem_id) { Connection *con = new Connection(pedge, _local_id, rem_id); _con_tab.AddConnection(con); qDebug() << _local_id.ToString() << ": Handle new connection from " << rem_id.ToString(); QObject::connect(con, SIGNAL(CalledDisconnect()), this, SLOT(HandleDisconnect())); QObject::connect(con, SIGNAL(Disconnected(const QString &)), this, SLOT(HandleDisconnected(const QString &))); emit NewConnection(con); } void ConnectionManager::Close(RpcRequest &notification) { Edge *edge = dynamic_cast<Edge *>(notification.GetFrom()); if(edge == 0) { qWarning() << "Connection attempt Edge close not from an Edge: " << notification.GetFrom()->ToString(); return; } edge->Close("Closed from remote peer"); } void ConnectionManager::HandleDisconnect() { Connection *con = qobject_cast<Connection *>(sender()); if(con == 0) { return; } qDebug() << "Handle disconnect on: " << con->ToString(); _con_tab.Disconnect(con); if(!con->GetEdge()->IsClosed()) { if(con->GetLocalId() != con->GetRemoteId()) { QVariantMap notification; notification["method"] = "CM::Disconnect"; _rpc.SendNotification(notification, con); } con->GetEdge()->Close("Local disconnect request"); } } void ConnectionManager::HandleDisconnected(const QString &reason) { Connection *con = qobject_cast<Connection *>(sender()); qDebug() << "Edge disconnected now removing Connection: " << con->ToString() << ", because: " << reason; _con_tab.RemoveConnection(con); } void ConnectionManager::Disconnect(RpcRequest &notification) { Connection *con = dynamic_cast<Connection *>(notification.GetFrom()); if(con == 0) { qWarning() << "Received DisconnectResponse from a non-connection: " << notification.GetFrom()->ToString(); return; } qDebug() << "Received disconnect for: " << con->ToString(); _con_tab.Disconnect(con); con->GetEdge()->Close("Remote disconnect"); } void ConnectionManager::HandleEdgeClose(const QString &reason) { Edge *edge = qobject_cast<Edge *>(sender()); qDebug() << "Edge closed: " << edge->ToString() << reason; if(!_con_tab.RemoveEdge(edge)) { qWarning() << "Edge closed but no Edge found in CT:" << edge->ToString(); } Connection *con = _con_tab.GetConnection(edge); if(con != 0) { con = _con_tab.GetConnection(con->GetRemoteId()); if(con != 0) { con->Disconnect(); } } if(!_closed) { return; } if(_con_tab.GetEdges().count() == 0) { emit Disconnected(); } } } } <commit_msg>[Connections] Better logging to ConnectionManager<commit_after>#include "Messaging/RpcHandler.hpp" #include "Transports/AddressFactory.hpp" #include "Connection.hpp" #include "ConnectionManager.hpp" using Dissent::Transports::AddressFactory; namespace Dissent { namespace Connections { ConnectionManager::ConnectionManager(const Id &local_id, RpcHandler &rpc) : _inquire(this, &ConnectionManager::Inquire), _inquired(this, &ConnectionManager::Inquired), _close(this, &ConnectionManager::Close), _connect(this, &ConnectionManager::Connect), _disconnect(this, &ConnectionManager::Disconnect), _con_tab(local_id), _local_id(local_id), _rpc(rpc), _closed(false) { _rpc.Register(&_inquire, "CM::Inquire"); _rpc.Register(&_close, "CM::Close"); _rpc.Register(&_connect, "CM::Connect"); _rpc.Register(&_disconnect, "CM::Disconnect"); Connection *con = _con_tab.GetConnection(_local_id); con->SetSink(&_rpc); QObject::connect(con->GetEdge().data(), SIGNAL(Closed(const QString &)), this, SLOT(HandleEdgeClose(const QString &))); QObject::connect(con, SIGNAL(CalledDisconnect()), this, SLOT(HandleDisconnect())); QObject::connect(con, SIGNAL(Disconnected(const QString &)), this, SLOT(HandleDisconnected(const QString &))); } ConnectionManager::~ConnectionManager() { _rpc.Unregister("CM::Inquire"); _rpc.Unregister("CM::Close"); _rpc.Unregister("CM::Connect"); _rpc.Unregister("CM::Disconnect"); } void ConnectionManager::AddEdgeListener(QSharedPointer<EdgeListener> el) { if(_closed) { qWarning() << "Attempting to add an EdgeListener after calling Disconnect."; return; } _edge_factory.AddEdgeListener(el); QObject::connect(el.data(), SIGNAL(NewEdge(QSharedPointer<Edge>)), this, SLOT(HandleNewEdge(QSharedPointer<Edge>))); QObject::connect(el.data(), SIGNAL(EdgeCreationFailure(const Address &, const QString &)), this, SLOT(HandleEdgeCreationFailure(const Address &, const QString&))); } void ConnectionManager::ConnectTo(const Address &addr) { if(_closed) { qWarning() << "Attempting to Connect to a remote node after calling Disconnect."; return; } if(_outstanding_con_attempts.contains(addr)) { qDebug() << "Attempting to connect multiple times to the same address:" << addr.ToString(); return; } _outstanding_con_attempts[addr] = true; if(!_edge_factory.CreateEdgeTo(addr)) { _outstanding_con_attempts.remove(addr); emit ConnectionAttemptFailure(addr, "No EdgeListener to handle request"); } } void ConnectionManager::Disconnect() { if(_closed) { qWarning() << "Called Disconnect twice on ConnectionManager."; return; } _closed = true; bool emit_dis = (_con_tab.GetEdges().count() == 0); foreach(Connection *con, _con_tab.GetConnections()) { con->Disconnect(); } foreach(QSharedPointer<Edge> edge, _con_tab.GetEdges()) { if(!edge->IsClosed()) { edge->Close("Disconnecting"); } } _edge_factory.Stop(); if(emit_dis) { emit Disconnected(); } } void ConnectionManager::HandleNewEdge(QSharedPointer<Edge> edge) { _con_tab.AddEdge(edge); edge->SetSink(&_rpc); QObject::connect(edge.data(), SIGNAL(Closed(const QString &)), this, SLOT(HandleEdgeClose(const QString &))); if(!edge->Outbound()) { return; } if(_outstanding_con_attempts.remove(edge->GetRemoteAddress()) == 0) { qDebug() << "No record of attempting connection to" << edge->GetRemoteAddress().ToString(); } QVariantMap request; request["method"] = "CM::Inquire"; request["peer_id"] = _local_id.GetByteArray(); QString type = edge->GetLocalAddress().GetType(); QSharedPointer<EdgeListener> el = _edge_factory.GetEdgeListener(type); request["persistent"] = el->GetAddress().ToString(); _rpc.SendRequest(request, edge.data(), &_inquired); } void ConnectionManager::HandleEdgeCreationFailure(const Address &to, const QString &reason) { _outstanding_con_attempts.remove(to); emit ConnectionAttemptFailure(to, reason); } void ConnectionManager::Inquire(RpcRequest &request) { Dissent::Messaging::ISender *from = request.GetFrom(); Edge *edge = dynamic_cast<Edge *>(from); if(edge == 0) { qWarning() << "Received an inquired from a non-Edge: " << from->ToString(); return; } else if(edge->Outbound()) { qWarning() << "We should never receive an inquire call on an outbound edge: " << from->ToString(); return; } QByteArray brem_id = request.GetMessage()["peer_id"].toByteArray(); if(brem_id.isEmpty()) { qWarning() << "Invalid Inqiure, no id"; return; } Id rem_id(brem_id); QVariantMap response; response["peer_id"] = _local_id.GetByteArray(); request.Respond(response); QString saddr = request.GetMessage()["persistent"].toString(); Address addr = AddressFactory::GetInstance().CreateAddress(saddr); edge->SetRemotePersistentAddress(addr); if(_local_id < rem_id) { BindEdge(edge, rem_id); } else if(_local_id == rem_id) { edge->Close("Attempting to connect to ourself"); } } void ConnectionManager::Inquired(RpcRequest &response) { Dissent::Messaging::ISender *from = response.GetFrom(); Edge *edge = dynamic_cast<Edge *>(from); if(edge == 0) { qWarning() << "Received an inquired from a non-Edge: " << from->ToString(); return; } else if(!edge->Outbound()) { qWarning() << "We would never make an inquire call on an incoming edge: " << from->ToString(); return; } QByteArray brem_id = response.GetMessage()["peer_id"].toByteArray(); if(brem_id.isEmpty()) { qWarning() << "Invalid ConnectionEstablished, no id"; return; } Id rem_id(brem_id); if(_local_id < rem_id) { BindEdge(edge, rem_id); } else if(rem_id == _local_id) { Address addr = edge->GetRemoteAddress(); qDebug() << "Attempting to connect to ourself"; edge->Close("Attempting to connect to ourself"); emit ConnectionAttemptFailure(addr, "Attempting to connect to ourself"); return; } } void ConnectionManager::BindEdge(Edge *edge, const Id &rem_id) { /// @TODO add an extra variable to the connection message such as a session ///token so that quick reconnects can be enabled. if(_con_tab.GetConnection(rem_id) != 0) { qWarning() << "Already have a connection to: " << rem_id.ToString() << " closing Edge: " << edge->ToString(); QVariantMap notification; notification["method"] = "CM::Close"; _rpc.SendNotification(notification, edge); Address addr = edge->GetRemoteAddress(); edge->Close("Duplicate connection"); emit ConnectionAttemptFailure(addr, "Duplicate connection"); return; } QSharedPointer<Edge> pedge = _con_tab.GetEdge(edge); if(pedge.isNull()) { qCritical() << "An edge attempted to create a connection, but there " "is no record of it" << edge->ToString(); return; } QVariantMap notification; notification["method"] = "CM::Connect"; notification["peer_id"] = _local_id.GetByteArray(); _rpc.SendNotification(notification, edge); CreateConnection(pedge, rem_id); } void ConnectionManager::Connect(RpcRequest &notification) { Edge *edge = dynamic_cast<Edge *>(notification.GetFrom()); if(edge == 0) { qWarning() << "Connection attempt not from an Edge: " << notification.GetFrom()->ToString(); return; } QByteArray brem_id = notification.GetMessage()["peer_id"].toByteArray(); if(brem_id.isEmpty()) { qWarning() << "Invalid ConnectionEstablished, no id"; return; } Id rem_id(brem_id); if(_local_id < rem_id) { qWarning() << "We should be sending CM::Connect, not the remote side."; return; } Connection *old_con = _con_tab.GetConnection(rem_id); // XXX if there is an old connection and the node doesn't want it, we need // to close it if(old_con != 0) { qDebug() << "Disconnecting old connection"; old_con->Disconnect(); } QSharedPointer<Edge> pedge = _con_tab.GetEdge(edge); if(pedge.isNull()) { qCritical() << "An edge attempted to create a connection, but there " "is no record of it" << edge->ToString(); return; } CreateConnection(pedge, rem_id); } void ConnectionManager::CreateConnection(QSharedPointer<Edge> pedge, const Id &rem_id) { Connection *con = new Connection(pedge, _local_id, rem_id); _con_tab.AddConnection(con); qDebug() << "Handle new connection:" << con->ToString(); QObject::connect(con, SIGNAL(CalledDisconnect()), this, SLOT(HandleDisconnect())); QObject::connect(con, SIGNAL(Disconnected(const QString &)), this, SLOT(HandleDisconnected(const QString &))); emit NewConnection(con); } void ConnectionManager::Close(RpcRequest &notification) { Edge *edge = dynamic_cast<Edge *>(notification.GetFrom()); if(edge == 0) { qWarning() << "Connection attempt Edge close not from an Edge: " << notification.GetFrom()->ToString(); return; } edge->Close("Closed from remote peer"); } void ConnectionManager::HandleDisconnect() { Connection *con = qobject_cast<Connection *>(sender()); if(con == 0) { return; } qDebug() << "Handle disconnect on: " << con->ToString(); _con_tab.Disconnect(con); if(!con->GetEdge()->IsClosed()) { if(con->GetLocalId() != con->GetRemoteId()) { QVariantMap notification; notification["method"] = "CM::Disconnect"; _rpc.SendNotification(notification, con); } con->GetEdge()->Close("Local disconnect request"); } } void ConnectionManager::HandleDisconnected(const QString &reason) { Connection *con = qobject_cast<Connection *>(sender()); qDebug() << "Edge disconnected now removing Connection: " << con->ToString() << ", because: " << reason; _con_tab.RemoveConnection(con); } void ConnectionManager::Disconnect(RpcRequest &notification) { Connection *con = dynamic_cast<Connection *>(notification.GetFrom()); if(con == 0) { qWarning() << "Received DisconnectResponse from a non-connection: " << notification.GetFrom()->ToString(); return; } qDebug() << "Received disconnect for: " << con->ToString(); _con_tab.Disconnect(con); con->GetEdge()->Close("Remote disconnect"); } void ConnectionManager::HandleEdgeClose(const QString &reason) { Edge *edge = qobject_cast<Edge *>(sender()); qDebug() << "Edge closed: " << edge->ToString() << reason; if(!_con_tab.RemoveEdge(edge)) { qWarning() << "Edge closed but no Edge found in CT:" << edge->ToString(); } Connection *con = _con_tab.GetConnection(edge); if(con != 0) { con = _con_tab.GetConnection(con->GetRemoteId()); if(con != 0) { con->Disconnect(); } } if(!_closed) { return; } if(_con_tab.GetEdges().count() == 0) { emit Disconnected(); } } } } <|endoftext|>
<commit_before>#include <CQIllustratorSelection.h> #include <CQIllustrator.h> #include <CQIllustratorShape.h> #include <CQIllustratorShapeControlLine.h> CQIllustratorSelectedShapes:: CQIllustratorSelectedShapes(CQIllustrator *illustrator) : illustrator_(illustrator), locked_(false) { } void CQIllustratorSelectedShapes:: clear() { shapes_.clear(); emit selectionChanged(); } void CQIllustratorSelectedShapes:: startSelect() { assert(! locked_); locked_ = true; } void CQIllustratorSelectedShapes:: endSelect() { assert(locked_); locked_ = false; emit selectionChanged(); } void CQIllustratorSelectedShapes:: add(CQIllustratorShape *shape) { if (exists(shape)) return; shapes_.push_back(CQIllustratorSelectedShape(shape)); if (! locked_) emit selectionChanged(); } void CQIllustratorSelectedShapes:: remove(iterator i) { shapes_.erase(i); if (! locked_) emit selectionChanged(); } bool CQIllustratorSelectedShapes:: exists(const CQIllustratorShape *shape) const { SelectedShapes::const_iterator p1, p2; for (p1 = shapes_.begin(), p2 = shapes_.end(); p1 != p2; ++p1) { if ((*p1).getShape()->getId() == shape->getId()) return true; } return false; } bool CQIllustratorSelectedShapes:: exists(const CQIllustratorShape *shape, const CQIllustratorShapeControlPoint *point) const { SelectedShapes::const_iterator p1, p2; for (p1 = shapes_.begin(), p2 = shapes_.end(); p1 != p2; ++p1) { if ((*p1).getShape()->getId() == shape->getId() && (*p1).exists(point)) return true; } return false; } CQIllustratorSelectedShape & CQIllustratorSelectedShapes:: get(CQIllustratorShape *shape) { SelectedShapes::iterator p1, p2; for (p1 = shapes_.begin(), p2 = shapes_.end(); p1 != p2; ++p1) { if ((*p1).getShape()->getId() == shape->getId()) return *p1; } assert(false); } CQIllustratorSelectedShape & CQIllustratorSelectedShapes:: checkoutShape(const CQIllustratorSelectedShape &sshape, CQIllustratorData::ChangeType changeType) { CQIllustratorSelectedShape &sshape1 = const_cast<CQIllustratorSelectedShape &>(sshape); CQIllustratorShape *shape = sshape1.getShape(); illustrator_->checkoutShape(shape, changeType); return sshape1; } void CQIllustratorSelectedShapes:: checkinShape(const CQIllustratorSelectedShape &sshape, CQIllustratorData::ChangeType changeType) { CQIllustratorShape *shape = const_cast<CQIllustratorShape *>(sshape.getShape()); illustrator_->checkinShape(shape, changeType); if (! locked_) emit selectionChanged(); } //---- void CQIllustratorSelectedShapes:: clearShapeLines(CQIllustratorSelectedShape &shape) { shape.clearLines(); if (! locked_) emit selectionChanged(); } void CQIllustratorSelectedShapes:: addShapeLine(CQIllustratorSelectedShape &shape, CQIllustratorShapeControlLine *line) { shape.addLine(line); if (! locked_) emit selectionChanged(); } void CQIllustratorSelectedShapes:: removeShapeLine(CQIllustratorSelectedShape &shape, CQIllustratorShapeControlLine *line) { shape.removeLine(line); if (! locked_) emit selectionChanged(); } void CQIllustratorSelectedShapes:: setShapeLine(CQIllustratorSelectedShape &shape, uint i, const CLine2D &l) { CQIllustratorShapeControlLine *line = shape.getLine(i); line->setLine(shape.getShape(), l); if (! locked_) emit selectionChanged(); } //---- void CQIllustratorSelectedShapes:: clearShapePoints(CQIllustratorSelectedShape &shape) { shape.clearPoints(); if (! locked_) emit selectionChanged(); } void CQIllustratorSelectedShapes:: addShapePoint(CQIllustratorSelectedShape &shape, CQIllustratorShapeControlPoint *point) { shape.addPoint(point); if (! locked_) emit selectionChanged(); } void CQIllustratorSelectedShapes:: removeShapePoint(CQIllustratorSelectedShape &shape, CQIllustratorShapeControlPoint *point) { shape.removePoint(point); if (! locked_) emit selectionChanged(); } //------------- CQIllustratorSelectedShape:: CQIllustratorSelectedShape(CQIllustratorShape *shape) : shape_(shape), points_() { } CQIllustratorSelectedShape:: ~CQIllustratorSelectedShape() { clearPoints(); } CQIllustratorShape * CQIllustratorSelectedShape:: getShape() { return shape_; } const CQIllustratorShape * CQIllustratorSelectedShape:: getShape() const { return shape_; } //---- void CQIllustratorSelectedShape:: clearLines() { uint num = lines_.size(); for (uint i = 0; i < num; ++i) delete lines_[i]; lines_.clear(); } void CQIllustratorSelectedShape:: addLine(CQIllustratorShapeControlLine *line) { lines_.push_back(line->dup()); } void CQIllustratorSelectedShape:: removeLine(CQIllustratorShapeControlLine *line) { uint num = lines_.size(); uint i = 0; for ( ; i < num; ++i) if (line->getId() == lines_[i]->getId()) break; if (i < num) { ++i; for ( ; i < num; ++i) lines_[i - 1] = lines_[i]; lines_.pop_back(); } } bool CQIllustratorSelectedShape:: exists(const CQIllustratorShapeControlLine *line) const { uint num = lines_.size(); for (uint i = 0; i < num; ++i) if (line->getId() == lines_[i]->getId()) return true;; return false; } uint CQIllustratorSelectedShape:: numLines() const { return lines_.size(); } const CQIllustratorShapeControlLine * CQIllustratorSelectedShape:: getLine(uint i) const { return lines_[i]; } CQIllustratorShapeControlLine * CQIllustratorSelectedShape:: getLine(uint i) { return lines_[i]; } //---- void CQIllustratorSelectedShape:: clearPoints() { uint num = points_.size(); for (uint i = 0; i < num; ++i) delete points_[i]; points_.clear(); } void CQIllustratorSelectedShape:: addPoint(CQIllustratorShapeControlPoint *point) { points_.push_back(point->dup()); } void CQIllustratorSelectedShape:: removePoint(CQIllustratorShapeControlPoint *point) { uint num = points_.size(); uint i = 0; for ( ; i < num; ++i) if (point->getId() == points_[i]->getId()) break; if (i < num) { ++i; for ( ; i < num; ++i) points_[i - 1] = points_[i]; points_.pop_back(); } } bool CQIllustratorSelectedShape:: exists(const CQIllustratorShapeControlPoint *point) const { uint num = points_.size(); for (uint i = 0; i < num; ++i) if (point->getId() == points_[i]->getId()) return true;; return false; } uint CQIllustratorSelectedShape:: numPoints() const { return points_.size(); } const CQIllustratorShapeControlPoint * CQIllustratorSelectedShape:: getPoint(uint i) const { return points_[i]; } CQIllustratorShapeControlPoint * CQIllustratorSelectedShape:: getPoint(uint i) { return points_[i]; } <commit_msg>new files<commit_after>#include <CQIllustratorSelection.h> #include <CQIllustrator.h> #include <CQIllustratorShape.h> #include <CQIllustratorShapeControlLine.h> CQIllustratorSelectedShapes:: CQIllustratorSelectedShapes(CQIllustrator *illustrator) : illustrator_(illustrator), locked_(false) { } void CQIllustratorSelectedShapes:: clear() { shapes_.clear(); emit selectionChanged(); } void CQIllustratorSelectedShapes:: startSelect() { assert(! locked_); locked_ = true; } void CQIllustratorSelectedShapes:: endSelect() { assert(locked_); locked_ = false; emit selectionChanged(); } void CQIllustratorSelectedShapes:: add(CQIllustratorShape *shape) { if (exists(shape)) return; shapes_.push_back(CQIllustratorSelectedShape(shape)); if (! locked_) emit selectionChanged(); } void CQIllustratorSelectedShapes:: remove(iterator i) { shapes_.erase(i); if (! locked_) emit selectionChanged(); } bool CQIllustratorSelectedShapes:: exists(const CQIllustratorShape *shape) const { SelectedShapes::const_iterator p1, p2; for (p1 = shapes_.begin(), p2 = shapes_.end(); p1 != p2; ++p1) { if ((*p1).getShape()->getId() == shape->getId()) return true; } return false; } bool CQIllustratorSelectedShapes:: exists(const CQIllustratorShape *shape, const CQIllustratorShapeControlPoint *point) const { SelectedShapes::const_iterator p1, p2; for (p1 = shapes_.begin(), p2 = shapes_.end(); p1 != p2; ++p1) { if ((*p1).getShape()->getId() == shape->getId() && (*p1).exists(point)) return true; } return false; } CQIllustratorSelectedShape & CQIllustratorSelectedShapes:: get(CQIllustratorShape *shape) { SelectedShapes::iterator p1, p2; for (p1 = shapes_.begin(), p2 = shapes_.end(); p1 != p2; ++p1) { if ((*p1).getShape()->getId() == shape->getId()) return *p1; } assert(false); } CQIllustratorSelectedShape & CQIllustratorSelectedShapes:: checkoutShape(const CQIllustratorSelectedShape &sshape, CQIllustratorData::ChangeType changeType) { CQIllustratorSelectedShape &sshape1 = const_cast<CQIllustratorSelectedShape &>(sshape); CQIllustratorShape *shape = sshape1.getShape(); illustrator_->checkoutShape(shape, changeType); return sshape1; } void CQIllustratorSelectedShapes:: checkinShape(const CQIllustratorSelectedShape &sshape, CQIllustratorData::ChangeType changeType) { CQIllustratorShape *shape = const_cast<CQIllustratorShape *>(sshape.getShape()); illustrator_->checkinShape(shape, changeType); if (! locked_) emit selectionChanged(); } //---- void CQIllustratorSelectedShapes:: clearShapeLines(CQIllustratorSelectedShape &shape) { shape.clearLines(); if (! locked_) emit selectionChanged(); } void CQIllustratorSelectedShapes:: addShapeLine(CQIllustratorSelectedShape &shape, CQIllustratorShapeControlLine *line) { shape.addLine(line); if (! locked_) emit selectionChanged(); } void CQIllustratorSelectedShapes:: removeShapeLine(CQIllustratorSelectedShape &shape, CQIllustratorShapeControlLine *line) { shape.removeLine(line); if (! locked_) emit selectionChanged(); } void CQIllustratorSelectedShapes:: setShapeLine(CQIllustratorSelectedShape &shape, uint i, const CLine2D &l) { CQIllustratorShapeControlLine *line = shape.getLine(i); line->setLine(shape.getShape(), l); if (! locked_) emit selectionChanged(); } //---- void CQIllustratorSelectedShapes:: clearShapePoints(CQIllustratorSelectedShape &shape) { shape.clearPoints(); if (! locked_) emit selectionChanged(); } void CQIllustratorSelectedShapes:: addShapePoint(CQIllustratorSelectedShape &shape, CQIllustratorShapeControlPoint *point) { shape.addPoint(point); if (! locked_) emit selectionChanged(); } void CQIllustratorSelectedShapes:: removeShapePoint(CQIllustratorSelectedShape &shape, CQIllustratorShapeControlPoint *point) { shape.removePoint(point); if (! locked_) emit selectionChanged(); } //------------- CQIllustratorSelectedShape:: CQIllustratorSelectedShape(CQIllustratorShape *shape) : shape_(shape), points_() { } CQIllustratorSelectedShape:: ~CQIllustratorSelectedShape() { clearPoints(); } CQIllustratorShape * CQIllustratorSelectedShape:: getShape() { return shape_; } const CQIllustratorShape * CQIllustratorSelectedShape:: getShape() const { return shape_; } //---- void CQIllustratorSelectedShape:: clearLines() { uint num = lines_.size(); for (uint i = 0; i < num; ++i) delete lines_[i]; lines_.clear(); } void CQIllustratorSelectedShape:: addLine(CQIllustratorShapeControlLine *line) { lines_.push_back(line->dup()); } void CQIllustratorSelectedShape:: removeLine(CQIllustratorShapeControlLine *line) { uint num = lines_.size(); uint i = 0; for ( ; i < num; ++i) if (line->getId() == lines_[i]->getId()) break; if (i < num) { ++i; for ( ; i < num; ++i) lines_[i - 1] = lines_[i]; lines_.pop_back(); } } bool CQIllustratorSelectedShape:: exists(const CQIllustratorShapeControlLine *line) const { uint num = lines_.size(); for (uint i = 0; i < num; ++i) if (line->getId() == lines_[i]->getId()) return true; return false; } uint CQIllustratorSelectedShape:: numLines() const { return lines_.size(); } const CQIllustratorShapeControlLine * CQIllustratorSelectedShape:: getLine(uint i) const { return lines_[i]; } CQIllustratorShapeControlLine * CQIllustratorSelectedShape:: getLine(uint i) { return lines_[i]; } //---- void CQIllustratorSelectedShape:: clearPoints() { uint num = points_.size(); for (uint i = 0; i < num; ++i) delete points_[i]; points_.clear(); } void CQIllustratorSelectedShape:: addPoint(CQIllustratorShapeControlPoint *point) { points_.push_back(point->dup()); } void CQIllustratorSelectedShape:: removePoint(CQIllustratorShapeControlPoint *point) { uint num = points_.size(); uint i = 0; for ( ; i < num; ++i) if (point->getId() == points_[i]->getId()) break; if (i < num) { ++i; for ( ; i < num; ++i) points_[i - 1] = points_[i]; points_.pop_back(); } } bool CQIllustratorSelectedShape:: exists(const CQIllustratorShapeControlPoint *point) const { uint num = points_.size(); for (uint i = 0; i < num; ++i) if (point->getId() == points_[i]->getId()) return true; return false; } uint CQIllustratorSelectedShape:: numPoints() const { return points_.size(); } const CQIllustratorShapeControlPoint * CQIllustratorSelectedShape:: getPoint(uint i) const { return points_[i]; } CQIllustratorShapeControlPoint * CQIllustratorSelectedShape:: getPoint(uint i) { return points_[i]; } <|endoftext|>
<commit_before>/* Copyright (c) 2011 Cody Miller, Daniel Norris, Brett Hitchcock. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *****************************************************************************/ #include "Terrain.h" TerrainGenerator::TerrainGenerator(Ogre::SceneManager *scene) : terrains_imported_(false), scene_manager_(scene) { /*mCamera->setPosition(Ogre::Vector3(1683, 50, 2116)); mCamera->lookAt(Ogre::Vector3(1963, 50, 1660)); mCamera->setNearClipDistance(0.1); mCamera->setFarClipDistance(50000);*/ Ogre::MaterialManager::getSingleton().setDefaultTextureFiltering(Ogre::TFO_ANISOTROPIC); Ogre::MaterialManager::getSingleton().setDefaultAnisotropy(7); Ogre::Light* light = scene_manager_->createLight("tstLight"); light->setDiffuseColour(Ogre::ColourValue::White); light->setSpecularColour(Ogre::ColourValue(1, 1, 1)); scene_manager_->setAmbientLight(Ogre::ColourValue(1.0, 1.0, 1.0)); light->setAttenuation(100000, 1, 1, 1); terrain_globals_ = OGRE_NEW Ogre::TerrainGlobalOptions(); terrain_group_ = OGRE_NEW Ogre::TerrainGroup(scene_manager_, Ogre::Terrain::ALIGN_X_Z, 513, 12000.0f); terrain_group_->setFilenameConvention(Ogre::String("BasicTutorial3Terrain"), Ogre::String("dat")); terrain_group_->setOrigin(Ogre::Vector3::ZERO); configureTerrainDefaults(light); for (long x = 0; x <= 0; ++x) for (long y = 0; y <= 0; ++y) defineTerrain(x, y); // sync load since we want everything in place when we start terrain_group_->loadAllTerrains(true); if (terrains_imported_) { Ogre::TerrainGroup::TerrainIterator ti = terrain_group_->getTerrainIterator(); while(ti.hasMoreElements()) { Ogre::Terrain* t = ti.getNext()->instance; t->setPosition(Ogre::Vector3::ZERO); initBlendMaps(t); } } terrain_group_->freeTemporaryResources(); scene_manager_->setSkyDome(true, "Examples/CloudySky", 5, 8); //Optional skybox //Graphics::instance()->getSceneManager()->setSkyDome(true, "Examples/CloudySky", 5, 8); } TerrainGenerator::~TerrainGenerator() { } void TerrainGenerator::getTerrainImage(bool flipX, bool flipY, Ogre::Image& img) { img.load("terrain.png", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); if (flipX) img.flipAroundY(); if (flipY) img.flipAroundX(); } void TerrainGenerator::defineTerrain(long x, long y) { Ogre::String filename = terrain_group_->generateFilename(x, y); if (Ogre::ResourceGroupManager::getSingleton().resourceExists(terrain_group_->getResourceGroup(), filename)) terrain_group_->defineTerrain(x, y); else { Ogre::Image img; getTerrainImage(x % 2 != 0, y % 2 != 0, img); terrain_group_->defineTerrain(x, y, &img); terrains_imported_ = true; } } void TerrainGenerator::initBlendMaps(Ogre::Terrain *terrain) { Ogre::TerrainLayerBlendMap* blendMap0 = terrain->getLayerBlendMap(1); Ogre::TerrainLayerBlendMap* blendMap1 = terrain->getLayerBlendMap(2); Ogre::Real minHeight0 = 70; Ogre::Real fadeDist0 = 40; Ogre::Real minHeight1 = 70; Ogre::Real fadeDist1 = 15; float* pBlend1 = blendMap1->getBlendPointer(); for (Ogre::uint16 y = 0; y < terrain->getLayerBlendMapSize(); ++y) { for (Ogre::uint16 x = 0; x < terrain->getLayerBlendMapSize(); ++x) { Ogre::Real tx, ty; blendMap0->convertImageToTerrainSpace(x, y, &tx, &ty); Ogre::Real height = terrain->getHeightAtTerrainPosition(tx, ty); Ogre::Real val = (height - minHeight0) / fadeDist0; val = Ogre::Math::Clamp(val, (Ogre::Real)0, (Ogre::Real)1); val = (height - minHeight1) / fadeDist1; val = Ogre::Math::Clamp(val, (Ogre::Real)0, (Ogre::Real)1); *pBlend1++ = val; } } blendMap0->dirty(); blendMap1->dirty(); blendMap0->update(); blendMap1->update(); } void TerrainGenerator::configureTerrainDefaults(Ogre::Light *light) { // Configure global terrain_globals_->setMaxPixelError(8); // testing composite map terrain_globals_->setCompositeMapDistance(3000); // Important to set these so that the terrain knows what to use for derived (non-realtime) data terrain_globals_->setLightMapDirection(light->getDerivedDirection()); terrain_globals_->setCompositeMapAmbient(scene_manager_->getAmbientLight()); terrain_globals_->setCompositeMapDiffuse(light->getDiffuseColour()); // Configure default import settings for if we use imported image Ogre::Terrain::ImportData& defaultimp = terrain_group_->getDefaultImportSettings(); defaultimp.terrainSize = 513; defaultimp.worldSize = 12000.0f; defaultimp.inputScale = 600; defaultimp.minBatchSize = 33; defaultimp.maxBatchSize = 65; // textures defaultimp.layerList.resize(3); defaultimp.layerList[0].worldSize = 100; defaultimp.layerList[0].textureNames.push_back("dirt_grayrocky_diffusespecular.dds"); defaultimp.layerList[0].textureNames.push_back("dirt_grayrocky_normalheight.dds"); defaultimp.layerList[1].worldSize = 30; defaultimp.layerList[1].textureNames.push_back("grass_green-01_diffusespecular.dds"); defaultimp.layerList[1].textureNames.push_back("grass_green-01_normalheight.dds"); defaultimp.layerList[2].worldSize = 200; defaultimp.layerList[2].textureNames.push_back("growth_weirdfungus-03_diffusespecular.dds"); defaultimp.layerList[2].textureNames.push_back("growth_weirdfungus-03_normalheight.dds"); } <commit_msg>Moves the Terrain down to the ocean level.<commit_after>/* Copyright (c) 2011 Cody Miller, Daniel Norris, Brett Hitchcock. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *****************************************************************************/ #include "Terrain.h" TerrainGenerator::TerrainGenerator(Ogre::SceneManager *scene) : terrains_imported_(false), scene_manager_(scene) { /*mCamera->setPosition(Ogre::Vector3(1683, 50, 2116)); mCamera->lookAt(Ogre::Vector3(1963, 50, 1660)); mCamera->setNearClipDistance(0.1); mCamera->setFarClipDistance(50000);*/ Ogre::MaterialManager::getSingleton().setDefaultTextureFiltering(Ogre::TFO_ANISOTROPIC); Ogre::MaterialManager::getSingleton().setDefaultAnisotropy(7); Ogre::Light* light = scene_manager_->createLight("tstLight"); light->setDiffuseColour(Ogre::ColourValue::White); light->setSpecularColour(Ogre::ColourValue(1, 1, 1)); scene_manager_->setAmbientLight(Ogre::ColourValue(1.0, 1.0, 1.0)); light->setAttenuation(100000, 1, 1, 1); terrain_globals_ = OGRE_NEW Ogre::TerrainGlobalOptions(); terrain_group_ = OGRE_NEW Ogre::TerrainGroup(scene_manager_, Ogre::Terrain::ALIGN_X_Z, 513, 12000.0f); terrain_group_->setFilenameConvention(Ogre::String("BasicTutorial3Terrain"), Ogre::String("dat")); terrain_group_->setOrigin(Ogre::Vector3::ZERO); configureTerrainDefaults(light); for (long x = 0; x <= 0; ++x) for (long y = 0; y <= 0; ++y) defineTerrain(x, y); // sync load since we want everything in place when we start terrain_group_->loadAllTerrains(true); if (terrains_imported_) { Ogre::TerrainGroup::TerrainIterator ti = terrain_group_->getTerrainIterator(); while(ti.hasMoreElements()) { Ogre::Terrain* t = ti.getNext()->instance; t->setPosition(Ogre::Vector3(0, -305, 0)); initBlendMaps(t); } } terrain_group_->freeTemporaryResources(); scene_manager_->setSkyDome(true, "Examples/CloudySky", 5, 8); //Optional skybox //Graphics::instance()->getSceneManager()->setSkyDome(true, "Examples/CloudySky", 5, 8); } TerrainGenerator::~TerrainGenerator() { } void TerrainGenerator::getTerrainImage(bool flipX, bool flipY, Ogre::Image& img) { img.load("terrain.png", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); if (flipX) img.flipAroundY(); if (flipY) img.flipAroundX(); } void TerrainGenerator::defineTerrain(long x, long y) { Ogre::String filename = terrain_group_->generateFilename(x, y); if (Ogre::ResourceGroupManager::getSingleton().resourceExists(terrain_group_->getResourceGroup(), filename)) terrain_group_->defineTerrain(x, y); else { Ogre::Image img; getTerrainImage(x % 2 != 0, y % 2 != 0, img); terrain_group_->defineTerrain(x, y, &img); terrains_imported_ = true; } } void TerrainGenerator::initBlendMaps(Ogre::Terrain *terrain) { Ogre::TerrainLayerBlendMap* blendMap0 = terrain->getLayerBlendMap(1); Ogre::TerrainLayerBlendMap* blendMap1 = terrain->getLayerBlendMap(2); Ogre::Real minHeight0 = 70; Ogre::Real fadeDist0 = 40; Ogre::Real minHeight1 = 70; Ogre::Real fadeDist1 = 15; float* pBlend1 = blendMap1->getBlendPointer(); for (Ogre::uint16 y = 0; y < terrain->getLayerBlendMapSize(); ++y) { for (Ogre::uint16 x = 0; x < terrain->getLayerBlendMapSize(); ++x) { Ogre::Real tx, ty; blendMap0->convertImageToTerrainSpace(x, y, &tx, &ty); Ogre::Real height = terrain->getHeightAtTerrainPosition(tx, ty); Ogre::Real val = (height - minHeight0) / fadeDist0; val = Ogre::Math::Clamp(val, (Ogre::Real)0, (Ogre::Real)1); val = (height - minHeight1) / fadeDist1; val = Ogre::Math::Clamp(val, (Ogre::Real)0, (Ogre::Real)1); *pBlend1++ = val; } } blendMap0->dirty(); blendMap1->dirty(); blendMap0->update(); blendMap1->update(); } void TerrainGenerator::configureTerrainDefaults(Ogre::Light *light) { // Configure global terrain_globals_->setMaxPixelError(8); // testing composite map terrain_globals_->setCompositeMapDistance(3000); // Important to set these so that the terrain knows what to use for derived (non-realtime) data terrain_globals_->setLightMapDirection(light->getDerivedDirection()); terrain_globals_->setCompositeMapAmbient(scene_manager_->getAmbientLight()); terrain_globals_->setCompositeMapDiffuse(light->getDiffuseColour()); // Configure default import settings for if we use imported image Ogre::Terrain::ImportData& defaultimp = terrain_group_->getDefaultImportSettings(); defaultimp.terrainSize = 513; defaultimp.worldSize = 12000.0f; defaultimp.inputScale = 600; defaultimp.minBatchSize = 33; defaultimp.maxBatchSize = 65; // textures defaultimp.layerList.resize(3); defaultimp.layerList[0].worldSize = 100; defaultimp.layerList[0].textureNames.push_back("dirt_grayrocky_diffusespecular.dds"); defaultimp.layerList[0].textureNames.push_back("dirt_grayrocky_normalheight.dds"); defaultimp.layerList[1].worldSize = 30; defaultimp.layerList[1].textureNames.push_back("grass_green-01_diffusespecular.dds"); defaultimp.layerList[1].textureNames.push_back("grass_green-01_normalheight.dds"); defaultimp.layerList[2].worldSize = 200; defaultimp.layerList[2].textureNames.push_back("growth_weirdfungus-03_diffusespecular.dds"); defaultimp.layerList[2].textureNames.push_back("growth_weirdfungus-03_normalheight.dds"); } <|endoftext|>
<commit_before>/* * Copyright (C) FFLAS-FFPACK * Written by Hongguang ZHU <[email protected]> * This file is Free Software and part of FFLAS-FFPACK. * * ========LICENCE======== * This file is part of the library FFLAS-FFPACK. * * FFLAS-FFPACK is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ========LICENCE======== *. */ //#define __FFLASFFPACK_SEQUENTIAL //#define ENABLE_ALL_CHECKINGS 1 //#include "fflas-ffpack/fflas-ffpack-config.h" #include <givaro/modular-integer.h> #include <iomanip> #include <iostream> #include "fflas-ffpack/utils/timer.h" #include "fflas-ffpack/fflas/fflas.h" #include "fflas-ffpack/utils/args-parser.h" #include "fflas-ffpack/utils/test-utils.h" #include <givaro/modular.h> #include <givaro/modular-balanced.h> using namespace std; using namespace FFLAS; using namespace FFPACK; using Givaro::Modular; using Givaro::ModularBalanced; template<typename Field, class Cut, class Param> void run_solve(const Field &F, size_t m, typename Field::Element_ptr A, const size_t lda, typename Field::Element_ptr x, const int incx, typename Field::ConstElement_ptr b, const int incb, const FFLAS::ParSeqHelper::Parallel<Cut,Param>& parH) { FFPACK::pSolve(F, m, A, lda, x, incx, b, incb); } template<typename Field> void run_solve(const Field &F, size_t m, typename Field::Element_ptr A, const size_t lda, typename Field::Element_ptr x, const int incx, typename Field::ConstElement_ptr b, const int incb, const FFLAS::ParSeqHelper::Sequential& seqH) { FFPACK::Solve(F, m, A, lda, x, incx, b, incb); } template<typename Field, class RandIter, class PSHelper> bool check_solve(const Field &F, size_t m, RandIter& Rand, const PSHelper& psH){ typename Field::Element_ptr A, A2, B, B2, x; size_t lda,incb,incx; lda=m; incb=1; incx=1; A = FFLAS::fflas_new(F,m,lda); A2 = FFLAS::fflas_new(F,m,lda); B = FFLAS::fflas_new(F,m,incb); B2 = FFLAS::fflas_new(F,m,incb); x = FFLAS::fflas_new(F,m,incx); RandomMatrixWithRank (F, m, m, m, A, lda, Rand); RandomMatrix (F, m, 1, B, incb, Rand); FFLAS::fassign (F, m, B, incb, B2, incb); FFLAS::fassign (F, m, m, A, lda, A2, lda); #ifdef DEBUG FFLAS::WriteMatrix(std::cout<<"b:="<<std::endl,F,m,1,B,incb)<<std::endl; #endif FFLAS::Timer t; t.clear(); double time=0.0; t.clear(); t.start(); run_solve(F, m, A, lda, x, incx, B, incb, psH); t.stop(); time+=t.realtime(); FFLAS::fgemv(F, FFLAS::FflasNoTrans, m, m, F.one, A2, lda, x, incx, F.zero, B, incb); bool ok = true; if (FFLAS::fequal (F, m, 1, B2, incb, B, incb)){ cout << " PASSED ("<<time<<")"; } else{ #ifdef DEBUG FFLAS::WriteMatrix(std::cout<<"A*x:="<<std::endl,F,m,1,B2,incb)<<std::endl; FFLAS::WriteMatrix(std::cout<<"b:="<<std::endl,F,m,1,B,incb)<<std::endl; #endif cout << " FAILED ("<<time<<")"; ok=false; } FFLAS::fflas_delete(A); FFLAS::fflas_delete(A2); FFLAS::fflas_delete(B); FFLAS::fflas_delete(B2); FFLAS::fflas_delete(x); return ok; } template <class Field> bool run_with_field (Givaro::Integer q, size_t b, size_t m, size_t iters, uint64_t seed){ bool ok = true ; int nbit=(int)iters; while (ok && nbit){ //typedef typename Field::Element Element ; // choose Field Field* F= chooseField<Field>(q,b,seed); typename Field::RandIter G(*F,0,seed++); if (F==nullptr) return true; std::ostringstream oss; F->write(oss); std::cout.fill('.'); std::cout<<"Checking "; std::cout.width(50); std::cout<<oss.str(); std::cout<<" ... "; // testing a sequential run std::cout<<" seq: "; ok = ok && check_solve(*F,m,G, FFLAS::ParSeqHelper::Sequential()); // testing a parallel run std::cout<<" par: "; ok = ok && check_solve(*F,m,G, FFLAS::ParSeqHelper::Parallel<FFLAS::CuttingStrategy::Recursive,FFLAS::StrategyParameter::Threads>()); std::cout<<std::endl; nbit--; delete F; } return ok; } int main(int argc, char** argv) { cerr<<setprecision(10); Givaro::Integer q=-1; size_t b=0; size_t m=1000; size_t iters=4; bool loop=false; uint64_t seed = getSeed(); Argument as[] = { { 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INTEGER , &q }, { 'b', "-b B", "Set the bitsize of the field characteristic.", TYPE_INT , &b }, { 'm', "-m M", "Set the dimension of unknown square matrix.", TYPE_INT , &m }, { 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iters }, { 'l', "-loop Y/N", "run the test in an infinite loop.", TYPE_BOOL , &loop }, { 's', "-s seed", "Set seed for the random generator", TYPE_UINT64, &seed }, END_OF_ARGUMENTS }; FFLAS::parseArguments(argc,argv,as); bool ok = true; do{ ok = ok && run_with_field<Modular<double> >(q,b,m,iters,seed); ok = ok && run_with_field<ModularBalanced<double> >(q,b,m,iters,seed); ok = ok && run_with_field<Modular<float> >(q,b,m,iters,seed); ok = ok && run_with_field<ModularBalanced<float> >(q,b,m,iters,seed); ok = ok && run_with_field<Modular<int32_t> >(q,b,m,iters,seed); ok = ok && run_with_field<ModularBalanced<int32_t> >(q,b,m,iters,seed); ok = ok && run_with_field<Modular<int64_t> >(q,b,m,iters,seed); ok = ok && run_with_field<ModularBalanced<int64_t> >(q,b,m,iters,seed); ok = ok &&run_with_field<Givaro::Modular<Givaro::Integer> > (q,5,m/6,iters,seed); ok = ok &&run_with_field<Givaro::Modular<Givaro::Integer> > (q,(b?b:512),m/6,iters,seed); } while (loop && ok); return !ok ; } /* -*- mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ // vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s <commit_msg>cleaned up the test-solve according to comments after code review<commit_after>/* * Copyright (C) FFLAS-FFPACK * Written by Hongguang ZHU <[email protected]> * This file is Free Software and part of FFLAS-FFPACK. * * ========LICENCE======== * This file is part of the library FFLAS-FFPACK. * * FFLAS-FFPACK is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ========LICENCE======== *. */ //#define __FFLASFFPACK_SEQUENTIAL //#define ENABLE_ALL_CHECKINGS 1 //#include "fflas-ffpack/fflas-ffpack-config.h" #include <givaro/modular-integer.h> #include <iomanip> #include <iostream> #include "fflas-ffpack/utils/timer.h" #include "fflas-ffpack/fflas/fflas.h" #include "fflas-ffpack/utils/args-parser.h" #include "fflas-ffpack/utils/test-utils.h" #include <givaro/modular.h> #include <givaro/modular-balanced.h> using namespace std; using namespace FFLAS; using namespace FFPACK; using Givaro::Modular; using Givaro::ModularBalanced; template<typename Field, class RandIter> bool check_solve(const Field &F, size_t m, RandIter& Rand, bool isParallel){ typename Field::Element_ptr A, A2, B, B2, x; size_t lda,incb,incx; lda=m; incb=1; incx=1; A = FFLAS::fflas_new(F,m,lda); A2 = FFLAS::fflas_new(F,m,lda); B = FFLAS::fflas_new(F,m,incb); B2 = FFLAS::fflas_new(F,m,incb); x = FFLAS::fflas_new(F,m,incx); RandomMatrixWithRank (F, m, m, m, A, lda, Rand); RandomMatrix (F, m, 1, B, incb, Rand); FFLAS::fassign (F, m, B, incb, B2, incb); FFLAS::fassign (F, m, m, A, lda, A2, lda); #ifdef DEBUG FFLAS::WriteMatrix(std::cout<<"b:="<<std::endl,F,m,1,B,incb)<<std::endl; #endif FFLAS::Timer t; t.clear(); double time=0.0; t.clear(); t.start(); if(isParallel){ FFPACK::pSolve(F, m, A, lda, x, incx, B, incb); }else{ FFPACK::Solve(F, m, A, lda, x, incx, B, incb); } t.stop(); time+=t.realtime(); FFLAS::fgemv(F, FFLAS::FflasNoTrans, m, m, F.one, A2, lda, x, incx, F.zero, B, incb); bool ok = true; if (FFLAS::fequal (F, m, 1, B2, incb, B, incb)){ cout << " PASSED ("<<time<<")"; } else{ #ifdef DEBUG FFLAS::WriteMatrix(std::cout<<"A*x:="<<std::endl,F,m,1,B2,incb)<<std::endl; FFLAS::WriteMatrix(std::cout<<"b:="<<std::endl,F,m,1,B,incb)<<std::endl; #endif cout << " FAILED ("<<time<<")"; ok=false; } FFLAS::fflas_delete(A); FFLAS::fflas_delete(A2); FFLAS::fflas_delete(B); FFLAS::fflas_delete(B2); FFLAS::fflas_delete(x); return ok; } template <class Field> bool run_with_field (Givaro::Integer q, size_t b, size_t m, size_t iters, uint64_t seed){ bool ok = true ; int nbit=(int)iters; while (ok && nbit){ //typedef typename Field::Element Element ; // choose Field Field* F= chooseField<Field>(q,b,seed); typename Field::RandIter G(*F,0,seed++); if (F==nullptr) return true; std::ostringstream oss; F->write(oss); std::cout.fill('.'); std::cout<<"Checking "; std::cout.width(50); std::cout<<oss.str(); std::cout<<" ... "; // testing a sequential run std::cout<<" seq: "; ok = ok && check_solve(*F,m,G,false); // testing a parallel run std::cout<<" par: "; ok = ok && check_solve(*F,m,G,true); std::cout<<std::endl; nbit--; delete F; } return ok; } int main(int argc, char** argv) { cerr<<setprecision(10); Givaro::Integer q=-1; size_t b=0; size_t m=1000; size_t iters=4; bool loop=false; uint64_t seed = getSeed(); Argument as[] = { { 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INTEGER , &q }, { 'b', "-b B", "Set the bitsize of the field characteristic.", TYPE_INT , &b }, { 'm', "-m M", "Set the dimension of unknown square matrix.", TYPE_INT , &m }, { 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iters }, { 'l', "-loop Y/N", "run the test in an infinite loop.", TYPE_BOOL , &loop }, { 's', "-s seed", "Set seed for the random generator", TYPE_UINT64, &seed }, END_OF_ARGUMENTS }; FFLAS::parseArguments(argc,argv,as); bool ok = true; do{ ok = ok && run_with_field<Modular<double> >(q,b,m,iters,seed); ok = ok && run_with_field<ModularBalanced<double> >(q,b,m,iters,seed); ok = ok && run_with_field<Modular<float> >(q,b,m,iters,seed); ok = ok && run_with_field<ModularBalanced<float> >(q,b,m,iters,seed); ok = ok && run_with_field<Modular<int32_t> >(q,b,m,iters,seed); ok = ok && run_with_field<ModularBalanced<int32_t> >(q,b,m,iters,seed); ok = ok && run_with_field<Modular<int64_t> >(q,b,m,iters,seed); ok = ok && run_with_field<ModularBalanced<int64_t> >(q,b,m,iters,seed); ok = ok &&run_with_field<Givaro::Modular<Givaro::Integer> > (q,5,m/6,iters,seed); ok = ok &&run_with_field<Givaro::Modular<Givaro::Integer> > (q,(b?b:512),m/6,iters,seed); } while (loop && ok); return !ok ; } /* -*- mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ // vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s <|endoftext|>
<commit_before>/* OpenSceneGraph example, osgparticle. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <osgViewer/Viewer> #include <osg/Group> #include <osg/Geode> #include <osgParticle/Particle> #include <osgParticle/ParticleSystem> #include <osgParticle/ParticleSystemUpdater> #include <osgParticle/ModularEmitter> #include <osgParticle/ModularProgram> #include <osgParticle/RandomRateCounter> #include <osgParticle/SectorPlacer> #include <osgParticle/RadialShooter> #include <osgParticle/AccelOperator> #include <osgParticle/FluidFrictionOperator> ////////////////////////////////////////////////////////////////////////////// // CUSTOM OPERATOR CLASS ////////////////////////////////////////////////////////////////////////////// // This class demonstrates Operator subclassing. This way you can create // custom operators to apply your motion effects to the particles. See docs // for more details. class VortexOperator: public osgParticle::Operator { public: VortexOperator() : osgParticle::Operator(), center_(0, 0, 0), axis_(0, 0, 1), intensity_(0.1f) {} VortexOperator(const VortexOperator &copy, const osg::CopyOp &copyop = osg::CopyOp::SHALLOW_COPY) : osgParticle::Operator(copy, copyop), center_(copy.center_), axis_(copy.axis_), intensity_(copy.intensity_) {} META_Object(osgParticle, VortexOperator); void setCenter(const osg::Vec3 &c) { center_ = c; } void setAxis(const osg::Vec3 &a) { axis_ = a / a.length(); } // this method is called by ModularProgram before applying // operators on the particle set via the operate() method. void beginOperate(osgParticle::Program *prg) { // we have to check whether the reference frame is RELATIVE_RF to parents // or it's absolute; in the first case, we must transform the vectors // from local to world space. if (prg->getReferenceFrame() == osgParticle::Program::RELATIVE_RF) { // transform the center point (full transformation) xf_center_ = prg->transformLocalToWorld(center_); // transform the axis vector (only rotation and scale) xf_axis_ = prg->rotateLocalToWorld(axis_); } else { xf_center_ = center_; xf_axis_ = axis_; } } // apply a vortex-like acceleration. This code is not optimized, // it's here only for demonstration purposes. void operate(osgParticle::Particle *P, double dt) { float l = xf_axis_ * (P->getPosition() - xf_center_); osg::Vec3 lc = xf_center_ + xf_axis_ * l; osg::Vec3 R = P->getPosition() - lc; osg::Vec3 v = (R ^ xf_axis_) * P->getMassInv() * intensity_; // compute new position osg::Vec3 newpos = P->getPosition() + v * dt; // update the position of the particle without modifying its // velocity vector (this is unusual, normally you should call // the Particle::setVelocity() or Particle::addVelocity() // methods). P->setPosition(newpos); } protected: virtual ~VortexOperator() {} private: osg::Vec3 center_; osg::Vec3 xf_center_; osg::Vec3 axis_; osg::Vec3 xf_axis_; float intensity_; }; ////////////////////////////////////////////////////////////////////////////// // SIMPLE PARTICLE SYSTEM CREATION ////////////////////////////////////////////////////////////////////////////// osgParticle::ParticleSystem *create_simple_particle_system(osg::Group *root) { // Ok folks, this is the first particle system we build; it will be // very simple, with no textures and no special effects, just default // values except for a couple of attributes. // First of all, we create the ParticleSystem object; it will hold // our particles and expose the interface for managing them; this object // is a Drawable, so we'll have to add it to a Geode later. osgParticle::ParticleSystem *ps = new osgParticle::ParticleSystem; // As for other Drawable classes, the aspect of graphical elements of // ParticleSystem (the particles) depends on the StateAttribute's we // give it. The ParticleSystem class has an helper function that let // us specify a set of the most common attributes: setDefaultAttributes(). // This method can accept up to three parameters; the first is a texture // name (std::string), which can be empty to disable texturing, the second // sets whether particles have to be "emissive" (additive blending) or not; // the third parameter enables or disables lighting. ps->setDefaultAttributes("", true, false); // Now that our particle system is set we have to create an emitter, that is // an object (actually a Node descendant) that generate new particles at // each frame. The best choice is to use a ModularEmitter, which allow us to // achieve a wide variety of emitting styles by composing the emitter using // three objects: a "counter", a "placer" and a "shooter". The counter must // tell the ModularEmitter how many particles it has to create for the // current frame; then, the ModularEmitter creates these particles, and for // each new particle it instructs the placer and the shooter to set its // position vector and its velocity vector, respectively. // By default, a ModularEmitter object initializes itself with a counter of // type RandomRateCounter, a placer of type PointPlacer and a shooter of // type RadialShooter (see documentation for details). We are going to leave // these default objects there, but we'll modify the counter so that it // counts faster (more particles are emitted at each frame). osgParticle::ModularEmitter *emitter = new osgParticle::ModularEmitter; // the first thing you *MUST* do after creating an emitter is to set the // destination particle system, otherwise it won't know where to create // new particles. emitter->setParticleSystem(ps); // Ok, get a pointer to the emitter's Counter object. We could also // create a new RandomRateCounter object and assign it to the emitter, // but since the default counter is already a RandomRateCounter, we // just get a pointer to it and change a value. osgParticle::RandomRateCounter *rrc = static_cast<osgParticle::RandomRateCounter *>(emitter->getCounter()); // Now set the rate range to a better value. The actual rate at each frame // will be chosen randomly within that range. rrc->setRateRange(20, 30); // generate 20 to 30 particles per second // The emitter is done! Let's add it to the scene graph. The cool thing is // that any emitter node will take into account the accumulated local-to-world // matrix, so you can attach an emitter to a transform node and see it move. root->addChild(emitter); // Ok folks, we have almost finished. We don't add any particle modifier // here (see ModularProgram and Operator classes), so all we still need is // to create a Geode and add the particle system to it, so it can be // displayed. osg::Geode *geode = new osg::Geode; geode->addDrawable(ps); // add the geode to the scene graph root->addChild(geode); return ps; } ////////////////////////////////////////////////////////////////////////////// // COMPLEX PARTICLE SYSTEM CREATION ////////////////////////////////////////////////////////////////////////////// osgParticle::ParticleSystem *create_complex_particle_system(osg::Group *root) { // Are you ready for a more complex particle system? Well, read on! // Now we take one step we didn't before: create a particle template. // A particle template is simply a Particle object for which you set // the desired properties (see documentation for details). When the // particle system has to create a new particle and it's been assigned // a particle template, the new particle will inherit the template's // properties. // You can even assign different particle templates to each emitter; in // this case, the emitter's template will override the particle system's // default template. osgParticle::Particle ptemplate; ptemplate.setLifeTime(3); // 3 seconds of life // the following ranges set the envelope of the respective // graphical properties in time. ptemplate.setSizeRange(osgParticle::rangef(0.75f, 3.0f)); ptemplate.setAlphaRange(osgParticle::rangef(0.0f, 1.5f)); ptemplate.setColorRange(osgParticle::rangev4( osg::Vec4(1, 0.5f, 0.3f, 1.5f), osg::Vec4(0, 0.7f, 1.0f, 0.0f))); // these are physical properties of the particle ptemplate.setRadius(0.05f); // 5 cm wide particles ptemplate.setMass(0.05f); // 50 g heavy // As usual, let's create the ParticleSystem object and set its // default state attributes. This time we use a texture named // "smoke.rgb", you can find it in the data distribution of OSG. // We turn off the additive blending, because smoke has no self- // illumination. osgParticle::ParticleSystem *ps = new osgParticle::ParticleSystem; ps->setDefaultAttributes("Images/smoke.rgb", false, false); // assign the particle template to the system. ps->setDefaultParticleTemplate(ptemplate); // now we have to create an emitter; this will be a ModularEmitter, for which // we define a RandomRateCounter as counter, a SectorPlacer as placer, and // a RadialShooter as shooter. osgParticle::ModularEmitter *emitter = new osgParticle::ModularEmitter; emitter->setParticleSystem(ps); // setup the counter osgParticle::RandomRateCounter *counter = new osgParticle::RandomRateCounter; counter->setRateRange(60, 60); emitter->setCounter(counter); // setup the placer; it will be a circle of radius 5 (the particles will // be placed inside this circle). osgParticle::SectorPlacer *placer = new osgParticle::SectorPlacer; placer->setCenter(8, 0, 10); placer->setRadiusRange(2.5, 5); placer->setPhiRange(0, 2 * osg::PI); // 360 angle to make a circle emitter->setPlacer(placer); // now let's setup the shooter; we use a RadialShooter but we set the // initial speed to zero, because we want the particles to fall down // only under the effect of the gravity force. Since we se the speed // to zero, there is no need to setup the shooting angles. osgParticle::RadialShooter *shooter = new osgParticle::RadialShooter; shooter->setInitialSpeedRange(0, 0); emitter->setShooter(shooter); // add the emitter to the scene graph root->addChild(emitter); // WELL, we got our particle system and a nice emitter. Now we want to // simulate the effect of the earth gravity, so first of all we have to // create a Program. It is a particle processor just like the Emitter // class, but it allows to modify particle properties *after* they have // been created. // The ModularProgram class can be thought as a sequence of operators, // each one performing some actions on the particles. So, the trick is: // create the ModularProgram object, create one or more Operator objects, // add those operators to the ModularProgram, and finally add the // ModularProgram object to the scene graph. // NOTE: since the Program objects perform actions after the particles // have been emitted by one or more Emitter objects, all instances of // Program (and its descendants) should be placed *after* the instances // of Emitter objects in the scene graph. osgParticle::ModularProgram *program = new osgParticle::ModularProgram; program->setParticleSystem(ps); // create an operator that simulates the gravity acceleration. osgParticle::AccelOperator *op1 = new osgParticle::AccelOperator; op1->setToGravity(); program->addOperator(op1); // now create a custom operator, we have defined it before (see // class VortexOperator). VortexOperator *op2 = new VortexOperator; op2->setCenter(osg::Vec3(8, 0, 0)); program->addOperator(op2); // let's add a fluid operator to simulate air friction. osgParticle::FluidFrictionOperator *op3 = new osgParticle::FluidFrictionOperator; op3->setFluidToAir(); program->addOperator(op3); // add the program to the scene graph root->addChild(program); // create a Geode to contain our particle system. osg::Geode *geode = new osg::Geode; geode->addDrawable(ps); // add the geode to the scene graph. root->addChild(geode); return ps; } ////////////////////////////////////////////////////////////////////////////// // MAIN SCENE GRAPH BUILDING FUNCTION ////////////////////////////////////////////////////////////////////////////// void build_world(osg::Group *root) { // In this function we are going to create two particle systems; // the first one will be very simple, based mostly on default properties; // the second one will be a little bit more complex, showing how to // create custom operators. // To avoid inserting too much code in a single function, we have // splitted the work into two functions which accept a Group node as // parameter, and return a pointer to the particle system they created. osgParticle::ParticleSystem *ps1 = create_simple_particle_system(root); osgParticle::ParticleSystem *ps2 = create_complex_particle_system(root); // Now that the particle systems and all other related objects have been // created, we have to add an "updater" node to the scene graph. This node // will react to cull traversal by updating the specified particles system. osgParticle::ParticleSystemUpdater *psu = new osgParticle::ParticleSystemUpdater; psu->addParticleSystem(ps1); psu->addParticleSystem(ps2); // add the updater node to the scene graph root->addChild(psu); } ////////////////////////////////////////////////////////////////////////////// // main() ////////////////////////////////////////////////////////////////////////////// int main(int, char **) { // construct the viewer. osgViewer::Viewer viewer; osg::Group *root = new osg::Group; build_world(root); // add a viewport to the viewer and attach the scene graph. viewer.setSceneData(root); return viewer.run(); } <commit_msg>Added stats handler to track performance effects of new GLBeginEndAdapter usage<commit_after>/* OpenSceneGraph example, osgparticle. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <osgViewer/Viewer> #include <osgViewer/ViewerEventHandlers> #include <osg/Group> #include <osg/Geode> #include <osgParticle/Particle> #include <osgParticle/ParticleSystem> #include <osgParticle/ParticleSystemUpdater> #include <osgParticle/ModularEmitter> #include <osgParticle/ModularProgram> #include <osgParticle/RandomRateCounter> #include <osgParticle/SectorPlacer> #include <osgParticle/RadialShooter> #include <osgParticle/AccelOperator> #include <osgParticle/FluidFrictionOperator> ////////////////////////////////////////////////////////////////////////////// // CUSTOM OPERATOR CLASS ////////////////////////////////////////////////////////////////////////////// // This class demonstrates Operator subclassing. This way you can create // custom operators to apply your motion effects to the particles. See docs // for more details. class VortexOperator: public osgParticle::Operator { public: VortexOperator() : osgParticle::Operator(), center_(0, 0, 0), axis_(0, 0, 1), intensity_(0.1f) {} VortexOperator(const VortexOperator &copy, const osg::CopyOp &copyop = osg::CopyOp::SHALLOW_COPY) : osgParticle::Operator(copy, copyop), center_(copy.center_), axis_(copy.axis_), intensity_(copy.intensity_) {} META_Object(osgParticle, VortexOperator); void setCenter(const osg::Vec3 &c) { center_ = c; } void setAxis(const osg::Vec3 &a) { axis_ = a / a.length(); } // this method is called by ModularProgram before applying // operators on the particle set via the operate() method. void beginOperate(osgParticle::Program *prg) { // we have to check whether the reference frame is RELATIVE_RF to parents // or it's absolute; in the first case, we must transform the vectors // from local to world space. if (prg->getReferenceFrame() == osgParticle::Program::RELATIVE_RF) { // transform the center point (full transformation) xf_center_ = prg->transformLocalToWorld(center_); // transform the axis vector (only rotation and scale) xf_axis_ = prg->rotateLocalToWorld(axis_); } else { xf_center_ = center_; xf_axis_ = axis_; } } // apply a vortex-like acceleration. This code is not optimized, // it's here only for demonstration purposes. void operate(osgParticle::Particle *P, double dt) { float l = xf_axis_ * (P->getPosition() - xf_center_); osg::Vec3 lc = xf_center_ + xf_axis_ * l; osg::Vec3 R = P->getPosition() - lc; osg::Vec3 v = (R ^ xf_axis_) * P->getMassInv() * intensity_; // compute new position osg::Vec3 newpos = P->getPosition() + v * dt; // update the position of the particle without modifying its // velocity vector (this is unusual, normally you should call // the Particle::setVelocity() or Particle::addVelocity() // methods). P->setPosition(newpos); } protected: virtual ~VortexOperator() {} private: osg::Vec3 center_; osg::Vec3 xf_center_; osg::Vec3 axis_; osg::Vec3 xf_axis_; float intensity_; }; ////////////////////////////////////////////////////////////////////////////// // SIMPLE PARTICLE SYSTEM CREATION ////////////////////////////////////////////////////////////////////////////// osgParticle::ParticleSystem *create_simple_particle_system(osg::Group *root) { // Ok folks, this is the first particle system we build; it will be // very simple, with no textures and no special effects, just default // values except for a couple of attributes. // First of all, we create the ParticleSystem object; it will hold // our particles and expose the interface for managing them; this object // is a Drawable, so we'll have to add it to a Geode later. osgParticle::ParticleSystem *ps = new osgParticle::ParticleSystem; // As for other Drawable classes, the aspect of graphical elements of // ParticleSystem (the particles) depends on the StateAttribute's we // give it. The ParticleSystem class has an helper function that let // us specify a set of the most common attributes: setDefaultAttributes(). // This method can accept up to three parameters; the first is a texture // name (std::string), which can be empty to disable texturing, the second // sets whether particles have to be "emissive" (additive blending) or not; // the third parameter enables or disables lighting. ps->setDefaultAttributes("", true, false); // Now that our particle system is set we have to create an emitter, that is // an object (actually a Node descendant) that generate new particles at // each frame. The best choice is to use a ModularEmitter, which allow us to // achieve a wide variety of emitting styles by composing the emitter using // three objects: a "counter", a "placer" and a "shooter". The counter must // tell the ModularEmitter how many particles it has to create for the // current frame; then, the ModularEmitter creates these particles, and for // each new particle it instructs the placer and the shooter to set its // position vector and its velocity vector, respectively. // By default, a ModularEmitter object initializes itself with a counter of // type RandomRateCounter, a placer of type PointPlacer and a shooter of // type RadialShooter (see documentation for details). We are going to leave // these default objects there, but we'll modify the counter so that it // counts faster (more particles are emitted at each frame). osgParticle::ModularEmitter *emitter = new osgParticle::ModularEmitter; // the first thing you *MUST* do after creating an emitter is to set the // destination particle system, otherwise it won't know where to create // new particles. emitter->setParticleSystem(ps); // Ok, get a pointer to the emitter's Counter object. We could also // create a new RandomRateCounter object and assign it to the emitter, // but since the default counter is already a RandomRateCounter, we // just get a pointer to it and change a value. osgParticle::RandomRateCounter *rrc = static_cast<osgParticle::RandomRateCounter *>(emitter->getCounter()); // Now set the rate range to a better value. The actual rate at each frame // will be chosen randomly within that range. rrc->setRateRange(20, 30); // generate 20 to 30 particles per second // The emitter is done! Let's add it to the scene graph. The cool thing is // that any emitter node will take into account the accumulated local-to-world // matrix, so you can attach an emitter to a transform node and see it move. root->addChild(emitter); // Ok folks, we have almost finished. We don't add any particle modifier // here (see ModularProgram and Operator classes), so all we still need is // to create a Geode and add the particle system to it, so it can be // displayed. osg::Geode *geode = new osg::Geode; geode->addDrawable(ps); // add the geode to the scene graph root->addChild(geode); return ps; } ////////////////////////////////////////////////////////////////////////////// // COMPLEX PARTICLE SYSTEM CREATION ////////////////////////////////////////////////////////////////////////////// osgParticle::ParticleSystem *create_complex_particle_system(osg::Group *root) { // Are you ready for a more complex particle system? Well, read on! // Now we take one step we didn't before: create a particle template. // A particle template is simply a Particle object for which you set // the desired properties (see documentation for details). When the // particle system has to create a new particle and it's been assigned // a particle template, the new particle will inherit the template's // properties. // You can even assign different particle templates to each emitter; in // this case, the emitter's template will override the particle system's // default template. osgParticle::Particle ptemplate; ptemplate.setLifeTime(3); // 3 seconds of life // the following ranges set the envelope of the respective // graphical properties in time. ptemplate.setSizeRange(osgParticle::rangef(0.75f, 3.0f)); ptemplate.setAlphaRange(osgParticle::rangef(0.0f, 1.5f)); ptemplate.setColorRange(osgParticle::rangev4( osg::Vec4(1, 0.5f, 0.3f, 1.5f), osg::Vec4(0, 0.7f, 1.0f, 0.0f))); // these are physical properties of the particle ptemplate.setRadius(0.05f); // 5 cm wide particles ptemplate.setMass(0.05f); // 50 g heavy // As usual, let's create the ParticleSystem object and set its // default state attributes. This time we use a texture named // "smoke.rgb", you can find it in the data distribution of OSG. // We turn off the additive blending, because smoke has no self- // illumination. osgParticle::ParticleSystem *ps = new osgParticle::ParticleSystem; ps->setDefaultAttributes("Images/smoke.rgb", false, false); // assign the particle template to the system. ps->setDefaultParticleTemplate(ptemplate); // now we have to create an emitter; this will be a ModularEmitter, for which // we define a RandomRateCounter as counter, a SectorPlacer as placer, and // a RadialShooter as shooter. osgParticle::ModularEmitter *emitter = new osgParticle::ModularEmitter; emitter->setParticleSystem(ps); // setup the counter osgParticle::RandomRateCounter *counter = new osgParticle::RandomRateCounter; counter->setRateRange(60, 60); emitter->setCounter(counter); // setup the placer; it will be a circle of radius 5 (the particles will // be placed inside this circle). osgParticle::SectorPlacer *placer = new osgParticle::SectorPlacer; placer->setCenter(8, 0, 10); placer->setRadiusRange(2.5, 5); placer->setPhiRange(0, 2 * osg::PI); // 360 angle to make a circle emitter->setPlacer(placer); // now let's setup the shooter; we use a RadialShooter but we set the // initial speed to zero, because we want the particles to fall down // only under the effect of the gravity force. Since we se the speed // to zero, there is no need to setup the shooting angles. osgParticle::RadialShooter *shooter = new osgParticle::RadialShooter; shooter->setInitialSpeedRange(0, 0); emitter->setShooter(shooter); // add the emitter to the scene graph root->addChild(emitter); // WELL, we got our particle system and a nice emitter. Now we want to // simulate the effect of the earth gravity, so first of all we have to // create a Program. It is a particle processor just like the Emitter // class, but it allows to modify particle properties *after* they have // been created. // The ModularProgram class can be thought as a sequence of operators, // each one performing some actions on the particles. So, the trick is: // create the ModularProgram object, create one or more Operator objects, // add those operators to the ModularProgram, and finally add the // ModularProgram object to the scene graph. // NOTE: since the Program objects perform actions after the particles // have been emitted by one or more Emitter objects, all instances of // Program (and its descendants) should be placed *after* the instances // of Emitter objects in the scene graph. osgParticle::ModularProgram *program = new osgParticle::ModularProgram; program->setParticleSystem(ps); // create an operator that simulates the gravity acceleration. osgParticle::AccelOperator *op1 = new osgParticle::AccelOperator; op1->setToGravity(); program->addOperator(op1); // now create a custom operator, we have defined it before (see // class VortexOperator). VortexOperator *op2 = new VortexOperator; op2->setCenter(osg::Vec3(8, 0, 0)); program->addOperator(op2); // let's add a fluid operator to simulate air friction. osgParticle::FluidFrictionOperator *op3 = new osgParticle::FluidFrictionOperator; op3->setFluidToAir(); program->addOperator(op3); // add the program to the scene graph root->addChild(program); // create a Geode to contain our particle system. osg::Geode *geode = new osg::Geode; geode->addDrawable(ps); // add the geode to the scene graph. root->addChild(geode); return ps; } ////////////////////////////////////////////////////////////////////////////// // MAIN SCENE GRAPH BUILDING FUNCTION ////////////////////////////////////////////////////////////////////////////// void build_world(osg::Group *root) { // In this function we are going to create two particle systems; // the first one will be very simple, based mostly on default properties; // the second one will be a little bit more complex, showing how to // create custom operators. // To avoid inserting too much code in a single function, we have // splitted the work into two functions which accept a Group node as // parameter, and return a pointer to the particle system they created. osgParticle::ParticleSystem *ps1 = create_simple_particle_system(root); osgParticle::ParticleSystem *ps2 = create_complex_particle_system(root); // Now that the particle systems and all other related objects have been // created, we have to add an "updater" node to the scene graph. This node // will react to cull traversal by updating the specified particles system. osgParticle::ParticleSystemUpdater *psu = new osgParticle::ParticleSystemUpdater; psu->addParticleSystem(ps1); psu->addParticleSystem(ps2); // add the updater node to the scene graph root->addChild(psu); } ////////////////////////////////////////////////////////////////////////////// // main() ////////////////////////////////////////////////////////////////////////////// int main(int, char **) { // construct the viewer. osgViewer::Viewer viewer; osg::Group *root = new osg::Group; build_world(root); // add the stats handler viewer.addEventHandler(new osgViewer::StatsHandler); // add a viewport to the viewer and attach the scene graph. viewer.setSceneData(root); return viewer.run(); } <|endoftext|>
<commit_before>#include "evolve.h" extern double eTable[26][26]; // English contact table extern double cTable[26][26]; // Cipher contact table extern vector < keyFitType > population; // The population of possible keys // Uses index to select character from key for fitness evaluation // NOTE: does not bounds check, if theres bug it'll probably happen here inline int encode( int index, string key ) { return (int)(convert(key[index])); // Converts char to int (ASCII 'a' - 97 = 0) } // end encode // Returns the fitness found using the currently selected fitness function double fitness( string key ) { if(FITNESS_FUNC == 0) return eFitness(key); else return bFitness(key); } // Fitness function using Euclidean distance // SMALLER IS BETTER FOR THIS FITNESS double eFitness( string key ) { double fit = 0.0; // Fitness for( int i = 0; i < 26; i++ ) { for( int j = 0; j < 26; j++ ) { if(eTable[i][j] != 0) fit += pow(( eTable[i][j] - cTable[encode(i, key)][encode(j, key)] ), 2); } } return fit; } // end eFitness // Fitness function using Bhatthacaryya distance // BIGGER IS BETTER FOR THIS FITNESS (oh yeah) double bFitness( string key ) { double fit = 0.0; // Fitness for( int i = 0; i < 26; i++ ) { for( int j = 0; j < 26; j++ ) { if(eTable[i][j] != 0) fit += sqrt(eTable[i][j] * cTable[encode(i, key)][encode(j, key)]); } } return fit; } // end bFitness // Combines genomes of parents using crossover function of choice into child void crossover( int parentA, int parentB, int child ) { // Order One Crossover if(CROSSOVER == 0) { } // PMX Crossover else if(CROSSOVER == 1) { pmx(parentA, parentB, child); } } // end crossover // Mutate chromosome in-place using permutation-based mutation operator void mutate( int chromosome ) { if(MUTATION == 0) { // Single Swap mutation swap(population[chromosome].key[randMod(26)], population[chromosome].key[randMod(26)]); } else if(MUTATION == 1) { // Swap twice swap(population[chromosome].key[randMod(26)], population[chromosome].key[randMod(26)]); swap(population[chromosome].key[randMod(26)], population[chromosome].key[randMod(26)]); } else if(MUTATION == 2) { // Three-point shift int a, b, c; swap(population[chromosome].key[a], population[chromosome].key[b]); } } // end mutate // Using a tournament selection to select parents out of the population, culls the weak (bwuahahha) // This is where we calculate the fitnesses // NOTE: Assumes a tourney size of three. This may (and probably should) change int select( int &parentA, int &parentB ) { int indicies[TSIZE]; int range[POPSIZE]; vector <indFitType> members; indFitType m; int temp = 0; // Randomly select a unique individual (spent more time on this than i should've...) for( int i = 0; i < POPSIZE; i++ ) range[i] = i; for( int i = 0; i < TSIZE; i++ ) { do { temp = randMod(POPSIZE); } while(range[temp] < 0); indicies[i] = range[temp]; range[temp] = -1; } // Setup the tournament, determining fitness of each contestant for( int i = 0; i < TSIZE; i++ ) { m.index = indicies[i]; m.fit = population[indicies[i]].fit; members.push_back(m); } // FIGHT! FIGHT FOR YOUR SURVIVAL! sort(members.begin(), members.end(), compSelect); // Winners circle parentA = members[0].index; parentB = members[1].index; // Losing individual will be overwritten by child...what a horrible fate return members[TSIZE - 1].index; } // Comparison function for sorting that changes based on fitness function used bool compSelect( indFitType a, indFitType b) { if(FITNESS_FUNC == 0) return (a.fit < b.fit); else return (a.fit > b.fit); } // Order One crossover - a fast permutation crossover. void orderOne( int parentA, int parentB, int child ) { } // PMX Crossover. Code derived from Robert Heckendorn's implementation found in pmx.cpp void pmx( int parentA, int parentB, int child ) { const double prob = 3.0 / 26.0; // Tweak this tweak the world bool pick[26]; int locA[26]; int locB[26]; string a = population[parentA].key; string b = population[parentB].key; string c(26, 'a'); // Temporary child string // Copy a random subnet (a "swath") of parent B for( int i = 0; i < 26; i++ ) { if(choose(prob)) { // Select what to copy from parent B pick[i] = true; c[i] = b[i]; } else { // Mark everything else as bad (-1) pick[i] = false; c[i] = -1; } // Location lookup table for A and B locA[convert(a[i])] = locB[convert(b[i])] = i; } // Remove duplicates for( int i = 0; i < 26; i++ ) { if( pick[i] && !pick[locB[convert(a[i])]] ) { int loc = i; do { loc = locA[convert(b[loc])]; } while( c[loc] != -1 ); c[loc] = a[i]; } } // Copy remaining genes from parent A for( int i = 0; i < 26; i++ ) { if( c[i] == -1 ) c[i] = a[i]; } // Put child into population population[child].key = c; } <commit_msg>opps<commit_after>#include "evolve.h" extern double eTable[26][26]; // English contact table extern double cTable[26][26]; // Cipher contact table extern vector < keyFitType > population; // The population of possible keys // Uses index to select character from key for fitness evaluation // NOTE: does not bounds check, if theres bug it'll probably happen here inline int encode( int index, string key ) { return (int)(convert(key[index])); // Converts char to int (ASCII 'a' - 97 = 0) } // end encode // Returns the fitness found using the currently selected fitness function double fitness( string key ) { if(FITNESS_FUNC == 0) return eFitness(key); else return bFitness(key); } // Fitness function using Euclidean distance // SMALLER IS BETTER FOR THIS FITNESS double eFitness( string key ) { double fit = 0.0; // Fitness for( int i = 0; i < 26; i++ ) { for( int j = 0; j < 26; j++ ) { if(eTable[i][j] != 0) fit += pow(( eTable[i][j] - cTable[encode(i, key)][encode(j, key)] ), 2); } } return fit; } // end eFitness // Fitness function using Bhatthacaryya distance // BIGGER IS BETTER FOR THIS FITNESS (oh yeah) double bFitness( string key ) { double fit = 0.0; // Fitness for( int i = 0; i < 26; i++ ) { for( int j = 0; j < 26; j++ ) { if(eTable[i][j] != 0) fit += sqrt(eTable[i][j] * cTable[encode(i, key)][encode(j, key)]); } } return fit; } // end bFitness // Combines genomes of parents using crossover function of choice into child void crossover( int parentA, int parentB, int child ) { // Order One Crossover if(CROSSOVER == 0) { } // PMX Crossover else if(CROSSOVER == 1) { pmx(parentA, parentB, child); } } // end crossover // Mutate chromosome in-place using permutation-based mutation operator void mutate( int chromosome ) { if(MUTATION == 0) { // Single Swap mutation swap(population[chromosome].key[randMod(26)], population[chromosome].key[randMod(26)]); } else if(MUTATION == 1) { // Swap twice swap(population[chromosome].key[randMod(26)], population[chromosome].key[randMod(26)]); swap(population[chromosome].key[randMod(26)], population[chromosome].key[randMod(26)]); } else if(MUTATION == 2) { // Three-point shift int a, b, c; a = randMod(26 - 2); do { b = randMod(26 - 1); } while(b <= a); do { c = randMod(26); } while(c <= b); char tempB = population[chromosome].key[b]; swap(population[chromosome].key[a], population[chromosome].key[b]); swap(population[chromosome].key[c], tempB ); } } // end mutate // Using a tournament selection to select parents out of the population, culls the weak (bwuahahha) // This is where we calculate the fitnesses // NOTE: Assumes a tourney size of three. This may (and probably should) change int select( int &parentA, int &parentB ) { int indicies[TSIZE]; int range[POPSIZE]; vector <indFitType> members; indFitType m; int temp = 0; // Randomly select a unique individual (spent more time on this than i should've...) for( int i = 0; i < POPSIZE; i++ ) range[i] = i; for( int i = 0; i < TSIZE; i++ ) { do { temp = randMod(POPSIZE); } while(range[temp] < 0); indicies[i] = range[temp]; range[temp] = -1; } // Setup the tournament, determining fitness of each contestant for( int i = 0; i < TSIZE; i++ ) { m.index = indicies[i]; m.fit = population[indicies[i]].fit; members.push_back(m); } // FIGHT! FIGHT FOR YOUR SURVIVAL! sort(members.begin(), members.end(), compSelect); // Winners circle parentA = members[0].index; parentB = members[1].index; // Losing individual will be overwritten by child...what a horrible fate return members[TSIZE - 1].index; } // Comparison function for sorting that changes based on fitness function used bool compSelect( indFitType a, indFitType b) { if(FITNESS_FUNC == 0) return (a.fit < b.fit); else return (a.fit > b.fit); } // Order One crossover - a fast permutation crossover. void orderOne( int parentA, int parentB, int child ) { } // PMX Crossover. Code derived from Robert Heckendorn's implementation found in pmx.cpp void pmx( int parentA, int parentB, int child ) { const double prob = 3.0 / 26.0; // Tweak this tweak the world bool pick[26]; int locA[26]; int locB[26]; string a = population[parentA].key; string b = population[parentB].key; string c(26, 'a'); // Temporary child string // Copy a random subnet (a "swath") of parent B for( int i = 0; i < 26; i++ ) { if(choose(prob)) { // Select what to copy from parent B pick[i] = true; c[i] = b[i]; } else { // Mark everything else as bad (-1) pick[i] = false; c[i] = -1; } // Location lookup table for A and B locA[convert(a[i])] = locB[convert(b[i])] = i; } // Remove duplicates for( int i = 0; i < 26; i++ ) { if( pick[i] && !pick[locB[convert(a[i])]] ) { int loc = i; do { loc = locA[convert(b[loc])]; } while( c[loc] != -1 ); c[loc] = a[i]; } } // Copy remaining genes from parent A for( int i = 0; i < 26; i++ ) { if( c[i] == -1 ) c[i] = a[i]; } // Put child into population population[child].key = c; } <|endoftext|>
<commit_before>#include "Game.h" #include "Player.h" #include "DrawComponent.h" #include <stdio.h> #include <SDL2/SDL.h> bool Game::inst_ = false; Game::Game() { if (!inst_) { window_ = NULL; renderer_ = NULL; entities_ = new Entity*[numEntities_]; for (int i = 0; i < numEntities_; i++) { entities_[i] = NULL; } running_ = false; inst_ = true; } } Game::~Game() { delete drawComponent_; delete[] entities_; SDL_DestroyWindow(window_); } bool Game::setup(const char* title, int xPos, int yPos, int width, int height, int flags) { if(SDL_Init(SDL_INIT_EVERYTHING) < 0) { printf("SDL could not initialize"); return false; } else { window_ = SDL_CreateWindow( title, xPos, yPos, width, height, flags ); if (window_ == NULL) { printf("SDL Window not initialized"); return false; } else { renderer_ = SDL_CreateRenderer(window_, -1, 0); if (renderer_ == NULL) { printf("SDL Renderer not initialized"); return false; } drawComponent_ = new DrawComponent(renderer_); //test code pls delete SDL_SetRenderDrawColor(renderer_, 0,0,0,255); running_ = true; printf("making the player.\n"); entities_[0] = new Player(drawComponent_); entities_[0]->setup(); printf("player made.\n"); return true; } } } void Game::handleInput() { SDL_Event event; if (SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: running_ = false; break; default: break; } } } void Game::update() { } void Game::draw() { SDL_RenderClear(renderer_); for (int i = 0; i < numEntities_; i++) { if (entities_[i] != NULL) { entities_[i]->draw(); } } SDL_RenderPresent(renderer_); } void Game::clean() { } <commit_msg>beginning to add keyboard input<commit_after>#include "Game.h" #include "Player.h" #include "DrawComponent.h" #include <stdio.h> #include <SDL2/SDL.h> bool Game::inst_ = false; Game::Game() { if (!inst_) { window_ = NULL; renderer_ = NULL; entities_ = new Entity*[numEntities_]; for (int i = 0; i < numEntities_; i++) { entities_[i] = NULL; } running_ = false; inst_ = true; } } Game::~Game() { delete drawComponent_; delete[] entities_; SDL_DestroyWindow(window_); } bool Game::setup(const char* title, int xPos, int yPos, int width, int height, int flags) { if(SDL_Init(SDL_INIT_EVERYTHING) < 0) { printf("SDL could not initialize"); return false; } else { window_ = SDL_CreateWindow( title, xPos, yPos, width, height, flags ); if (window_ == NULL) { printf("SDL Window not initialized"); return false; } else { renderer_ = SDL_CreateRenderer(window_, -1, 0); if (renderer_ == NULL) { printf("SDL Renderer not initialized"); return false; } drawComponent_ = new DrawComponent(renderer_); //test code pls delete SDL_SetRenderDrawColor(renderer_, 0,0,0,255); running_ = true; printf("making the player.\n"); entities_[0] = new Player(drawComponent_); entities_[0]->setup(); printf("player made.\n"); return true; } } } void Game::handleInput() { SDL_Event event; if (SDL_PollEvent(&event)) { if ( event.type == SDL_QUIT ) { running_ = false; } else if (event.type == SDL_KEYDOWN) { switch( event.key.keysym.sym) { case SDLK_w: printf("Pressed W\n"); default: break; } } } } void Game::update() { } void Game::draw() { SDL_RenderClear(renderer_); for (int i = 0; i < numEntities_; i++) { if (entities_[i] != NULL) { entities_[i]->draw(); } } SDL_RenderPresent(renderer_); } void Game::clean() { } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbImageKeywordlist.h" #include <cassert> #include "otbMacro.h" #include "ossim/base/ossimKeywordlist.h" #include "ossim/base/ossimString.h" #include "ossim/ossimPluginProjectionFactory.h" #include "ossim/imaging/ossimImageHandlerRegistry.h" #include "ossim/ossimTileMapModel.h" #include "ossim/projection/ossimProjectionFactoryRegistry.h" namespace otb { ImageKeywordlist ::ImageKeywordlist() { } ImageKeywordlist ::ImageKeywordlist(const Self& p) : m_Keywordlist(p.m_Keywordlist) { } ImageKeywordlist ::~ImageKeywordlist() { } void ImageKeywordlist:: operator =(const Self& p) { m_Keywordlist = p.m_Keywordlist; } void ImageKeywordlist:: SetKeywordlist(const ossimKeywordlist& kwl) { m_Keywordlist.clear(); for (ossimKeywordlist::KeywordMap::const_iterator it = kwl.getMap().begin(); it != kwl.getMap().end(); ++it) { std::string first(it->first); std::string second(it->second); m_Keywordlist[first] = second; } } const std::string& ImageKeywordlist:: GetMetadataByKey(const std::string& key) const { // Search for the key in the output map KeywordlistMap::const_iterator it = m_Keywordlist.find(key); // If the key can not be found, throw an exception if (it == m_Keywordlist.end()) { itkExceptionMacro(<< "Keywordlist has no output with key " << key); } // Then if everything is ok, return the ossinString return it->second; } bool ImageKeywordlist:: HasKey(const std::string& key) const { KeywordlistMap::const_iterator it = m_Keywordlist.find(key); return (it != m_Keywordlist.end()); } void ImageKeywordlist:: ClearMetadataByKey(const std::string& key) { m_Keywordlist[key] = ""; } void ImageKeywordlist:: AddKey(const std::string& key, const std::string& value) { m_Keywordlist[key] = value; } void ImageKeywordlist:: convertToOSSIMKeywordlist(ossimKeywordlist& kwl) const { ossimKeywordlist::KeywordMap ossimMap; for(KeywordlistMap::const_iterator it = m_Keywordlist.begin(); it != m_Keywordlist.end(); ++it) { ossimMap[it->first] = it->second; } kwl.getMap() = ossimMap; } void ImageKeywordlist:: Print(std::ostream& os, itk::Indent indent) const { this->PrintSelf(os, indent.GetNextIndent()); } void ImageKeywordlist:: PrintSelf(std::ostream& os, itk::Indent indent) const { ossimKeywordlist kwl; convertToOSSIMKeywordlist(kwl); os << indent << " Ossim Keyword list:" << std::endl; os << indent << kwl; } std::ostream & operator <<(std::ostream& os, const ImageKeywordlist& kwl) { kwl.Print(os); return os; } ImageKeywordlist ReadGeometry(const std::string& filename) { // Trying to read ossim MetaData bool hasMetaData = false; ossimKeywordlist geom_kwl; // = new ossimKeywordlist(); // Test the plugins factory /** Before, the pluginfactory was tested if the ossim one returned false. But in the case TSX, the images tif were considered as ossimQuickbirdTiffTileSource thus a TSX tif image wasn't read with TSX Model. We don't use the ossimRegisteryFactory because the default include factory contains ossimQuickbirdTiffTileSource. */ ossimProjection * projection = ossimplugins::ossimPluginProjectionFactory::instance() ->createProjection(ossimFilename(filename.c_str()), 0); if (!projection) { otbMsgDevMacro(<< "OSSIM Instantiate projection FAILED ! "); } else { otbMsgDevMacro(<< "OSSIM Instantiate projection SUCCESS ! "); hasMetaData = projection->saveState(geom_kwl); // Free memory delete projection; } if (!hasMetaData) { ossimImageHandler* handler = ossimImageHandlerRegistry::instance() ->open(ossimFilename(filename.c_str())); if (!handler) { otbMsgDevMacro(<< "OSSIM Open Image FAILED ! "); } else { otbMsgDevMacro(<< "OSSIM Open Image SUCCESS ! "); // Add ossimPlugins model ossimProjectionFactoryRegistry::instance()->registerFactory(ossimplugins::ossimPluginProjectionFactory::instance()); // hasMetaData = handler->getImageGeometry(geom_kwl); ossimRefPtr<ossimImageGeometry> geom = handler->getImageGeometry(); if (geom.valid()) { ossimProjection* projection = geom->getProjection(); if (projection) { hasMetaData = projection->saveState(geom_kwl); } } } // Free memory delete handler; } if (!hasMetaData) { otbMsgDevMacro(<< "OSSIM MetaData not present ! "); } else { otbMsgDevMacro(<< "OSSIM MetaData present ! "); otbMsgDevMacro(<< geom_kwl); } ImageKeywordlist otb_kwl; otb_kwl.SetKeywordlist(geom_kwl); return otb_kwl; } void WriteGeometry(const ImageKeywordlist& otb_kwl, const std::string& filename) { // Write the image keyword list if any ossimKeywordlist geom_kwl; otb_kwl.convertToOSSIMKeywordlist(geom_kwl); if (geom_kwl.getSize() > 0) { otbMsgDevMacro(<< "Exporting keywordlist ..."); ossimFilename geomFileName(filename); geomFileName.setExtension(".geom"); geom_kwl.write(geomFileName.chars()); } } } //namespace otb <commit_msg>BUG: workaround for issue #573<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbImageKeywordlist.h" #include <cassert> #include "otbMacro.h" #include "ossim/base/ossimKeywordlist.h" #include "ossim/base/ossimString.h" #include "ossim/ossimPluginProjectionFactory.h" #include "ossim/imaging/ossimImageHandlerRegistry.h" #include "ossim/ossimTileMapModel.h" #include "ossim/projection/ossimProjectionFactoryRegistry.h" #include "otbSensorModelAdapter.h" namespace otb { ImageKeywordlist ::ImageKeywordlist() { } ImageKeywordlist ::ImageKeywordlist(const Self& p) : m_Keywordlist(p.m_Keywordlist) { } ImageKeywordlist ::~ImageKeywordlist() { } void ImageKeywordlist:: operator =(const Self& p) { m_Keywordlist = p.m_Keywordlist; } void ImageKeywordlist:: SetKeywordlist(const ossimKeywordlist& kwl) { m_Keywordlist.clear(); for (ossimKeywordlist::KeywordMap::const_iterator it = kwl.getMap().begin(); it != kwl.getMap().end(); ++it) { std::string first(it->first); std::string second(it->second); m_Keywordlist[first] = second; } } const std::string& ImageKeywordlist:: GetMetadataByKey(const std::string& key) const { // Search for the key in the output map KeywordlistMap::const_iterator it = m_Keywordlist.find(key); // If the key can not be found, throw an exception if (it == m_Keywordlist.end()) { itkExceptionMacro(<< "Keywordlist has no output with key " << key); } // Then if everything is ok, return the ossinString return it->second; } bool ImageKeywordlist:: HasKey(const std::string& key) const { KeywordlistMap::const_iterator it = m_Keywordlist.find(key); return (it != m_Keywordlist.end()); } void ImageKeywordlist:: ClearMetadataByKey(const std::string& key) { m_Keywordlist[key] = ""; } void ImageKeywordlist:: AddKey(const std::string& key, const std::string& value) { m_Keywordlist[key] = value; } void ImageKeywordlist:: convertToOSSIMKeywordlist(ossimKeywordlist& kwl) const { ossimKeywordlist::KeywordMap ossimMap; for(KeywordlistMap::const_iterator it = m_Keywordlist.begin(); it != m_Keywordlist.end(); ++it) { ossimMap[it->first] = it->second; } kwl.getMap() = ossimMap; } void ImageKeywordlist:: Print(std::ostream& os, itk::Indent indent) const { this->PrintSelf(os, indent.GetNextIndent()); } void ImageKeywordlist:: PrintSelf(std::ostream& os, itk::Indent indent) const { ossimKeywordlist kwl; convertToOSSIMKeywordlist(kwl); os << indent << " Ossim Keyword list:" << std::endl; os << indent << kwl; } std::ostream & operator <<(std::ostream& os, const ImageKeywordlist& kwl) { kwl.Print(os); return os; } ImageKeywordlist ReadGeometry(const std::string& filename) { // Trying to read ossim MetaData bool hasMetaData = false; ossimKeywordlist geom_kwl; // = new ossimKeywordlist(); // Test the plugins factory /** Before, the pluginfactory was tested if the ossim one returned false. But in the case TSX, the images tif were considered as ossimQuickbirdTiffTileSource thus a TSX tif image wasn't read with TSX Model. We don't use the ossimRegisteryFactory because the default include factory contains ossimQuickbirdTiffTileSource. */ ossimProjection * projection = ossimplugins::ossimPluginProjectionFactory::instance() ->createProjection(ossimFilename(filename.c_str()), 0); if (!projection) { otbMsgDevMacro(<< "OSSIM Instantiate projection FAILED ! "); } else { otbMsgDevMacro(<< "OSSIM Instantiate projection SUCCESS ! "); hasMetaData = projection->saveState(geom_kwl); // Free memory delete projection; } if (!hasMetaData) { ossimImageHandler* handler = ossimImageHandlerRegistry::instance() ->open(ossimFilename(filename.c_str())); if (!handler) { otbMsgDevMacro(<< "OSSIM Open Image FAILED ! "); // In some corner cases, ossim is unable to create a ossimImageHandler // instance for the provided file. // This can happen for TIFF+geom files where the ossimTiffTileSource // fails when trying to open the TIFF file (for example // because ossim is compiled with a libtiff without BigTIFF support // and when the actual TIFF file exceeds the Large File limit). // In such cases, we don't actually need ossim to interpret the TIFF file, // and just want a valid ossimKeywordlist corresponding to a sensor model. // Here is implemented a shortcut used as a fallback scenario, // where we bypass the ossimImageHandlerRegistry // and directly create a ossimKeywordlist from the ".geom" file. // We then verify it is a valid sensor model by using otb::SensorModelAdapter // which uses ossimSensorModelFactory and ossimPluginProjectionFactory internally, // thus by-passing the need for a valid ossimImageHandler. // Try to find a ".geom" file next to 'filename' ossimFilename ossimGeomFile = ossimFilename(filename).setExtension(".geom"); if (ossimGeomFile.exists() && ossimGeomFile.isFile()) { // Interpret the geom file as a KWL ossimKeywordlist kwl(ossimGeomFile); // Check that the geom file results in a valid ossimKeywordlist if (kwl.getErrorStatus() == ossimErrorCodes::OSSIM_OK) { // Be sure there is a corresponding instance of ossimSensorModel // which understands this kwl SensorModelAdapter::Pointer sensorModel = SensorModelAdapter::New(); ImageKeywordlist otbkwl; otbkwl.SetKeywordlist(kwl); sensorModel->CreateProjection(otbkwl); if (sensorModel->IsValidSensorModel()) { geom_kwl = kwl; } } } } else { otbMsgDevMacro(<< "OSSIM Open Image SUCCESS ! "); // Add ossimPlugins model ossimProjectionFactoryRegistry::instance()->registerFactory(ossimplugins::ossimPluginProjectionFactory::instance()); // hasMetaData = handler->getImageGeometry(geom_kwl); ossimRefPtr<ossimImageGeometry> geom = handler->getImageGeometry(); if (geom.valid()) { ossimProjection* projection = geom->getProjection(); if (projection) { hasMetaData = projection->saveState(geom_kwl); } } } // Free memory delete handler; } if (!hasMetaData) { otbMsgDevMacro(<< "OSSIM MetaData not present ! "); } else { otbMsgDevMacro(<< "OSSIM MetaData present ! "); otbMsgDevMacro(<< geom_kwl); } ImageKeywordlist otb_kwl; otb_kwl.SetKeywordlist(geom_kwl); return otb_kwl; } void WriteGeometry(const ImageKeywordlist& otb_kwl, const std::string& filename) { // Write the image keyword list if any ossimKeywordlist geom_kwl; otb_kwl.convertToOSSIMKeywordlist(geom_kwl); if (geom_kwl.getSize() > 0) { otbMsgDevMacro(<< "Exporting keywordlist ..."); ossimFilename geomFileName(filename); geomFileName.setExtension(".geom"); geom_kwl.write(geomFileName.chars()); } } } //namespace otb <|endoftext|>
<commit_before>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE JPetReaderTest #include <boost/test/unit_test.hpp> #define protected public #define private public #include "../JPetSigCh/JPetSigCh.h" #include "../JPetSignal/JPetSignal.h" #include "../JPetReader/JPetReader.h" #include <cstddef> #include <iostream> #include <vector> #include <TError.h> /// gErrorIgnoreLevel BOOST_AUTO_TEST_SUITE (FirstSuite) BOOST_AUTO_TEST_CASE (default_constructor) { JPetReader reader; BOOST_CHECK(reader.fBranch == 0); BOOST_CHECK(reader.fFile == NULL); BOOST_CHECK(reader.fObject == 0); BOOST_CHECK(reader.fTree == 0); } BOOST_AUTO_TEST_CASE (bad_file) { gErrorIgnoreLevel = 6000; /// we turn off the ROOT error messages JPetReader reader; /// not a ROOT file BOOST_CHECK(!reader.OpenFile("bad_file.txt")); BOOST_CHECK(reader.fBranch == 0); BOOST_CHECK(reader.fFile == NULL); BOOST_CHECK(reader.fObject == 0); BOOST_CHECK(reader.fTree == 0); reader.CloseFile(); } BOOST_AUTO_TEST_CASE (open_file) { //std::cout << "test if open constructor works" << std::endl; JPetReader constructor_open("test.root"); constructor_open.ReadData(""); //std::cout << "test if OpenFile works" << std::endl; JPetReader reader; BOOST_CHECK( reader.OpenFile("test.root") ); reader.ReadData(""); } /// @todo add a proper file example !! //BOOST_AUTO_TEST_CASE (proper_file) //{ // JPetReader reader; // bool openedPropery = reader.OpenFile("phys.sig.root"); // BOOST_CHECK(openedPropery ); // if (openedPropery) { // reader.ReadData(""); // BOOST_CHECK(reader.fBranch != 0); // BOOST_CHECK(reader.fFile.IsOpen()); // BOOST_CHECK(reader.fObject != 0); // BOOST_CHECK(reader.fTree != 0); // // BOOST_CHECK(reader.GetEntries() > 0); // BOOST_CHECK(reader.GetEntry(1) > 0); // // reader.CloseFile(); // // BOOST_CHECK(reader.fBranch == 0); // BOOST_CHECK(reader.fFile.IsOpen()); // BOOST_CHECK(reader.fObject == 0); // BOOST_CHECK(reader.fTree == 0); // } //} BOOST_AUTO_TEST_SUITE_END() <commit_msg>dodanie brakującego pliku z danymi<commit_after>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE JPetReaderTest #include <boost/test/unit_test.hpp> #define protected public #define private public #include "../JPetSigCh/JPetSigCh.h" #include "../JPetSignal/JPetSignal.h" #include "../JPetReader/JPetReader.h" #include <cstddef> #include <iostream> #include <vector> #include <TError.h> /// gErrorIgnoreLevel BOOST_AUTO_TEST_SUITE (FirstSuite) BOOST_AUTO_TEST_CASE (default_constructor) { JPetReader reader; BOOST_CHECK(reader.fBranch == 0); BOOST_CHECK(reader.fFile == NULL); BOOST_CHECK(reader.fObject == 0); BOOST_CHECK(reader.fTree == 0); } BOOST_AUTO_TEST_CASE (bad_file) { gErrorIgnoreLevel = 6000; /// we turn off the ROOT error messages JPetReader reader; /// not a ROOT file BOOST_CHECK(!reader.OpenFile("bad_file.txt")); BOOST_CHECK(reader.fBranch == 0); BOOST_CHECK(reader.fFile == NULL); BOOST_CHECK(reader.fObject == 0); BOOST_CHECK(reader.fTree == 0); reader.CloseFile(); } BOOST_AUTO_TEST_CASE (open_file) { //std::cout << "test if open constructor works" << std::endl; JPetReader constructor_open("test.root"); constructor_open.ReadData(""); constructor_open.CloseFile(); //std::cout << "test if OpenFile works" << std::endl; JPetReader reader; BOOST_CHECK( reader.OpenFile("test.root") ); reader.ReadData(""); reader.CloseFile(); } /// @todo add a proper file example !! //BOOST_AUTO_TEST_CASE (proper_file) //{ // JPetReader reader; // bool openedPropery = reader.OpenFile("phys.sig.root"); // BOOST_CHECK(openedPropery ); // if (openedPropery) { // reader.ReadData(""); // BOOST_CHECK(reader.fBranch != 0); // BOOST_CHECK(reader.fFile.IsOpen()); // BOOST_CHECK(reader.fObject != 0); // BOOST_CHECK(reader.fTree != 0); // // BOOST_CHECK(reader.GetEntries() > 0); // BOOST_CHECK(reader.GetEntry(1) > 0); // // reader.CloseFile(); // // BOOST_CHECK(reader.fBranch == 0); // BOOST_CHECK(reader.fFile.IsOpen()); // BOOST_CHECK(reader.fObject == 0); // BOOST_CHECK(reader.fTree == 0); // } //} BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // Provide BZFS with a list server connection /* class header */ #include "ListServerConnection.h" /* system implementation headers */ #include <string.h> #include <string> #include <math.h> #include <errno.h> /* common implementation headers */ #include "bzfio.h" #include "version.h" #include "TextUtils.h" #include "Protocol.h" #include "GameKeeper.h" /* local implementation headers */ #include "CmdLineOptions.h" // FIXME remove externs! extern PingPacket getTeamCounts(); extern uint16_t curMaxPlayers; extern void sendMessage(int playerIndex, PlayerId targetPlayer, const char *message); extern void sendPlayerInfo(void); extern void sendIPUpdate(int targetPlayer, int playerIndex); extern CmdLineOptions *clOptions; const int ListServerLink::NotConnected = -1; ListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle) { std::string bzfsUserAgent = "bzfs "; bzfsUserAgent += getAppVersion(); setURL(listServerURL); setUserAgent(bzfsUserAgent); if (clOptions->pingInterface != "") setInterface(clOptions->pingInterface); publicizeAddress = publicizedAddress; publicizeDescription = publicizedTitle; //if this c'tor is called, it's safe to publicize publicizeServer = true; queuedRequest = false; // schedule initial ADD message queueMessage(ListServerLink::ADD); } ListServerLink::ListServerLink() { // does not create a usable link, so checks should be placed // in all public member functions to ensure that nothing tries // to happen if publicizeServer is false publicizeServer = false; } ListServerLink::~ListServerLink() { // now tell the list server that we're going away. this can // take some time but we don't want to wait too long. we do // our own multiplexing loop and wait for a maximum of 3 seconds // total. // if we aren't supposed to be publicizing, skip the whole thing // and don't waste 3 seconds. if (!publicizeServer) return; queueMessage(ListServerLink::REMOVE); for (int i = 0; i < 12; i++) { cURLManager::perform(); if (!queuedRequest) break; TimeKeeper::sleep(0.25f); } } void ListServerLink::finalization(char *data, unsigned int length, bool good) { queuedRequest = false; if (good && (length < 2048)) { char buf[2048]; memcpy(buf, data, length); int bytes = length; buf[bytes]=0; char* base = buf; static char *tokGoodIdentifier = "TOKGOOD: "; static char *tokBadIdentifier = "TOKBAD: "; // walks entire reply including HTTP headers while (*base) { // find next newline char* scan = base; while (*scan && *scan != '\r' && *scan != '\n') scan++; // if no newline then no more complete replies if (*scan != '\r' && *scan != '\n') break; while (*scan && (*scan == '\r' || *scan == '\n')) *scan++ = '\0'; DEBUG4("Got line: \"%s\"\n", base); // TODO don't do this if we don't want central logins if (strncmp(base, tokGoodIdentifier, strlen(tokGoodIdentifier)) == 0) { char *callsign, *group; callsign = base + strlen(tokGoodIdentifier); DEBUG3("Got: %s\n", base); group = callsign; while (*group && (*group != ':')) group++; while (*group && (*group == ':')) *group++ = 0; int playerIndex = GameKeeper::Player::getPlayerIDByName(callsign); if (playerIndex < curMaxPlayers) { GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(playerIndex); if (playerData != NULL) { // don't accept the global auth if there's a local account // of the same name and the local account is not marked as // being the same as the global account if (!playerData->accessInfo.hasRealPassword() || playerData->accessInfo.getUserInfo(callsign) .hasGroup("LOCAL.GLOBAL")) { if (!playerData->accessInfo.isRegistered()) playerData->accessInfo.storeInfo(NULL); playerData->accessInfo.setPermissionRights(); while (*group) { char *nextgroup = group; while (*nextgroup && (*nextgroup != ':')) nextgroup++; while (*nextgroup && (*nextgroup == ':')) *nextgroup++ = 0; playerData->accessInfo.addGroup(group); group = nextgroup; } playerData->authentication.global(true); sendMessage(ServerPlayer, playerIndex, "Global login approved!"); sendIPUpdate(playerIndex, -1); sendPlayerInfo(); } else { sendMessage(ServerPlayer, playerIndex, "Global login rejected. " "This callsign is registered locally on this " "server."); sendMessage(ServerPlayer, playerIndex, "If the local account is yours, " "/identify, /deregister and reconnnect, " "or ask an admin for the LOCAL.GLOBAL group."); sendMessage(ServerPlayer, playerIndex, "If it is not yours, please ask an admin " "to deregister it so that you may use your global " "callsign."); } playerData->setNeedThisHostbanChecked(true); playerData->player.clearToken(); } } } else if (!strncmp(base, tokBadIdentifier, strlen(tokBadIdentifier))) { char *callsign; callsign = base + strlen(tokBadIdentifier); int playerIndex = GameKeeper::Player::getPlayerIDByName(callsign); DEBUG3("Got: [%d] %s\n", playerIndex, base); if (playerIndex < curMaxPlayers) { GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(playerIndex); sendMessage(ServerPlayer, playerIndex, "Global login rejected, bad token."); if (playerData != NULL) { playerData->setNeedThisHostbanChecked(true); playerData->player.clearToken(); } } } // next reply base = scan; } } if (nextMessageType != ListServerLink::NONE) { // There was a pending request arrived after we write: // we should redo all the stuff sendQueuedMessages(); } } void ListServerLink::queueMessage(MessageType type) { // ignore if the server is not public if (!publicizeServer) return; // record next message to send. nextMessageType = type; if (!queuedRequest) sendQueuedMessages(); } void ListServerLink::sendQueuedMessages() { queuedRequest = true; if (nextMessageType == ListServerLink::ADD) { DEBUG3("Queuing ADD message to list server\n"); addMe(getTeamCounts(), publicizeAddress, publicizeDescription); lastAddTime = TimeKeeper::getCurrent(); } else if (nextMessageType == ListServerLink::REMOVE) { DEBUG3("Queuing REMOVE message to list server\n"); removeMe(publicizeAddress); } nextMessageType = ListServerLink::NONE; } void ListServerLink::addMe(PingPacket pingInfo, std::string publicizedAddress, std::string publicizedTitle) { std::string msg; std::string hdr; // encode ping reply as ascii hex digits plus NULL char gameInfo[PingPacketHexPackedSize + 1]; pingInfo.packHex(gameInfo); // send ADD message (must send blank line) addFormData("action", "ADD"); addFormData("nameport", publicizedAddress.c_str()); addFormData("version", getServerVersion()); addFormData("gameinfo", gameInfo); addFormData("build", getAppVersion()); // callsign1@ip1=token1%0D%0Acallsign2@ip2=token2%0D%0A for (int i = 0; i < curMaxPlayers; i++) { GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i); if (!playerData) continue; NetHandler *handler = playerData->netHandler; if (strlen(playerData->player.getCallSign()) && strlen(playerData->player.getToken())) { msg += playerData->player.getCallSign(); Address addr = handler->getIPAddress(); if (!addr.isPrivate()) { msg += "@"; msg += handler->getTargetIP(); } msg += "="; msg += playerData->player.getToken(); msg += "%0D%0A"; } } addFormData("checktokens", msg.c_str()); // *groups=GROUP0%0D%0AGROUP1%0D%0A msg = ""; PlayerAccessMap::iterator itr = groupAccess.begin(); for ( ; itr != groupAccess.end(); itr++) { if (itr->first.substr(0, 6) != "LOCAL.") { msg += itr->first.c_str(); msg += "%0D%0A"; } } addFormData("groups", msg.c_str()); addFormData("title", publicizedTitle.c_str()); addHandle(); } void ListServerLink::removeMe(std::string publicizedAddress) { std::string msg; addFormData("action", "REMOVE"); addFormData("nameport", publicizedAddress.c_str()); addHandle(); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>setPostMode must be called for using POST after the form data are filled<commit_after>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // Provide BZFS with a list server connection /* class header */ #include "ListServerConnection.h" /* system implementation headers */ #include <string.h> #include <string> #include <math.h> #include <errno.h> /* common implementation headers */ #include "bzfio.h" #include "version.h" #include "TextUtils.h" #include "Protocol.h" #include "GameKeeper.h" /* local implementation headers */ #include "CmdLineOptions.h" // FIXME remove externs! extern PingPacket getTeamCounts(); extern uint16_t curMaxPlayers; extern void sendMessage(int playerIndex, PlayerId targetPlayer, const char *message); extern void sendPlayerInfo(void); extern void sendIPUpdate(int targetPlayer, int playerIndex); extern CmdLineOptions *clOptions; const int ListServerLink::NotConnected = -1; ListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle) { std::string bzfsUserAgent = "bzfs "; bzfsUserAgent += getAppVersion(); setURL(listServerURL); setUserAgent(bzfsUserAgent); if (clOptions->pingInterface != "") setInterface(clOptions->pingInterface); publicizeAddress = publicizedAddress; publicizeDescription = publicizedTitle; //if this c'tor is called, it's safe to publicize publicizeServer = true; queuedRequest = false; // schedule initial ADD message queueMessage(ListServerLink::ADD); } ListServerLink::ListServerLink() { // does not create a usable link, so checks should be placed // in all public member functions to ensure that nothing tries // to happen if publicizeServer is false publicizeServer = false; } ListServerLink::~ListServerLink() { // now tell the list server that we're going away. this can // take some time but we don't want to wait too long. we do // our own multiplexing loop and wait for a maximum of 3 seconds // total. // if we aren't supposed to be publicizing, skip the whole thing // and don't waste 3 seconds. if (!publicizeServer) return; queueMessage(ListServerLink::REMOVE); for (int i = 0; i < 12; i++) { cURLManager::perform(); if (!queuedRequest) break; TimeKeeper::sleep(0.25f); } } void ListServerLink::finalization(char *data, unsigned int length, bool good) { queuedRequest = false; if (good && (length < 2048)) { char buf[2048]; memcpy(buf, data, length); int bytes = length; buf[bytes]=0; char* base = buf; static char *tokGoodIdentifier = "TOKGOOD: "; static char *tokBadIdentifier = "TOKBAD: "; // walks entire reply including HTTP headers while (*base) { // find next newline char* scan = base; while (*scan && *scan != '\r' && *scan != '\n') scan++; // if no newline then no more complete replies if (*scan != '\r' && *scan != '\n') break; while (*scan && (*scan == '\r' || *scan == '\n')) *scan++ = '\0'; DEBUG4("Got line: \"%s\"\n", base); // TODO don't do this if we don't want central logins if (strncmp(base, tokGoodIdentifier, strlen(tokGoodIdentifier)) == 0) { char *callsign, *group; callsign = base + strlen(tokGoodIdentifier); DEBUG3("Got: %s\n", base); group = callsign; while (*group && (*group != ':')) group++; while (*group && (*group == ':')) *group++ = 0; int playerIndex = GameKeeper::Player::getPlayerIDByName(callsign); if (playerIndex < curMaxPlayers) { GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(playerIndex); if (playerData != NULL) { // don't accept the global auth if there's a local account // of the same name and the local account is not marked as // being the same as the global account if (!playerData->accessInfo.hasRealPassword() || playerData->accessInfo.getUserInfo(callsign) .hasGroup("LOCAL.GLOBAL")) { if (!playerData->accessInfo.isRegistered()) playerData->accessInfo.storeInfo(NULL); playerData->accessInfo.setPermissionRights(); while (*group) { char *nextgroup = group; while (*nextgroup && (*nextgroup != ':')) nextgroup++; while (*nextgroup && (*nextgroup == ':')) *nextgroup++ = 0; playerData->accessInfo.addGroup(group); group = nextgroup; } playerData->authentication.global(true); sendMessage(ServerPlayer, playerIndex, "Global login approved!"); sendIPUpdate(playerIndex, -1); sendPlayerInfo(); } else { sendMessage(ServerPlayer, playerIndex, "Global login rejected. " "This callsign is registered locally on this " "server."); sendMessage(ServerPlayer, playerIndex, "If the local account is yours, " "/identify, /deregister and reconnnect, " "or ask an admin for the LOCAL.GLOBAL group."); sendMessage(ServerPlayer, playerIndex, "If it is not yours, please ask an admin " "to deregister it so that you may use your global " "callsign."); } playerData->setNeedThisHostbanChecked(true); playerData->player.clearToken(); } } } else if (!strncmp(base, tokBadIdentifier, strlen(tokBadIdentifier))) { char *callsign; callsign = base + strlen(tokBadIdentifier); int playerIndex = GameKeeper::Player::getPlayerIDByName(callsign); DEBUG3("Got: [%d] %s\n", playerIndex, base); if (playerIndex < curMaxPlayers) { GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(playerIndex); sendMessage(ServerPlayer, playerIndex, "Global login rejected, bad token."); if (playerData != NULL) { playerData->setNeedThisHostbanChecked(true); playerData->player.clearToken(); } } } // next reply base = scan; } } if (nextMessageType != ListServerLink::NONE) { // There was a pending request arrived after we write: // we should redo all the stuff sendQueuedMessages(); } } void ListServerLink::queueMessage(MessageType type) { // ignore if the server is not public if (!publicizeServer) return; // record next message to send. nextMessageType = type; if (!queuedRequest) sendQueuedMessages(); } void ListServerLink::sendQueuedMessages() { queuedRequest = true; if (nextMessageType == ListServerLink::ADD) { DEBUG3("Queuing ADD message to list server\n"); addMe(getTeamCounts(), publicizeAddress, publicizeDescription); lastAddTime = TimeKeeper::getCurrent(); } else if (nextMessageType == ListServerLink::REMOVE) { DEBUG3("Queuing REMOVE message to list server\n"); removeMe(publicizeAddress); } nextMessageType = ListServerLink::NONE; } void ListServerLink::addMe(PingPacket pingInfo, std::string publicizedAddress, std::string publicizedTitle) { std::string msg; std::string hdr; // encode ping reply as ascii hex digits plus NULL char gameInfo[PingPacketHexPackedSize + 1]; pingInfo.packHex(gameInfo); // send ADD message (must send blank line) addFormData("action", "ADD"); addFormData("nameport", publicizedAddress.c_str()); addFormData("version", getServerVersion()); addFormData("gameinfo", gameInfo); addFormData("build", getAppVersion()); // callsign1@ip1=token1%0D%0Acallsign2@ip2=token2%0D%0A for (int i = 0; i < curMaxPlayers; i++) { GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i); if (!playerData) continue; NetHandler *handler = playerData->netHandler; if (strlen(playerData->player.getCallSign()) && strlen(playerData->player.getToken())) { msg += playerData->player.getCallSign(); Address addr = handler->getIPAddress(); if (!addr.isPrivate()) { msg += "@"; msg += handler->getTargetIP(); } msg += "="; msg += playerData->player.getToken(); msg += "%0D%0A"; } } addFormData("checktokens", msg.c_str()); // *groups=GROUP0%0D%0AGROUP1%0D%0A msg = ""; PlayerAccessMap::iterator itr = groupAccess.begin(); for ( ; itr != groupAccess.end(); itr++) { if (itr->first.substr(0, 6) != "LOCAL.") { msg += itr->first.c_str(); msg += "%0D%0A"; } } addFormData("groups", msg.c_str()); addFormData("title", publicizedTitle.c_str()); setPostMode(); addHandle(); } void ListServerLink::removeMe(std::string publicizedAddress) { std::string msg; addFormData("action", "REMOVE"); addFormData("nameport", publicizedAddress.c_str()); setPostMode(); addHandle(); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/* Copyright (c) 2014-2015 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <string> #include "CoordinatorClusterClock.h" #include "CoordinatorClusterClock.pb.h" #include "ShortMacros.h" #include "Util.h" namespace RAMCloud { /** * Constructor for the CoordinatorClusterClock. * * \param context * Overall information about the RAMCloud server and provides access to * externalStorage (externalStorage must be non-null). */ CoordinatorClusterClock::CoordinatorClusterClock(Context *context) : mutex() , startingSysTimeUs(Cycles::toMicroseconds(Cycles::rdtsc())) , startingClusterTimeUs(recoverClusterTime(context->externalStorage)) , safeClusterTimeUs(startingClusterTimeUs) , updater(context, this) {} /** * Returns the current cluster time. Repeated calls to this method are * guaranteed to return monotonically non-decreasing cluster times, even across * Coordinator crashes. The cluster time is expected to advance in microseconds * roughly at the same rate as the coordinator system clock. In rare cases (e.g. * when updates to externalStorage take a long time), the clock may stall * causing this method to return the same value for an extended period of time. * * This method is thread-safe. */ uint64_t CoordinatorClusterClock::getTime() { Lock lock(mutex); uint64_t time = getInternal(lock); // In the unlikely event that the current time exceeds the safe time, // return the safe time so that an unsafe time can never be observed. if (expect_false(time > safeClusterTimeUs)) {// Not sure predictor helps. RAMCLOUD_CLOG(WARNING, "Returning stale time. " "SafeTimeUpdater may be running behind."); return safeClusterTimeUs; } return time; } /** * Start the SafeTimeUpdater. Must be called to ensure the clock will advance. * Separated out mostly for ease of testing. */ void CoordinatorClusterClock::startUpdater() { updater.start(0); } /** * Constructor for the SafeTimeUpdater. * * \param context * Overall information about the RAMCloud server and provides access to * externalStorage. * \param clock * Provides access to the cluster clock to update the safeClusterTime. */ CoordinatorClusterClock::SafeTimeUpdater::SafeTimeUpdater( Context* context, CoordinatorClusterClock* clock) : WorkerTimer(context->dispatch) , externalStorage(context->externalStorage) , clock(clock) {} /** * This handler advances the safeClusterTime stored on external storage and * updates the CoordinatorClusterClock's safeClusterTime once successful. This * handler is called when the SafeTimeUpdater timer expires (i.e. once every * updateIntervalCycles). */ void CoordinatorClusterClock::SafeTimeUpdater::handleTimerEvent() { uint64_t startTimeCycles = Cycles::rdtsc(); CoordinatorClusterClock::Lock lock(clock->mutex); uint64_t nextSafeTimeUs = clock->getInternal(lock) + clock->safeTimeIntervalUs; ProtoBuf::CoordinatorClusterClock info; info.set_next_safe_time(nextSafeTimeUs); std::string str; info.SerializeToString(&str); externalStorage->set(ExternalStorage::Hint::UPDATE, "coordinatorClusterClock", str.c_str(), downCast<int>(str.length())); clock->safeClusterTimeUs = nextSafeTimeUs; this->start(startTimeCycles + Cycles::fromSeconds(clock->updateIntervalS)); } /** * Returns the raw, calculated, unprotected cluster time. Should not be used * by external methods. * * \param lock * Ensures that caller has acquired mutex; not actually used here. */ uint64_t CoordinatorClusterClock::getInternal(Lock &lock) { uint64_t currentSysTimeUs = Cycles::toMicroseconds(Cycles::rdtsc()); return (currentSysTimeUs - startingSysTimeUs) + startingClusterTimeUs; } /** * Recovers and returns the last stored safeClusterTime from externalStorage. * Used during the construction of the cluster clock to initialize the * startingClusterTime. * * \param externalStorage * Pointer to the externalStorage module from which to recover. * * \return * The last stored safeClusterTime or zero if none exists. */ uint64_t CoordinatorClusterClock::recoverClusterTime(ExternalStorage* externalStorage) { uint64_t startingClusterTime = 0; // Recover any previously persisted safe cluster time. Cluster time starts // at zero if no persisted time is found. ProtoBuf::CoordinatorClusterClock info; if (externalStorage->getProtoBuf<ProtoBuf::CoordinatorClusterClock>( "coordinatorClusterClock", &info)) { startingClusterTime = info.next_safe_time(); } else { // TODO(cstlee): only output message when NOT starting a new cluster. // may need to use an additional param flag. LOG(WARNING, "couldn't find \"coordinatorClusterClock\" object in " "external storage; starting new clock from zero; benign if " "starting new cluster from scratch, may cause linearizability " "failures otherwise"); } LOG(NOTICE, "initializing CoordinatorClusterClock: startingClusterTime = %lu", startingClusterTime); return startingClusterTime; } } // namespace RAMCloud <commit_msg>Remove TODO for RAM-698<commit_after>/* Copyright (c) 2014-2015 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <string> #include "CoordinatorClusterClock.h" #include "CoordinatorClusterClock.pb.h" #include "ShortMacros.h" #include "Util.h" namespace RAMCloud { /** * Constructor for the CoordinatorClusterClock. * * \param context * Overall information about the RAMCloud server and provides access to * externalStorage (externalStorage must be non-null). */ CoordinatorClusterClock::CoordinatorClusterClock(Context *context) : mutex() , startingSysTimeUs(Cycles::toMicroseconds(Cycles::rdtsc())) , startingClusterTimeUs(recoverClusterTime(context->externalStorage)) , safeClusterTimeUs(startingClusterTimeUs) , updater(context, this) {} /** * Returns the current cluster time. Repeated calls to this method are * guaranteed to return monotonically non-decreasing cluster times, even across * Coordinator crashes. The cluster time is expected to advance in microseconds * roughly at the same rate as the coordinator system clock. In rare cases (e.g. * when updates to externalStorage take a long time), the clock may stall * causing this method to return the same value for an extended period of time. * * This method is thread-safe. */ uint64_t CoordinatorClusterClock::getTime() { Lock lock(mutex); uint64_t time = getInternal(lock); // In the unlikely event that the current time exceeds the safe time, // return the safe time so that an unsafe time can never be observed. if (expect_false(time > safeClusterTimeUs)) {// Not sure predictor helps. RAMCLOUD_CLOG(WARNING, "Returning stale time. " "SafeTimeUpdater may be running behind."); return safeClusterTimeUs; } return time; } /** * Start the SafeTimeUpdater. Must be called to ensure the clock will advance. * Separated out mostly for ease of testing. */ void CoordinatorClusterClock::startUpdater() { updater.start(0); } /** * Constructor for the SafeTimeUpdater. * * \param context * Overall information about the RAMCloud server and provides access to * externalStorage. * \param clock * Provides access to the cluster clock to update the safeClusterTime. */ CoordinatorClusterClock::SafeTimeUpdater::SafeTimeUpdater( Context* context, CoordinatorClusterClock* clock) : WorkerTimer(context->dispatch) , externalStorage(context->externalStorage) , clock(clock) {} /** * This handler advances the safeClusterTime stored on external storage and * updates the CoordinatorClusterClock's safeClusterTime once successful. This * handler is called when the SafeTimeUpdater timer expires (i.e. once every * updateIntervalCycles). */ void CoordinatorClusterClock::SafeTimeUpdater::handleTimerEvent() { uint64_t startTimeCycles = Cycles::rdtsc(); CoordinatorClusterClock::Lock lock(clock->mutex); uint64_t nextSafeTimeUs = clock->getInternal(lock) + clock->safeTimeIntervalUs; ProtoBuf::CoordinatorClusterClock info; info.set_next_safe_time(nextSafeTimeUs); std::string str; info.SerializeToString(&str); externalStorage->set(ExternalStorage::Hint::UPDATE, "coordinatorClusterClock", str.c_str(), downCast<int>(str.length())); clock->safeClusterTimeUs = nextSafeTimeUs; this->start(startTimeCycles + Cycles::fromSeconds(clock->updateIntervalS)); } /** * Returns the raw, calculated, unprotected cluster time. Should not be used * by external methods. * * \param lock * Ensures that caller has acquired mutex; not actually used here. */ uint64_t CoordinatorClusterClock::getInternal(Lock &lock) { uint64_t currentSysTimeUs = Cycles::toMicroseconds(Cycles::rdtsc()); return (currentSysTimeUs - startingSysTimeUs) + startingClusterTimeUs; } /** * Recovers and returns the last stored safeClusterTime from externalStorage. * Used during the construction of the cluster clock to initialize the * startingClusterTime. * * \param externalStorage * Pointer to the externalStorage module from which to recover. * * \return * The last stored safeClusterTime or zero if none exists. */ uint64_t CoordinatorClusterClock::recoverClusterTime(ExternalStorage* externalStorage) { uint64_t startingClusterTime = 0; // Recover any previously persisted safe cluster time. Cluster time starts // at zero if no persisted time is found. ProtoBuf::CoordinatorClusterClock info; if (externalStorage->getProtoBuf<ProtoBuf::CoordinatorClusterClock>( "coordinatorClusterClock", &info)) { startingClusterTime = info.next_safe_time(); } else { LOG(WARNING, "couldn't find \"coordinatorClusterClock\" object in " "external storage; starting new clock from zero; benign if " "starting new cluster from scratch, may cause linearizability " "failures otherwise"); } LOG(NOTICE, "initializing CoordinatorClusterClock: startingClusterTime = %lu", startingClusterTime); return startingClusterTime; } } // namespace RAMCloud <|endoftext|>
<commit_before>// -*-c++-*- #include <osg/Group> #include <osg/Sequence> #include <osg/MatrixTransform> #include <osgDB/ReadFile> #include <osgGA/TrackballManipulator> #include <osgGLUT/Viewer> #include <osgGLUT/glut> // // A simple demo demonstrating usage of osg::Sequence. // // simple event handler to start/stop sequences class MyEventHandler : public osgGA::GUIEventHandler { public: /// Constructor. MyEventHandler(std::vector<osg::Sequence*>* seq) { _seq = seq; } /// Handle events. virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter&) { bool handled = false; if (ea.getEventType() == osgGA::GUIEventAdapter::KEYBOARD) { const char keys[] = "!@#$%^&*()"; for (unsigned int i = 0; i < (sizeof(keys) / sizeof(keys[0])); i++) { if (i < _seq->size() && ea.getKey() == keys[i]) { // toggle sequence osg::Sequence* seq = (*_seq)[i]; osg::Sequence::SequenceMode mode = seq->getMode(); switch (mode) { case osg::Sequence::START: seq->setMode(osg::Sequence::PAUSE); break; case osg::Sequence::STOP: seq->setMode(osg::Sequence::START); break; case osg::Sequence::PAUSE: seq->setMode(osg::Sequence::RESUME); break; default: break; } std::cerr << "Toggled sequence " << i << std::endl; handled = true; } } } return handled; } /// accept visits. virtual void accept(osgGA::GUIEventHandlerVisitor&) {} private: std::vector<osg::Sequence*>* _seq; }; void write_usage(std::ostream& out, const std::string& name) { out << std::endl; out <<"usage:"<< std::endl; out <<" "<<name<<" [options] infile1 [infile2 ...]"<< std::endl; out << std::endl; out <<"options:"<< std::endl; out <<" -l libraryName - load plugin of name libraryName"<< std::endl; out <<" i.e. -l osgdb_pfb"<< std::endl; out <<" Useful for loading reader/writers which can load"<< std::endl; out <<" other file formats in addition to its extension."<< std::endl; out <<" -e extensionName - load reader/wrter plugin for file extension"<< std::endl; out <<" i.e. -e pfb"<< std::endl; out <<" Useful short hand for specifying full library name as"<< std::endl; out <<" done with -l above, as it automatically expands to"<< std::endl; out <<" the full library name appropriate for each platform."<< std::endl; out<<std::endl; } osg::Sequence* generateSeq(osg::Sequence::LoopMode mode, float speed, int nreps, std::vector<osg::Node*>& model) { osg::Sequence* seqNode = osgNew osg::Sequence; // add children, show each child for 1.0 seconds for (unsigned int i = 0; i < model.size(); i++) { seqNode->addChild(model[i]); seqNode->setTime(i, 1.0f); } // interval seqNode->setInterval(mode, 0, -1); // speed-up factor and number of repeats for entire sequence seqNode->setDuration(speed, nreps); // stopped seqNode->setMode(osg::Sequence::STOP); return seqNode; } int main( int argc, char **argv ) { // initialize the GLUT glutInit( &argc, argv ); if (argc < 2) { write_usage(osg::notify(osg::NOTICE), argv[0]); return 0; } // create commandline args std::vector<std::string> commandLine; for (int i = 1; i < argc; i++) commandLine.push_back(argv[i]); // initialize the viewer osgGLUT::Viewer viewer; viewer.setWindowTitle(argv[0]); // configure the viewer from the commandline arguments, and eat any // parameters that have been matched. viewer.readCommandLine(commandLine); // assumes any remaining parameters are models std::vector<osg::Node*> model; for (unsigned int i = 0; i < commandLine.size(); i++) { std::cerr << "Loading " << commandLine[i] << std::endl; osg::Node* node = osgDB::readNodeFile(commandLine[i]); if (node) model.push_back(node); } if (model.empty()) { write_usage(osg::notify(osg::NOTICE),argv[0]); return -1; } // root osg::Group* rootNode = osgNew osg::Group; // create sequences std::vector<osg::Sequence*> seq; const osg::Sequence::LoopMode mode[] = { osg::Sequence::LOOP, osg::Sequence::SWING, osg::Sequence::LOOP }; const float speed[] = { 0.5f, 1.0f, 1.5f }; const int nreps[] = { -1, 5, 1 }; float x = 0.0f; for (unsigned int i = 0; i < (sizeof(speed) / sizeof(speed[0])); i++) { osg::Sequence* seqNode = generateSeq(mode[i], speed[i], nreps[i], model); if (!seqNode) continue; seq.push_back(seqNode); // position sequence osg::Matrix matrix; matrix.makeTranslate(x, 0.0, 0.0); osg::MatrixTransform* xform = osgNew osg::MatrixTransform; xform->setMatrix(matrix); xform->addChild(seqNode); rootNode->addChild(xform); x += seqNode->getBound()._radius * 1.5f; } // add model to viewer. viewer.addViewport(rootNode); // register additional event handler viewer.setEventHandler(osgNew MyEventHandler(&seq), 0); // register trackball, flight and drive. viewer.registerCameraManipulator(new osgGA::TrackballManipulator); viewer.open(); viewer.run(); return 0; } <commit_msg>Moved "unsigned int i" from for(.. to just before it, and removed subsequent ones to get the VisualStudio compiler working once more.<commit_after>// -*-c++-*- #include <osg/Group> #include <osg/Sequence> #include <osg/MatrixTransform> #include <osgDB/ReadFile> #include <osgGA/TrackballManipulator> #include <osgGLUT/Viewer> #include <osgGLUT/glut> // // A simple demo demonstrating usage of osg::Sequence. // // simple event handler to start/stop sequences class MyEventHandler : public osgGA::GUIEventHandler { public: /// Constructor. MyEventHandler(std::vector<osg::Sequence*>* seq) { _seq = seq; } /// Handle events. virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter&) { bool handled = false; if (ea.getEventType() == osgGA::GUIEventAdapter::KEYBOARD) { const char keys[] = "!@#$%^&*()"; for (unsigned int i = 0; i < (sizeof(keys) / sizeof(keys[0])); i++) { if (i < _seq->size() && ea.getKey() == keys[i]) { // toggle sequence osg::Sequence* seq = (*_seq)[i]; osg::Sequence::SequenceMode mode = seq->getMode(); switch (mode) { case osg::Sequence::START: seq->setMode(osg::Sequence::PAUSE); break; case osg::Sequence::STOP: seq->setMode(osg::Sequence::START); break; case osg::Sequence::PAUSE: seq->setMode(osg::Sequence::RESUME); break; default: break; } std::cerr << "Toggled sequence " << i << std::endl; handled = true; } } } return handled; } /// accept visits. virtual void accept(osgGA::GUIEventHandlerVisitor&) {} private: std::vector<osg::Sequence*>* _seq; }; void write_usage(std::ostream& out, const std::string& name) { out << std::endl; out <<"usage:"<< std::endl; out <<" "<<name<<" [options] infile1 [infile2 ...]"<< std::endl; out << std::endl; out <<"options:"<< std::endl; out <<" -l libraryName - load plugin of name libraryName"<< std::endl; out <<" i.e. -l osgdb_pfb"<< std::endl; out <<" Useful for loading reader/writers which can load"<< std::endl; out <<" other file formats in addition to its extension."<< std::endl; out <<" -e extensionName - load reader/wrter plugin for file extension"<< std::endl; out <<" i.e. -e pfb"<< std::endl; out <<" Useful short hand for specifying full library name as"<< std::endl; out <<" done with -l above, as it automatically expands to"<< std::endl; out <<" the full library name appropriate for each platform."<< std::endl; out<<std::endl; } osg::Sequence* generateSeq(osg::Sequence::LoopMode mode, float speed, int nreps, std::vector<osg::Node*>& model) { osg::Sequence* seqNode = osgNew osg::Sequence; // add children, show each child for 1.0 seconds for (unsigned int i = 0; i < model.size(); i++) { seqNode->addChild(model[i]); seqNode->setTime(i, 1.0f); } // interval seqNode->setInterval(mode, 0, -1); // speed-up factor and number of repeats for entire sequence seqNode->setDuration(speed, nreps); // stopped seqNode->setMode(osg::Sequence::STOP); return seqNode; } int main( int argc, char **argv ) { // initialize the GLUT glutInit( &argc, argv ); if (argc < 2) { write_usage(osg::notify(osg::NOTICE), argv[0]); return 0; } // create commandline args std::vector<std::string> commandLine; for (int ia = 1; ia < argc; ia++) commandLine.push_back(argv[ia]); // initialize the viewer osgGLUT::Viewer viewer; viewer.setWindowTitle(argv[0]); // configure the viewer from the commandline arguments, and eat any // parameters that have been matched. viewer.readCommandLine(commandLine); // assumes any remaining parameters are models std::vector<osg::Node*> model; unsigned int i; for (i = 0; i < commandLine.size(); i++) { std::cerr << "Loading " << commandLine[i] << std::endl; osg::Node* node = osgDB::readNodeFile(commandLine[i]); if (node) model.push_back(node); } if (model.empty()) { write_usage(osg::notify(osg::NOTICE),argv[0]); return -1; } // root osg::Group* rootNode = osgNew osg::Group; // create sequences std::vector<osg::Sequence*> seq; const osg::Sequence::LoopMode mode[] = { osg::Sequence::LOOP, osg::Sequence::SWING, osg::Sequence::LOOP }; const float speed[] = { 0.5f, 1.0f, 1.5f }; const int nreps[] = { -1, 5, 1 }; float x = 0.0f; for (i = 0; i < (sizeof(speed) / sizeof(speed[0])); i++) { osg::Sequence* seqNode = generateSeq(mode[i], speed[i], nreps[i], model); if (!seqNode) continue; seq.push_back(seqNode); // position sequence osg::Matrix matrix; matrix.makeTranslate(x, 0.0, 0.0); osg::MatrixTransform* xform = osgNew osg::MatrixTransform; xform->setMatrix(matrix); xform->addChild(seqNode); rootNode->addChild(xform); x += seqNode->getBound()._radius * 1.5f; } // add model to viewer. viewer.addViewport(rootNode); // register additional event handler viewer.setEventHandler(osgNew MyEventHandler(&seq), 0); // register trackball, flight and drive. viewer.registerCameraManipulator(new osgGA::TrackballManipulator); viewer.open(); viewer.run(); return 0; } <|endoftext|>
<commit_before>//Copyright 2015 Adam Smith // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. // Contact : // Email : [email protected] // GitHub repository : https://github.com/SolaireLibrary/SolaireCPP #include "Solaire/XML/Format.hpp" namespace Solaire { static bool skipWhitespace(IStream& aStream) { if(aStream.end()) return true; char c; aStream >> c; while(std::isspace(c)) { if(aStream.end()) return true; aStream >> c; } aStream.setOffset(aStream.getOffset() - 1); return true; } static bool writeObject(const StringConstant<char>& aName, const GenericObject& aValue, OStream& aStream) throw(); static bool writeArray(const StringConstant<char>& aName, const GenericArray& aValue, OStream& aStream) throw() { aStream << '<'; aStream << aName; if(aValue.size() > 0) { aStream << '>'; const auto end = aValue.end(); for(auto i = aValue.begin(); i != end; ++i) { switch(i->getType()) { case GenericValue::NULL_T: aStream << "<solaire_array_element type=\"null\"/>"; break; case GenericValue::CHAR_T: aStream << "<solaire_array_element type=\"char\" value=\""; aStream << i->getChar(); aStream << "\"/>"; break; case GenericValue::BOOL_T: aStream << "<solaire_array_element type=\"bool\" value=\""; if(i->getBool()) { aStream << "true"; }else { aStream << "false"; } aStream << "\"/>"; break; case GenericValue::UNSIGNED_T: aStream << "<solaire_array_element type=\"number\" value=\""; aStream << i->getUnsigned(); aStream << "\"/>"; break; case GenericValue::SIGNED_T: aStream << "<solaire_array_element type=\"number\" value=\""; aStream << i->getSigned(); aStream << "\"/>"; break; case GenericValue::DOUBLE_T: aStream << "<solaire_array_element type=\"number\" value=\""; aStream << i->getDouble(); aStream << "\"/>"; break; case GenericValue::STRING_T: aStream << "<solaire_array_element type=\"string\" value=\""; aStream << i->getString(); aStream << "\"/>"; break; case GenericValue::ARRAY_T: writeArray(CString("solaire_array_element"), i->getArray(), aStream); break; case GenericValue::OBJECT_T: writeObject(CString("solaire_array_element"), i->getObject(), aStream); break; default: break; } } aStream << '<'; aStream << '/'; aStream << aName; aStream << '>'; }else { aStream << '/'; aStream << '>'; } return true; } static bool writeObject(const StringConstant<char>& aName, const GenericObject& aValue, OStream& aStream) throw() { if(aValue.size() == 0) { aStream << '<'; aStream << aName; aStream << '/'; aStream << '>'; return true; } const auto entries = aValue.getEntries(); const auto end = entries->end(); aStream << '<'; aStream << aName; // Write attributes aStream << ' '; for(auto i = entries->begin(); i != end; ++i) { switch(i->second.getType()) { case GenericValue::NULL_T: aStream << i->first; aStream << "=\"null\" "; break; case GenericValue::CHAR_T: aStream << i->first; aStream << "=\""; aStream << i->second.getChar(); aStream << "\" "; break; case GenericValue::BOOL_T: aStream << i->first; if(i->second.getBool()) { aStream << "=\"true\" "; }else { aStream << "=\"false\" "; } break; case GenericValue::UNSIGNED_T: aStream << i->first; aStream << "=\""; aStream << i->second.getUnsigned(); aStream << "\" "; break; case GenericValue::SIGNED_T: aStream << i->first; aStream << "=\""; aStream << i->second.getSigned(); aStream << "\" "; break; case GenericValue::DOUBLE_T: aStream << i->first; aStream << "=\""; aStream << i->second.getDouble(); aStream << "\" "; break; case GenericValue::STRING_T: aStream << i->first; aStream << "=\""; aStream << i->second.getString(); aStream << "\" "; break; default: break; } } aStream << '>'; // Write elements for(auto i = entries->begin(); i != end; ++i) { switch(i->second.getType()) { case GenericValue::ARRAY_T: writeArray(i->first, i->second.getArray(), aStream); break; case GenericValue::OBJECT_T: writeObject(i->first, i->second.getObject(), aStream); break; default: break; } } aStream << '<'; aStream << '/'; aStream << aName; aStream << '>'; return true; } // JsonFormat SOLAIRE_EXPORT_CALL XmlFormat::~XmlFormat() { } GenericValue SOLAIRE_EXPORT_CALL XmlFormat::readValue(IStream& aStream) const throw() { try{ //! \todo Implement XML read throw std::runtime_error("Not implemented"); }catch(std::exception& e) { std::cerr << e.what() << std::endl; return GenericValue(); } } bool SOLAIRE_EXPORT_CALL XmlFormat::writeValue(const GenericValue& aValue, OStream& aStream) const throw() { try{ switch(aValue.getType()) { case GenericValue::ARRAY_T: return writeArray(CString("array"), aValue.getArray(), aStream); case GenericValue::OBJECT_T: return writeObject(CString("object"), aValue.getObject(), aStream); default: return false; } }catch(std::exception& e) { std::cerr << e.what() << std::endl; return false; } } Attribute XmlFormat::readAttribute(IStream& aStream) const throw() { if(! skipWhitespace(aStream)) return Attribute(); CString name; char c; if(aStream.end()) return Attribute(); aStream >> c; while(c != '=') { if(aStream.end()) return Attribute(); name += c; aStream >> c; } if(aStream.end()) return Attribute(); aStream >> c; if(c != '"') return Attribute(); CString value; if(aStream.end()) return Attribute(); aStream >> c; while(c != '"') { if(aStream.end()) return Attribute(); name += c; aStream >> c; } return Attribute(name, value); } bool XmlFormat::writeAttribute(const Attribute& aAttribute, OStream& aStream) const throw() { aStream << aAttribute.getName() << "=\"" << aAttribute.getValue() << '"'; return true; } Element XmlFormat::readElement(IStream& aStream) const throw() { if(! skipWhitespace(aStream)) return Element(); char c; Element element; String<char>& name = element.getName(); String<char>& body = element.getBody(); List<Attribute>& attributes = element.getAttributes(); List<Element>& elements = element.getElements(); // Start tag { // Open tag if(aStream.end()) return Element(); aStream >> c; if(c != '<') return Element(); // Read name if(aStream.end()) return Element(); aStream >> c; while(! (std::isspace(c) || c == '/' || c == '>')) { name += c; if(aStream.end()) return Element(); aStream >> c; } // Close tag bool endTag = true; while(endTag) { while(std::isspace(c)) { if(aStream.end()) return Element(); aStream >> c; } if(c == '/') { if(aStream.end()) return Element(); aStream >> c; if(c != '>') return Element(); return element; }else if(c == '>') { endTag = false; }else{ aStream.setOffset(aStream.getOffset() - 1); // Read attributes attributes.pushBack(readAttribute(aStream)); c = aStream.peek<char>(); } } } // Body { // Read body // Read Elements } // End tag { // Open tag while(std::isspace(c)) { if(aStream.end()) return Element(); aStream >> c; } if(aStream.end()) return Element(); aStream >> c; if(c != '<') return Element(); if(aStream.end()) return Element(); aStream >> c; if(c != '/') return Element(); // Read name while(std::isspace(c)) { if(aStream.end()) return Element(); aStream >> c; } CString endName; while(! (std::isspace(c) || c == '>')) { endName += c; if(aStream.end()) return Element(); aStream >> c; } if(name != endName) return Element(); // Close Tag while(c != '>') { if(aStream.end()) return Element(); aStream >> c; } } return element; } bool XmlFormat::writeElement(const Element& aElement, OStream& aStream) const throw() { aStream << '<' << aElement.getName(); const StaticContainer<const Attribute>& attributes = aElement.getAttributes(); if(attributes.size() > 0) { aStream << ' '; for(const Attribute& i : attributes) { writeAttribute(i, aStream); aStream << ' '; } } const int32_t bodySize = aElement.getBody().size(); const int32_t elementCount = aElement.getElements().size(); if(bodySize + elementCount == 0) { aStream << "/>"; }else { aStream << '>'; if(bodySize != 0) { if(elementCount != 0) return false; const StaticContainer<const Element>& elements = aElement.getElements(); for(const Element& i : elements) { writeElement(i, aStream); } }else { aStream << aElement.getBody(); } aStream << "</"; aStream << aElement.getName(); aStream << '>'; } return true; } } <commit_msg>Implemented Element body read<commit_after>//Copyright 2015 Adam Smith // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. // Contact : // Email : [email protected] // GitHub repository : https://github.com/SolaireLibrary/SolaireCPP #include "Solaire/XML/Format.hpp" namespace Solaire { static bool skipWhitespace(IStream& aStream) { if(aStream.end()) return true; char c; aStream >> c; while(std::isspace(c)) { if(aStream.end()) return true; aStream >> c; } aStream.setOffset(aStream.getOffset() - 1); return true; } static bool writeObject(const StringConstant<char>& aName, const GenericObject& aValue, OStream& aStream) throw(); static bool writeArray(const StringConstant<char>& aName, const GenericArray& aValue, OStream& aStream) throw() { aStream << '<'; aStream << aName; if(aValue.size() > 0) { aStream << '>'; const auto end = aValue.end(); for(auto i = aValue.begin(); i != end; ++i) { switch(i->getType()) { case GenericValue::NULL_T: aStream << "<solaire_array_element type=\"null\"/>"; break; case GenericValue::CHAR_T: aStream << "<solaire_array_element type=\"char\" value=\""; aStream << i->getChar(); aStream << "\"/>"; break; case GenericValue::BOOL_T: aStream << "<solaire_array_element type=\"bool\" value=\""; if(i->getBool()) { aStream << "true"; }else { aStream << "false"; } aStream << "\"/>"; break; case GenericValue::UNSIGNED_T: aStream << "<solaire_array_element type=\"number\" value=\""; aStream << i->getUnsigned(); aStream << "\"/>"; break; case GenericValue::SIGNED_T: aStream << "<solaire_array_element type=\"number\" value=\""; aStream << i->getSigned(); aStream << "\"/>"; break; case GenericValue::DOUBLE_T: aStream << "<solaire_array_element type=\"number\" value=\""; aStream << i->getDouble(); aStream << "\"/>"; break; case GenericValue::STRING_T: aStream << "<solaire_array_element type=\"string\" value=\""; aStream << i->getString(); aStream << "\"/>"; break; case GenericValue::ARRAY_T: writeArray(CString("solaire_array_element"), i->getArray(), aStream); break; case GenericValue::OBJECT_T: writeObject(CString("solaire_array_element"), i->getObject(), aStream); break; default: break; } } aStream << '<'; aStream << '/'; aStream << aName; aStream << '>'; }else { aStream << '/'; aStream << '>'; } return true; } static bool writeObject(const StringConstant<char>& aName, const GenericObject& aValue, OStream& aStream) throw() { if(aValue.size() == 0) { aStream << '<'; aStream << aName; aStream << '/'; aStream << '>'; return true; } const auto entries = aValue.getEntries(); const auto end = entries->end(); aStream << '<'; aStream << aName; // Write attributes aStream << ' '; for(auto i = entries->begin(); i != end; ++i) { switch(i->second.getType()) { case GenericValue::NULL_T: aStream << i->first; aStream << "=\"null\" "; break; case GenericValue::CHAR_T: aStream << i->first; aStream << "=\""; aStream << i->second.getChar(); aStream << "\" "; break; case GenericValue::BOOL_T: aStream << i->first; if(i->second.getBool()) { aStream << "=\"true\" "; }else { aStream << "=\"false\" "; } break; case GenericValue::UNSIGNED_T: aStream << i->first; aStream << "=\""; aStream << i->second.getUnsigned(); aStream << "\" "; break; case GenericValue::SIGNED_T: aStream << i->first; aStream << "=\""; aStream << i->second.getSigned(); aStream << "\" "; break; case GenericValue::DOUBLE_T: aStream << i->first; aStream << "=\""; aStream << i->second.getDouble(); aStream << "\" "; break; case GenericValue::STRING_T: aStream << i->first; aStream << "=\""; aStream << i->second.getString(); aStream << "\" "; break; default: break; } } aStream << '>'; // Write elements for(auto i = entries->begin(); i != end; ++i) { switch(i->second.getType()) { case GenericValue::ARRAY_T: writeArray(i->first, i->second.getArray(), aStream); break; case GenericValue::OBJECT_T: writeObject(i->first, i->second.getObject(), aStream); break; default: break; } } aStream << '<'; aStream << '/'; aStream << aName; aStream << '>'; return true; } // JsonFormat SOLAIRE_EXPORT_CALL XmlFormat::~XmlFormat() { } GenericValue SOLAIRE_EXPORT_CALL XmlFormat::readValue(IStream& aStream) const throw() { try{ //! \todo Implement XML read throw std::runtime_error("Not implemented"); }catch(std::exception& e) { std::cerr << e.what() << std::endl; return GenericValue(); } } bool SOLAIRE_EXPORT_CALL XmlFormat::writeValue(const GenericValue& aValue, OStream& aStream) const throw() { try{ switch(aValue.getType()) { case GenericValue::ARRAY_T: return writeArray(CString("array"), aValue.getArray(), aStream); case GenericValue::OBJECT_T: return writeObject(CString("object"), aValue.getObject(), aStream); default: return false; } }catch(std::exception& e) { std::cerr << e.what() << std::endl; return false; } } Attribute XmlFormat::readAttribute(IStream& aStream) const throw() { if(! skipWhitespace(aStream)) return Attribute(); CString name; char c; if(aStream.end()) return Attribute(); aStream >> c; while(c != '=') { if(aStream.end()) return Attribute(); name += c; aStream >> c; } if(aStream.end()) return Attribute(); aStream >> c; if(c != '"') return Attribute(); CString value; if(aStream.end()) return Attribute(); aStream >> c; while(c != '"') { if(aStream.end()) return Attribute(); name += c; aStream >> c; } return Attribute(name, value); } bool XmlFormat::writeAttribute(const Attribute& aAttribute, OStream& aStream) const throw() { aStream << aAttribute.getName() << "=\"" << aAttribute.getValue() << '"'; return true; } Element XmlFormat::readElement(IStream& aStream) const throw() { if(! skipWhitespace(aStream)) return Element(); char c; Element element; String<char>& name = element.getName(); String<char>& body = element.getBody(); List<Attribute>& attributes = element.getAttributes(); List<Element>& elements = element.getElements(); // Start tag { // Open tag if(aStream.end()) return Element(); aStream >> c; if(c != '<') return Element(); // Read name if(aStream.end()) return Element(); aStream >> c; while(! (std::isspace(c) || c == '/' || c == '>')) { name += c; if(aStream.end()) return Element(); aStream >> c; } // Close tag bool endTag = true; while(endTag) { while(std::isspace(c)) { if(aStream.end()) return Element(); aStream >> c; } if(c == '/') { if(aStream.end()) return Element(); aStream >> c; if(c != '>') return Element(); return element; }else if(c == '>') { endTag = false; }else{ aStream.setOffset(aStream.getOffset() - 1); // Read attributes attributes.pushBack(readAttribute(aStream)); c = aStream.peek<char>(); } } } // Body { bool endBody = true; while(endBody){ while(std::isspace(c)) { if(aStream.end()) return Element(); aStream >> c; } if(c == '<'){ if(aStream.end()) return Element(); aStream >> c; if(c == '/'){ endBody = false; aStream.setOffset(aStream.getOffset() - 2); }else { // Read Element aStream.setOffset(aStream.getOffset() - 2); elements.pushBack(readElement(aStream)); c = aStream.peek<char>(); } }else{ // Read body body += c; if(aStream.end()) return Element(); aStream >> c; } } } // End tag { // Open tag while(std::isspace(c)) { if(aStream.end()) return Element(); aStream >> c; } if(aStream.end()) return Element(); aStream >> c; if(c != '<') return Element(); if(aStream.end()) return Element(); aStream >> c; if(c != '/') return Element(); // Read name while(std::isspace(c)) { if(aStream.end()) return Element(); aStream >> c; } CString endName; while(! (std::isspace(c) || c == '>')) { endName += c; if(aStream.end()) return Element(); aStream >> c; } if(name != endName) return Element(); // Close Tag while(c != '>') { if(aStream.end()) return Element(); aStream >> c; } } return element; } bool XmlFormat::writeElement(const Element& aElement, OStream& aStream) const throw() { aStream << '<' << aElement.getName(); const StaticContainer<const Attribute>& attributes = aElement.getAttributes(); if(attributes.size() > 0) { aStream << ' '; for(const Attribute& i : attributes) { writeAttribute(i, aStream); aStream << ' '; } } const int32_t bodySize = aElement.getBody().size(); const int32_t elementCount = aElement.getElements().size(); if(bodySize + elementCount == 0) { aStream << "/>"; }else { aStream << '>'; if(bodySize != 0) { if(elementCount != 0) return false; const StaticContainer<const Element>& elements = aElement.getElements(); for(const Element& i : elements) { writeElement(i, aStream); } }else { aStream << aElement.getBody(); } aStream << "</"; aStream << aElement.getName(); aStream << '>'; } return true; } } <|endoftext|>
<commit_before><commit_msg>fdo#60491: embeddedobj: catch exception in fallback path<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: rotmodit.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 18:23:41 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SVX_ROTMODIT_HXX #define _SVX_ROTMODIT_HXX #ifndef _SFXENUMITEM_HXX //autogen #include <svtools/eitem.hxx> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif //---------------------------------------------------------------------------- // Ausrichtung bei gedrehtem Text enum SvxRotateMode { SVX_ROTATE_MODE_STANDARD, SVX_ROTATE_MODE_TOP, SVX_ROTATE_MODE_CENTER, SVX_ROTATE_MODE_BOTTOM }; class SVX_DLLPUBLIC SvxRotateModeItem: public SfxEnumItem { public: TYPEINFO(); SvxRotateModeItem( SvxRotateMode eMode=SVX_ROTATE_MODE_STANDARD, USHORT nWhich=0); SvxRotateModeItem( const SvxRotateModeItem& rItem ); ~SvxRotateModeItem(); virtual USHORT GetValueCount() const; virtual String GetValueText( USHORT nVal ) const; virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; virtual SfxPoolItem* Create(SvStream &, USHORT) const; virtual USHORT GetVersion( USHORT nFileVersion ) const; virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres, SfxMapUnit eCoreMetric, SfxMapUnit ePresMetric, String& rText, const IntlWrapper * = 0 ) const; virtual sal_Bool QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const; virtual sal_Bool PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ); }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.5.1252); FILE MERGED 2008/04/01 15:49:20 thb 1.5.1252.3: #i85898# Stripping all external header guards 2008/04/01 12:46:25 thb 1.5.1252.2: #i85898# Stripping all external header guards 2008/03/31 14:17:59 rt 1.5.1252.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: rotmodit.hxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SVX_ROTMODIT_HXX #define _SVX_ROTMODIT_HXX #include <svtools/eitem.hxx> #include "svx/svxdllapi.h" //---------------------------------------------------------------------------- // Ausrichtung bei gedrehtem Text enum SvxRotateMode { SVX_ROTATE_MODE_STANDARD, SVX_ROTATE_MODE_TOP, SVX_ROTATE_MODE_CENTER, SVX_ROTATE_MODE_BOTTOM }; class SVX_DLLPUBLIC SvxRotateModeItem: public SfxEnumItem { public: TYPEINFO(); SvxRotateModeItem( SvxRotateMode eMode=SVX_ROTATE_MODE_STANDARD, USHORT nWhich=0); SvxRotateModeItem( const SvxRotateModeItem& rItem ); ~SvxRotateModeItem(); virtual USHORT GetValueCount() const; virtual String GetValueText( USHORT nVal ) const; virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; virtual SfxPoolItem* Create(SvStream &, USHORT) const; virtual USHORT GetVersion( USHORT nFileVersion ) const; virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres, SfxMapUnit eCoreMetric, SfxMapUnit ePresMetric, String& rText, const IntlWrapper * = 0 ) const; virtual sal_Bool QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const; virtual sal_Bool PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ); }; #endif <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // Provide BZFS with a list server connection /* class header */ #include "ListServerConnection.h" /* system implementation headers */ #include <string.h> #include <string> #include <math.h> #include <errno.h> #include <set> /* common implementation headers */ #include "bzfio.h" #include "version.h" #include "TextUtils.h" #include "Protocol.h" #include "GameKeeper.h" #include "bzfsAPI.h" #include "WorldEventManager.h" /* local implementation headers */ #include "CmdLineOptions.h" // FIXME remove externs! extern PingPacket getTeamCounts(); extern uint16_t curMaxPlayers; extern void sendMessage(int playerIndex, PlayerId targetPlayer, const char *message); extern CmdLineOptions *clOptions; const int ListServerLink::NotConnected = -1; ListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle, std::string _advertiseGroups) { std::string bzfsUserAgent = "bzfs "; bzfsUserAgent += getAppVersion(); setURL(listServerURL); setUserAgent(bzfsUserAgent); setDNSCachingTime(-1); setTimeout(10); if (clOptions->pingInterface != "") setInterface(clOptions->pingInterface); publicizeAddress = publicizedAddress; publicizeDescription = publicizedTitle; advertiseGroups = _advertiseGroups; //if this c'tor is called, it's safe to publicize publicizeServer = true; queuedRequest = false; // schedule initial ADD message queueMessage(ListServerLink::ADD); } ListServerLink::ListServerLink() { // does not create a usable link, so checks should be placed // in all public member functions to ensure that nothing tries // to happen if publicizeServer is false publicizeServer = false; } ListServerLink::~ListServerLink() { // now tell the list server that we're going away. this can // take some time but we don't want to wait too long. we do // our own multiplexing loop and wait for a maximum of 3 seconds // total. // if we aren't supposed to be publicizing, skip the whole thing // and don't waste 3 seconds. if (!publicizeServer) return; queueMessage(ListServerLink::REMOVE); for (int i = 0; i < 12; i++) { cURLManager::perform(); if (!queuedRequest) break; TimeKeeper::sleep(0.25f); } } void ListServerLink::finalization(char *data, unsigned int length, bool good) { queuedRequest = false; if (good && (length < 2048)) { char buf[2048]; memcpy(buf, data, length); int bytes = length; buf[bytes]=0; char* base = buf; static char *tokGoodIdentifier = "TOKGOOD: "; static char *tokBadIdentifier = "TOKBAD: "; // walks entire reply including HTTP headers while (*base) { // find next newline char* scan = base; while (*scan && *scan != '\r' && *scan != '\n') scan++; // if no newline then no more complete replies if (*scan != '\r' && *scan != '\n') break; while (*scan && (*scan == '\r' || *scan == '\n')) *scan++ = '\0'; DEBUG4("Got line: \"%s\"\n", base); // TODO don't do this if we don't want central logins if (strncmp(base, tokGoodIdentifier, strlen(tokGoodIdentifier)) == 0) { char *callsign, *group; callsign = base + strlen(tokGoodIdentifier); DEBUG3("Got: %s\n", base); group = callsign; while (*group && (*group != ':')) group++; while (*group && (*group == ':')) *group++ = 0; int playerIndex; GameKeeper::Player *playerData = NULL; for (playerIndex = 0; playerIndex < curMaxPlayers; playerIndex++) { playerData = GameKeeper::Player::getPlayerByIndex(playerIndex); if (!playerData) continue; if (playerData->_LSAState != GameKeeper::Player::checking) continue; if (!TextUtils::compare_nocase(playerData->player.getCallSign(), callsign)) break; } if (playerIndex < curMaxPlayers) { // don't accept the global auth if there's a local account // of the same name and the local account is not marked as // being the same as the global account if (!playerData->accessInfo.hasRealPassword() || playerData->accessInfo.getUserInfo(callsign) .hasGroup("LOCAL.GLOBAL")) { playerData->_LSAState = GameKeeper::Player::verified; if (!playerData->accessInfo.isRegistered()) playerData->accessInfo.storeInfo(NULL); playerData->accessInfo.setPermissionRights(); while (*group) { char *nextgroup = group; while (*nextgroup && (*nextgroup != ':')) nextgroup++; while (*nextgroup && (*nextgroup == ':')) *nextgroup++ = 0; playerData->accessInfo.addGroup(group); group = nextgroup; } playerData->authentication.global(true); sendMessage(ServerPlayer, playerIndex, "Global login approved!"); } else { playerData->_LSAState = GameKeeper::Player::failed; sendMessage(ServerPlayer, playerIndex, "Global login rejected. " "This callsign is registered locally on this " "server."); sendMessage(ServerPlayer, playerIndex, "If the local account is yours, " "/identify, /deregister and reconnnect, " "or ask an admin for the LOCAL.GLOBAL group."); sendMessage(ServerPlayer, playerIndex, "If it is not yours, please ask an admin " "to deregister it so that you may use your global " "callsign."); } playerData->player.clearToken(); } } else if (!strncmp(base, tokBadIdentifier, strlen(tokBadIdentifier))) { char *callsign; callsign = base + strlen(tokBadIdentifier); int playerIndex; GameKeeper::Player *playerData = NULL; for (playerIndex = 0; playerIndex < curMaxPlayers; playerIndex++) { playerData = GameKeeper::Player::getPlayerByIndex(playerIndex); if (!playerData) continue; if (playerData->_LSAState != GameKeeper::Player::checking) continue; if (!TextUtils::compare_nocase(playerData->player.getCallSign(), callsign)) break; } DEBUG3("Got: [%d] %s\n", playerIndex, base); if (playerIndex < curMaxPlayers) { playerData->_LSAState = GameKeeper::Player::failed; sendMessage(ServerPlayer, playerIndex, "Global login rejected, bad token."); playerData->player.clearToken(); } } // next reply base = scan; } } for (int i = 0; i < curMaxPlayers; i++) { GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i); if (!playerData) continue; if (playerData->_LSAState != GameKeeper::Player::checking) continue; playerData->_LSAState = GameKeeper::Player::timed; } if (nextMessageType != ListServerLink::NONE) { // There was a pending request arrived after we write: // we should redo all the stuff sendQueuedMessages(); } } void ListServerLink::queueMessage(MessageType type) { // ignore if the server is not public if (!publicizeServer) return; // record next message to send. nextMessageType = type; if (!queuedRequest) sendQueuedMessages(); else DEBUG3("There is a message already queued to the list server: not sending this one yet.\n"); } void ListServerLink::sendQueuedMessages() { queuedRequest = true; if (nextMessageType == ListServerLink::ADD) { DEBUG3("Queuing ADD message to list server\n"); bz_ListServerUpdateEvent updateEvent; updateEvent.address = publicizeAddress; updateEvent.description = publicizeDescription; updateEvent.groups = advertiseGroups; worldEventManager.callEvents(bz_eListServerUpdateEvent,&updateEvent); addMe(getTeamCounts(), std::string(updateEvent.address.c_str()), std::string(updateEvent.description.c_str()), std::string(updateEvent.groups.c_str())); lastAddTime = TimeKeeper::getCurrent(); } else if (nextMessageType == ListServerLink::REMOVE) { DEBUG3("Queuing REMOVE message to list server\n"); removeMe(publicizeAddress); } nextMessageType = ListServerLink::NONE; } void ListServerLink::addMe(PingPacket pingInfo, std::string publicizedAddress, std::string publicizedTitle, std::string _advertiseGroups) { std::string msg; std::string hdr; // encode ping reply as ascii hex digits plus NULL char gameInfo[PingPacketHexPackedSize + 1]; pingInfo.packHex(gameInfo); // send ADD message (must send blank line) msg = "action=ADD&nameport="; msg += publicizedAddress; msg += "&version="; msg += getServerVersion(); msg += "&gameinfo="; msg += gameInfo; msg += "&build="; msg += getAppVersion(); msg += "&checktokens="; std::set<std::string> callSigns; // callsign1@ip1=token1%0D%0Acallsign2@ip2=token2%0D%0A for (int i = 0; i < curMaxPlayers; i++) { GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i); if (!playerData) continue; if ((playerData->_LSAState != GameKeeper::Player::required) && (playerData->_LSAState != GameKeeper::Player::requesting)) continue; if (callSigns.count(playerData->player.getCallSign())) continue; callSigns.insert(playerData->player.getCallSign()); playerData->_LSAState = GameKeeper::Player::checking; NetHandler *handler = playerData->netHandler; msg += TextUtils::url_encode(playerData->player.getCallSign()); Address addr = handler->getIPAddress(); if (!addr.isPrivate()) { msg += "@"; msg += handler->getTargetIP(); } msg += "="; msg += playerData->player.getToken(); msg += "%0D%0A"; } msg += "&groups="; // *groups=GROUP0%0D%0AGROUP1%0D%0A PlayerAccessMap::iterator itr = groupAccess.begin(); for ( ; itr != groupAccess.end(); itr++) { if (itr->first.substr(0, 6) != "LOCAL.") { msg += itr->first.c_str(); msg += "%0D%0A"; } } msg += "&advertgroups="; msg += _advertiseGroups; msg += "&title="; msg += publicizedTitle; setPostMode(msg); addHandle(); } void ListServerLink::removeMe(std::string publicizedAddress) { std::string msg; msg = "action=REMOVE&nameport="; msg += publicizedAddress; setPostMode(msg); addHandle(); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>better URL-encode server description and advertised group names<commit_after>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // Provide BZFS with a list server connection /* class header */ #include "ListServerConnection.h" /* system implementation headers */ #include <string.h> #include <string> #include <math.h> #include <errno.h> #include <set> /* common implementation headers */ #include "bzfio.h" #include "version.h" #include "TextUtils.h" #include "Protocol.h" #include "GameKeeper.h" #include "bzfsAPI.h" #include "WorldEventManager.h" /* local implementation headers */ #include "CmdLineOptions.h" // FIXME remove externs! extern PingPacket getTeamCounts(); extern uint16_t curMaxPlayers; extern void sendMessage(int playerIndex, PlayerId targetPlayer, const char *message); extern CmdLineOptions *clOptions; const int ListServerLink::NotConnected = -1; ListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle, std::string _advertiseGroups) { std::string bzfsUserAgent = "bzfs "; bzfsUserAgent += getAppVersion(); setURL(listServerURL); setUserAgent(bzfsUserAgent); setDNSCachingTime(-1); setTimeout(10); if (clOptions->pingInterface != "") setInterface(clOptions->pingInterface); publicizeAddress = publicizedAddress; publicizeDescription = publicizedTitle; advertiseGroups = _advertiseGroups; //if this c'tor is called, it's safe to publicize publicizeServer = true; queuedRequest = false; // schedule initial ADD message queueMessage(ListServerLink::ADD); } ListServerLink::ListServerLink() { // does not create a usable link, so checks should be placed // in all public member functions to ensure that nothing tries // to happen if publicizeServer is false publicizeServer = false; } ListServerLink::~ListServerLink() { // now tell the list server that we're going away. this can // take some time but we don't want to wait too long. we do // our own multiplexing loop and wait for a maximum of 3 seconds // total. // if we aren't supposed to be publicizing, skip the whole thing // and don't waste 3 seconds. if (!publicizeServer) return; queueMessage(ListServerLink::REMOVE); for (int i = 0; i < 12; i++) { cURLManager::perform(); if (!queuedRequest) break; TimeKeeper::sleep(0.25f); } } void ListServerLink::finalization(char *data, unsigned int length, bool good) { queuedRequest = false; if (good && (length < 2048)) { char buf[2048]; memcpy(buf, data, length); int bytes = length; buf[bytes]=0; char* base = buf; static char *tokGoodIdentifier = "TOKGOOD: "; static char *tokBadIdentifier = "TOKBAD: "; // walks entire reply including HTTP headers while (*base) { // find next newline char* scan = base; while (*scan && *scan != '\r' && *scan != '\n') scan++; // if no newline then no more complete replies if (*scan != '\r' && *scan != '\n') break; while (*scan && (*scan == '\r' || *scan == '\n')) *scan++ = '\0'; DEBUG4("Got line: \"%s\"\n", base); // TODO don't do this if we don't want central logins if (strncmp(base, tokGoodIdentifier, strlen(tokGoodIdentifier)) == 0) { char *callsign, *group; callsign = base + strlen(tokGoodIdentifier); DEBUG3("Got: %s\n", base); group = callsign; while (*group && (*group != ':')) group++; while (*group && (*group == ':')) *group++ = 0; int playerIndex; GameKeeper::Player *playerData = NULL; for (playerIndex = 0; playerIndex < curMaxPlayers; playerIndex++) { playerData = GameKeeper::Player::getPlayerByIndex(playerIndex); if (!playerData) continue; if (playerData->_LSAState != GameKeeper::Player::checking) continue; if (!TextUtils::compare_nocase(playerData->player.getCallSign(), callsign)) break; } if (playerIndex < curMaxPlayers) { // don't accept the global auth if there's a local account // of the same name and the local account is not marked as // being the same as the global account if (!playerData->accessInfo.hasRealPassword() || playerData->accessInfo.getUserInfo(callsign) .hasGroup("LOCAL.GLOBAL")) { playerData->_LSAState = GameKeeper::Player::verified; if (!playerData->accessInfo.isRegistered()) playerData->accessInfo.storeInfo(NULL); playerData->accessInfo.setPermissionRights(); while (*group) { char *nextgroup = group; while (*nextgroup && (*nextgroup != ':')) nextgroup++; while (*nextgroup && (*nextgroup == ':')) *nextgroup++ = 0; playerData->accessInfo.addGroup(group); group = nextgroup; } playerData->authentication.global(true); sendMessage(ServerPlayer, playerIndex, "Global login approved!"); } else { playerData->_LSAState = GameKeeper::Player::failed; sendMessage(ServerPlayer, playerIndex, "Global login rejected. " "This callsign is registered locally on this " "server."); sendMessage(ServerPlayer, playerIndex, "If the local account is yours, " "/identify, /deregister and reconnnect, " "or ask an admin for the LOCAL.GLOBAL group."); sendMessage(ServerPlayer, playerIndex, "If it is not yours, please ask an admin " "to deregister it so that you may use your global " "callsign."); } playerData->player.clearToken(); } } else if (!strncmp(base, tokBadIdentifier, strlen(tokBadIdentifier))) { char *callsign; callsign = base + strlen(tokBadIdentifier); int playerIndex; GameKeeper::Player *playerData = NULL; for (playerIndex = 0; playerIndex < curMaxPlayers; playerIndex++) { playerData = GameKeeper::Player::getPlayerByIndex(playerIndex); if (!playerData) continue; if (playerData->_LSAState != GameKeeper::Player::checking) continue; if (!TextUtils::compare_nocase(playerData->player.getCallSign(), callsign)) break; } DEBUG3("Got: [%d] %s\n", playerIndex, base); if (playerIndex < curMaxPlayers) { playerData->_LSAState = GameKeeper::Player::failed; sendMessage(ServerPlayer, playerIndex, "Global login rejected, bad token."); playerData->player.clearToken(); } } // next reply base = scan; } } for (int i = 0; i < curMaxPlayers; i++) { GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i); if (!playerData) continue; if (playerData->_LSAState != GameKeeper::Player::checking) continue; playerData->_LSAState = GameKeeper::Player::timed; } if (nextMessageType != ListServerLink::NONE) { // There was a pending request arrived after we write: // we should redo all the stuff sendQueuedMessages(); } } void ListServerLink::queueMessage(MessageType type) { // ignore if the server is not public if (!publicizeServer) return; // record next message to send. nextMessageType = type; if (!queuedRequest) sendQueuedMessages(); else DEBUG3("There is a message already queued to the list server: not sending this one yet.\n"); } void ListServerLink::sendQueuedMessages() { queuedRequest = true; if (nextMessageType == ListServerLink::ADD) { DEBUG3("Queuing ADD message to list server\n"); bz_ListServerUpdateEvent updateEvent; updateEvent.address = publicizeAddress; updateEvent.description = publicizeDescription; updateEvent.groups = advertiseGroups; worldEventManager.callEvents(bz_eListServerUpdateEvent,&updateEvent); addMe(getTeamCounts(), std::string(updateEvent.address.c_str()), std::string(updateEvent.description.c_str()), std::string(updateEvent.groups.c_str())); lastAddTime = TimeKeeper::getCurrent(); } else if (nextMessageType == ListServerLink::REMOVE) { DEBUG3("Queuing REMOVE message to list server\n"); removeMe(publicizeAddress); } nextMessageType = ListServerLink::NONE; } void ListServerLink::addMe(PingPacket pingInfo, std::string publicizedAddress, std::string publicizedTitle, std::string _advertiseGroups) { std::string msg; std::string hdr; // encode ping reply as ascii hex digits plus NULL char gameInfo[PingPacketHexPackedSize + 1]; pingInfo.packHex(gameInfo); // send ADD message (must send blank line) msg = "action=ADD&nameport="; msg += publicizedAddress; msg += "&version="; msg += getServerVersion(); msg += "&gameinfo="; msg += gameInfo; msg += "&build="; msg += getAppVersion(); msg += "&checktokens="; std::set<std::string> callSigns; // callsign1@ip1=token1%0D%0Acallsign2@ip2=token2%0D%0A for (int i = 0; i < curMaxPlayers; i++) { GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i); if (!playerData) continue; if ((playerData->_LSAState != GameKeeper::Player::required) && (playerData->_LSAState != GameKeeper::Player::requesting)) continue; if (callSigns.count(playerData->player.getCallSign())) continue; callSigns.insert(playerData->player.getCallSign()); playerData->_LSAState = GameKeeper::Player::checking; NetHandler *handler = playerData->netHandler; msg += TextUtils::url_encode(playerData->player.getCallSign()); Address addr = handler->getIPAddress(); if (!addr.isPrivate()) { msg += "@"; msg += handler->getTargetIP(); } msg += "="; msg += playerData->player.getToken(); msg += "%0D%0A"; } msg += "&groups="; // *groups=GROUP0%0D%0AGROUP1%0D%0A PlayerAccessMap::iterator itr = groupAccess.begin(); for ( ; itr != groupAccess.end(); itr++) { if (itr->first.substr(0, 6) != "LOCAL.") { msg += itr->first.c_str(); msg += "%0D%0A"; } } msg += "&advertgroups="; msg += TextUtils::url_encode(_advertiseGroups); msg += "&title="; msg += TextUtils::url_encode(publicizedTitle); setPostMode(msg); addHandle(); } void ListServerLink::removeMe(std::string publicizedAddress) { std::string msg; msg = "action=REMOVE&nameport="; msg += publicizedAddress; setPostMode(msg); addHandle(); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>#include "PhysicsManager.hpp" #include <btBulletDynamicsCommon.h> #include <BulletCollision/CollisionDispatch/btGhostObject.h> #include <glm/gtx/quaternion.hpp> #include "../Component/RigidBody.hpp" #include "../Component/Shape.hpp" #include "../Entity/Entity.hpp" #include "../Physics/GlmConversion.hpp" #include "../Physics/Shape.hpp" #include "../Physics/Trigger.hpp" #include "../Physics/TriggerObserver.hpp" #include "../Util/Json.hpp" #ifdef USINGMEMTRACK #include <MemTrackInclude.hpp> #endif PhysicsManager::PhysicsManager() { // The broadphase is used to quickly cull bodies that will not collide with // each other, normally by leveraging some simpler (and rough) test such as // bounding boxes. broadphase = new btDbvtBroadphase; // With the collision configuration one can configure collision detection // algorithms. collisionConfiguration = new btDefaultCollisionConfiguration; dispatcher = new btCollisionDispatcher(collisionConfiguration); // The solver makes objects interact by making use of gravity, collisions, // game logic supplied forces, and constraints. solver = new btSequentialImpulseConstraintSolver; // The dynamics world encompasses objects included in the simulation. dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration); // Y axis up dynamicsWorld->setGravity(btVector3(0, -9.82, 0)); // Set the lockbox key we will use for lockboxes created in here. triggerLockBoxKey.reset(new Utility::LockBox<Physics::Trigger>::Key()); } PhysicsManager::~PhysicsManager() { delete dynamicsWorld; delete solver; delete dispatcher; delete collisionConfiguration; delete broadphase; for (auto t : triggers) delete t; } void PhysicsManager::Update(float deltaTime) { for (auto rigidBodyComp : rigidBodyComponents.GetAll()) { if (rigidBodyComp->IsKilled() || !rigidBodyComp->entity->enabled) { continue; } auto worldPos = rigidBodyComp->entity->GetWorldPosition(); auto worldOrientation = rigidBodyComp->entity->GetWorldOrientation(); if (rigidBodyComp->ghost) { rigidBodyComp->SetPosition(worldPos); rigidBodyComp->SetOrientation(worldOrientation); rigidBodyComp->ghostObject->activate(true); } else if (rigidBodyComp->IsKinematic()) { rigidBodyComp->SetPosition(worldPos); rigidBodyComp->SetOrientation(worldOrientation); if (rigidBodyComp->GetHaltMovement()) { btTransform trans; rigidBodyComp->GetBulletRigidBody()->getMotionState()->getWorldTransform(trans); // Proceed twice to prevent interpolation of velocities. rigidBodyComp->GetBulletRigidBody()->proceedToTransform(trans); rigidBodyComp->GetBulletRigidBody()->proceedToTransform(trans); rigidBodyComp->SetHaltMovement(false); } } else if (rigidBodyComp->GetForceTransformSync()) { dynamicsWorld->removeRigidBody(rigidBodyComp->GetBulletRigidBody()); rigidBodyComp->SetPosition(worldPos); rigidBodyComp->SetOrientation(worldOrientation); rigidBodyComp->GetBulletRigidBody()->activate(true); // To wake up from potentially sleeping state dynamicsWorld->addRigidBody(rigidBodyComp->GetBulletRigidBody()); rigidBodyComp->SetForceTransformSync(false); } } dynamicsWorld->stepSimulation(deltaTime, 10); for (auto trigger : triggers) { trigger->Process(*dynamicsWorld); } } void PhysicsManager::UpdateEntityTransforms() { for (auto rigidBodyComp : rigidBodyComponents.GetAll()) { if (rigidBodyComp->IsKilled() || !rigidBodyComp->entity->enabled) continue; Entity* entity = rigidBodyComp->entity; auto trans = rigidBodyComp->GetBulletRigidBody()->getWorldTransform(); if (!rigidBodyComp->ghost && !rigidBodyComp->IsKinematic()) { entity->SetWorldPosition(Physics::btToGlm(trans.getOrigin())); entity->SetWorldOrientation(Physics::btToGlm(trans.getRotation())); } } } void PhysicsManager::OnTriggerEnter(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object, std::function<void()> callback) { // Add the callback to the trigger observer trigger.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) { trigger.ForObserver(object->GetBulletCollisionObject(), [&callback](Physics::TriggerObserver& observer) { observer.OnEnter(callback); }); }); } void PhysicsManager::ForgetTriggerEnter(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object) { trigger.Open(triggerLockBoxKey, [object](Physics::Trigger& trigger) { trigger.ForObserver(object->GetBulletCollisionObject(), [](Physics::TriggerObserver& observer) { observer.ForgetEnter(); }); }); } void PhysicsManager::OnTriggerRetain(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object, std::function<void()> callback) { // Add the callback to the trigger observer trigger.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) { trigger.ForObserver(object->GetBulletCollisionObject(), [&callback](::Physics::TriggerObserver& observer) { observer.OnRetain(callback); }); }); } void PhysicsManager::ForgetTriggerRetain(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object) { trigger.Open(triggerLockBoxKey, [object](Physics::Trigger& trigger) { trigger.ForObserver(object->GetBulletCollisionObject(), [](Physics::TriggerObserver& observer) { observer.ForgetRetain(); }); }); } void PhysicsManager::OnTriggerLeave(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object, std::function<void()> callback) { // Add the callback to the trigger observer trigger.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) { trigger.ForObserver(object->GetBulletCollisionObject(), [&callback](::Physics::TriggerObserver& observer) { observer.OnLeave(callback); }); }); } void PhysicsManager::ForgetTriggerLeave(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object) { trigger.Open(triggerLockBoxKey, [object](Physics::Trigger& trigger) { trigger.ForObserver(object->GetBulletCollisionObject(), [](Physics::TriggerObserver& observer) { observer.ForgetLeave(); }); }); } Component::RigidBody* PhysicsManager::CreateRigidBody(Entity* owner) { auto comp = rigidBodyComponents.Create(); comp->entity = owner; comp->NewBulletRigidBody(1.0f); auto shapeComp = comp->entity->GetComponent<Component::Shape>(); if (shapeComp) { comp->SetCollisionShape(shapeComp->GetShape()); comp->SetMass(1.0f); dynamicsWorld->addRigidBody(comp->GetBulletRigidBody()); } return comp; } Component::RigidBody* PhysicsManager::CreateRigidBody(Entity* owner, const Json::Value& node) { auto comp = rigidBodyComponents.Create(); comp->entity = owner; auto mass = node.get("mass", 1.0f).asFloat(); comp->NewBulletRigidBody(mass); auto friction = node.get("friction", 0.5f).asFloat(); comp->SetFriction(friction); auto rollingFriction = node.get("rollingFriction", 0.0f).asFloat(); comp->SetRollingFriction(rollingFriction); auto spinningFriction = node.get("spinningFriction", 0.0f).asFloat(); comp->SetSpinningFriction(spinningFriction); auto cor = node.get("cor", 0.0f).asFloat(); comp->SetRestitution(cor); auto linearDamping = node.get("linearDamping", 0.0f).asFloat(); comp->SetLinearDamping(linearDamping); auto angularDamping = node.get("angularDamping", 0.0f).asFloat(); comp->SetAngularDamping(angularDamping); auto kinematic = node.get("kinematic", false).asFloat(); if (kinematic) comp->MakeKinematic(); auto ghost = node.get("ghost", false).asBool(); if (ghost) comp->SetGhost(ghost); auto shapeComp = comp->entity->GetComponent<Component::Shape>(); if (shapeComp) { comp->SetCollisionShape(shapeComp->GetShape()); comp->SetMass(mass); dynamicsWorld->addRigidBody(comp->GetBulletRigidBody()); } return comp; } Component::Shape* PhysicsManager::CreateShape(Entity* owner) { auto comp = shapeComponents.Create(); comp->entity = owner; auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Sphere(1.0f))); comp->SetShape(shape); auto rigidBodyComp = comp->entity->GetComponent<Component::RigidBody>(); if (rigidBodyComp) { rigidBodyComp->SetCollisionShape(comp->GetShape()); rigidBodyComp->SetMass(rigidBodyComp->GetMass()); dynamicsWorld->addRigidBody(rigidBodyComp->GetBulletRigidBody()); } return comp; } Component::Shape* PhysicsManager::CreateShape(Entity* owner, const Json::Value& node) { auto comp = shapeComponents.Create(); comp->entity = owner; if (node.isMember("sphere")) { auto sphere = node.get("sphere", {}); auto radius = sphere.get("radius", 1.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Sphere(radius))); comp->SetShape(shape); } else if (node.isMember("plane")) { auto plane = node.get("plane", {}); auto normal = Json::LoadVec3(plane.get("normal", {})); auto planeCoeff = plane.get("planeCoeff", 0.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Plane(normal, planeCoeff))); comp->SetShape(shape); } else if (node.isMember("box")) { auto box = node.get("box", {}); auto width = box.get("width", 1.0f).asFloat(); auto height = box.get("height", 1.0f).asFloat(); auto depth = box.get("depth", 1.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Box(width, height, depth))); comp->SetShape(shape); } else if (node.isMember("cylinder")) { auto cylinder = node.get("cylinder", {}); auto radius = cylinder.get("radius", 1.0f).asFloat(); auto length = cylinder.get("length", 1.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Cylinder(radius, length))); comp->SetShape(shape); } else if (node.isMember("cone")) { auto cone = node.get("cone", {}); auto radius = cone.get("radius", 1.0f).asFloat(); auto height = cone.get("height", 1.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Cone(radius, height))); comp->SetShape(shape); } else if (node.isMember("capsule")) { auto capsule = node.get("capsule", {}); auto radius = capsule.get("radius", 1.0f).asFloat(); auto height = capsule.get("height", 1.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Capsule(radius, height))); comp->SetShape(shape); } auto rigidBodyComp = comp->entity->GetComponent<Component::RigidBody>(); if (rigidBodyComp) { rigidBodyComp->SetCollisionShape(comp->GetShape()); rigidBodyComp->SetMass(rigidBodyComp->GetMass()); dynamicsWorld->addRigidBody(rigidBodyComp->GetBulletRigidBody()); } return comp; } Utility::LockBox<Physics::Trigger> PhysicsManager::CreateTrigger(std::shared_ptr<Physics::Shape> shape) { btTransform trans(btQuaternion(0, 0, 0, 1), btVector3(0, 0, 0)); Physics::Trigger* trigger = new Physics::Trigger(trans); trigger->SetCollisionShape(shape); triggers.push_back(trigger); return Utility::LockBox<Physics::Trigger>(triggerLockBoxKey, trigger); } void PhysicsManager::SetPosition(Utility::LockBox<Physics::Trigger> trigger, const glm::vec3& position) { trigger.Open(triggerLockBoxKey, [&position](Physics::Trigger& trigger) { trigger.SetPosition(Physics::glmToBt(position)); }); } void PhysicsManager::SetShape(Component::Shape* comp, std::shared_ptr<::Physics::Shape> shape) { comp->SetShape(shape); auto rigidBodyComp = comp->entity->GetComponent<Component::RigidBody>(); if (rigidBodyComp) rigidBodyComp->SetCollisionShape(comp->GetShape()); } float PhysicsManager::GetMass(Component::RigidBody* comp) { return comp->GetMass(); } void PhysicsManager::SetShape(Utility::LockBox<Physics::Trigger> trigger, std::shared_ptr<Physics::Shape> shape) { trigger.Open(triggerLockBoxKey, [shape](Physics::Trigger& trigger) { trigger.SetCollisionShape(shape); }); } void PhysicsManager::SetMass(Component::RigidBody* comp, float mass) { // Setting mass is only valid with a shape because it also sets inertia. auto shapeComp = comp->entity->GetComponent<Component::Shape>(); if (shapeComp) comp->SetMass(mass); } void PhysicsManager::SetFriction(Component::RigidBody* comp, float friction) { comp->SetFriction(friction); } void PhysicsManager::SetRollingFriction(Component::RigidBody* comp, float friction) { comp->SetRollingFriction(friction); } void PhysicsManager::SetSpinningFriction(Component::RigidBody* comp, float friction) { comp->SetSpinningFriction(friction); } void PhysicsManager::SetRestitution(Component::RigidBody* comp, float cor) { comp->SetRestitution(cor); } void PhysicsManager::SetLinearDamping(Component::RigidBody* comp, float damping) { comp->SetLinearDamping(damping); } void PhysicsManager::SetAngularDamping(Component::RigidBody* comp, float damping) { comp->SetAngularDamping(damping); } void PhysicsManager::MakeKinematic(Component::RigidBody* comp) { comp->MakeKinematic(); } void PhysicsManager::MakeDynamic(Component::RigidBody* comp) { comp->MakeDynamic(); } void PhysicsManager::ForceTransformSync(Component::RigidBody* comp) { comp->SetForceTransformSync(true); } void PhysicsManager::HaltMovement(Component::RigidBody* comp) { comp->SetHaltMovement(true); } const std::vector<Component::Shape*>& PhysicsManager::GetShapeComponents() const { return shapeComponents.GetAll(); } void PhysicsManager::ClearKilledComponents() { rigidBodyComponents.ClearKilled( [this](Component::RigidBody* body) { dynamicsWorld->removeRigidBody(body->GetBulletRigidBody()); }); shapeComponents.ClearKilled(); } <commit_msg>Add the ghost object or rigid body to the dynamics world according to which one is active and remove it properly when destroying components.<commit_after>#include "PhysicsManager.hpp" #include <btBulletDynamicsCommon.h> #include <BulletCollision/CollisionDispatch/btGhostObject.h> #include <glm/gtx/quaternion.hpp> #include "../Component/RigidBody.hpp" #include "../Component/Shape.hpp" #include "../Entity/Entity.hpp" #include "../Physics/GlmConversion.hpp" #include "../Physics/Shape.hpp" #include "../Physics/Trigger.hpp" #include "../Physics/TriggerObserver.hpp" #include "../Util/Json.hpp" #ifdef USINGMEMTRACK #include <MemTrackInclude.hpp> #endif PhysicsManager::PhysicsManager() { // The broadphase is used to quickly cull bodies that will not collide with // each other, normally by leveraging some simpler (and rough) test such as // bounding boxes. broadphase = new btDbvtBroadphase; // With the collision configuration one can configure collision detection // algorithms. collisionConfiguration = new btDefaultCollisionConfiguration; dispatcher = new btCollisionDispatcher(collisionConfiguration); // The solver makes objects interact by making use of gravity, collisions, // game logic supplied forces, and constraints. solver = new btSequentialImpulseConstraintSolver; // The dynamics world encompasses objects included in the simulation. dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration); // Y axis up dynamicsWorld->setGravity(btVector3(0, -9.82, 0)); // Set the lockbox key we will use for lockboxes created in here. triggerLockBoxKey.reset(new Utility::LockBox<Physics::Trigger>::Key()); } PhysicsManager::~PhysicsManager() { delete dynamicsWorld; delete solver; delete dispatcher; delete collisionConfiguration; delete broadphase; for (auto t : triggers) delete t; } void PhysicsManager::Update(float deltaTime) { for (auto rigidBodyComp : rigidBodyComponents.GetAll()) { if (rigidBodyComp->IsKilled() || !rigidBodyComp->entity->enabled) { continue; } auto worldPos = rigidBodyComp->entity->GetWorldPosition(); auto worldOrientation = rigidBodyComp->entity->GetWorldOrientation(); if (rigidBodyComp->ghost) { rigidBodyComp->SetPosition(worldPos); rigidBodyComp->SetOrientation(worldOrientation); rigidBodyComp->ghostObject->activate(true); } else if (rigidBodyComp->IsKinematic()) { rigidBodyComp->SetPosition(worldPos); rigidBodyComp->SetOrientation(worldOrientation); if (rigidBodyComp->GetHaltMovement()) { btTransform trans; rigidBodyComp->GetBulletRigidBody()->getMotionState()->getWorldTransform(trans); // Proceed twice to prevent interpolation of velocities. rigidBodyComp->GetBulletRigidBody()->proceedToTransform(trans); rigidBodyComp->GetBulletRigidBody()->proceedToTransform(trans); rigidBodyComp->SetHaltMovement(false); } } else if (rigidBodyComp->GetForceTransformSync()) { dynamicsWorld->removeRigidBody(rigidBodyComp->GetBulletRigidBody()); rigidBodyComp->SetPosition(worldPos); rigidBodyComp->SetOrientation(worldOrientation); rigidBodyComp->GetBulletRigidBody()->activate(true); // To wake up from potentially sleeping state dynamicsWorld->addRigidBody(rigidBodyComp->GetBulletRigidBody()); rigidBodyComp->SetForceTransformSync(false); } } dynamicsWorld->stepSimulation(deltaTime, 10); for (auto trigger : triggers) { trigger->Process(*dynamicsWorld); } } void PhysicsManager::UpdateEntityTransforms() { for (auto rigidBodyComp : rigidBodyComponents.GetAll()) { if (rigidBodyComp->IsKilled() || !rigidBodyComp->entity->enabled) continue; Entity* entity = rigidBodyComp->entity; auto trans = rigidBodyComp->GetBulletRigidBody()->getWorldTransform(); if (!rigidBodyComp->ghost && !rigidBodyComp->IsKinematic()) { entity->SetWorldPosition(Physics::btToGlm(trans.getOrigin())); entity->SetWorldOrientation(Physics::btToGlm(trans.getRotation())); } } } void PhysicsManager::OnTriggerEnter(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object, std::function<void()> callback) { // Add the callback to the trigger observer trigger.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) { trigger.ForObserver(object->GetBulletCollisionObject(), [&callback](Physics::TriggerObserver& observer) { observer.OnEnter(callback); }); }); } void PhysicsManager::ForgetTriggerEnter(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object) { trigger.Open(triggerLockBoxKey, [object](Physics::Trigger& trigger) { trigger.ForObserver(object->GetBulletCollisionObject(), [](Physics::TriggerObserver& observer) { observer.ForgetEnter(); }); }); } void PhysicsManager::OnTriggerRetain(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object, std::function<void()> callback) { // Add the callback to the trigger observer trigger.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) { trigger.ForObserver(object->GetBulletCollisionObject(), [&callback](::Physics::TriggerObserver& observer) { observer.OnRetain(callback); }); }); } void PhysicsManager::ForgetTriggerRetain(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object) { trigger.Open(triggerLockBoxKey, [object](Physics::Trigger& trigger) { trigger.ForObserver(object->GetBulletCollisionObject(), [](Physics::TriggerObserver& observer) { observer.ForgetRetain(); }); }); } void PhysicsManager::OnTriggerLeave(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object, std::function<void()> callback) { // Add the callback to the trigger observer trigger.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) { trigger.ForObserver(object->GetBulletCollisionObject(), [&callback](::Physics::TriggerObserver& observer) { observer.OnLeave(callback); }); }); } void PhysicsManager::ForgetTriggerLeave(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object) { trigger.Open(triggerLockBoxKey, [object](Physics::Trigger& trigger) { trigger.ForObserver(object->GetBulletCollisionObject(), [](Physics::TriggerObserver& observer) { observer.ForgetLeave(); }); }); } Component::RigidBody* PhysicsManager::CreateRigidBody(Entity* owner) { auto comp = rigidBodyComponents.Create(); comp->entity = owner; comp->NewBulletRigidBody(1.0f); auto shapeComp = comp->entity->GetComponent<Component::Shape>(); if (shapeComp) { comp->SetCollisionShape(shapeComp->GetShape()); comp->SetMass(1.0f); dynamicsWorld->addRigidBody(comp->GetBulletRigidBody()); } return comp; } Component::RigidBody* PhysicsManager::CreateRigidBody(Entity* owner, const Json::Value& node) { auto comp = rigidBodyComponents.Create(); comp->entity = owner; auto mass = node.get("mass", 1.0f).asFloat(); comp->NewBulletRigidBody(mass); auto friction = node.get("friction", 0.5f).asFloat(); comp->SetFriction(friction); auto rollingFriction = node.get("rollingFriction", 0.0f).asFloat(); comp->SetRollingFriction(rollingFriction); auto spinningFriction = node.get("spinningFriction", 0.0f).asFloat(); comp->SetSpinningFriction(spinningFriction); auto cor = node.get("cor", 0.0f).asFloat(); comp->SetRestitution(cor); auto linearDamping = node.get("linearDamping", 0.0f).asFloat(); comp->SetLinearDamping(linearDamping); auto angularDamping = node.get("angularDamping", 0.0f).asFloat(); comp->SetAngularDamping(angularDamping); auto kinematic = node.get("kinematic", false).asFloat(); if (kinematic) comp->MakeKinematic(); auto ghost = node.get("ghost", false).asBool(); if (ghost) comp->SetGhost(ghost); auto shapeComp = comp->entity->GetComponent<Component::Shape>(); if (shapeComp) { comp->SetCollisionShape(shapeComp->GetShape()); comp->SetMass(mass); if (ghost) dynamicsWorld->addCollisionObject(comp->GetBulletCollisionObject()); else dynamicsWorld->addRigidBody(comp->GetBulletRigidBody()); } return comp; } Component::Shape* PhysicsManager::CreateShape(Entity* owner) { auto comp = shapeComponents.Create(); comp->entity = owner; auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Sphere(1.0f))); comp->SetShape(shape); auto rigidBodyComp = comp->entity->GetComponent<Component::RigidBody>(); if (rigidBodyComp) { rigidBodyComp->SetCollisionShape(comp->GetShape()); rigidBodyComp->SetMass(rigidBodyComp->GetMass()); if (rigidBodyComp->ghost) dynamicsWorld->addCollisionObject(rigidBodyComp->GetBulletCollisionObject()); else dynamicsWorld->addRigidBody(rigidBodyComp->GetBulletRigidBody()); } return comp; } Component::Shape* PhysicsManager::CreateShape(Entity* owner, const Json::Value& node) { auto comp = shapeComponents.Create(); comp->entity = owner; if (node.isMember("sphere")) { auto sphere = node.get("sphere", {}); auto radius = sphere.get("radius", 1.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Sphere(radius))); comp->SetShape(shape); } else if (node.isMember("plane")) { auto plane = node.get("plane", {}); auto normal = Json::LoadVec3(plane.get("normal", {})); auto planeCoeff = plane.get("planeCoeff", 0.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Plane(normal, planeCoeff))); comp->SetShape(shape); } else if (node.isMember("box")) { auto box = node.get("box", {}); auto width = box.get("width", 1.0f).asFloat(); auto height = box.get("height", 1.0f).asFloat(); auto depth = box.get("depth", 1.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Box(width, height, depth))); comp->SetShape(shape); } else if (node.isMember("cylinder")) { auto cylinder = node.get("cylinder", {}); auto radius = cylinder.get("radius", 1.0f).asFloat(); auto length = cylinder.get("length", 1.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Cylinder(radius, length))); comp->SetShape(shape); } else if (node.isMember("cone")) { auto cone = node.get("cone", {}); auto radius = cone.get("radius", 1.0f).asFloat(); auto height = cone.get("height", 1.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Cone(radius, height))); comp->SetShape(shape); } else if (node.isMember("capsule")) { auto capsule = node.get("capsule", {}); auto radius = capsule.get("radius", 1.0f).asFloat(); auto height = capsule.get("height", 1.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Capsule(radius, height))); comp->SetShape(shape); } auto rigidBodyComp = comp->entity->GetComponent<Component::RigidBody>(); if (rigidBodyComp) { rigidBodyComp->SetCollisionShape(comp->GetShape()); rigidBodyComp->SetMass(rigidBodyComp->GetMass()); if (rigidBodyComp->ghost) dynamicsWorld->addCollisionObject(rigidBodyComp->GetBulletCollisionObject()); else dynamicsWorld->addRigidBody(rigidBodyComp->GetBulletRigidBody()); } return comp; } Utility::LockBox<Physics::Trigger> PhysicsManager::CreateTrigger(std::shared_ptr<Physics::Shape> shape) { btTransform trans(btQuaternion(0, 0, 0, 1), btVector3(0, 0, 0)); Physics::Trigger* trigger = new Physics::Trigger(trans); trigger->SetCollisionShape(shape); triggers.push_back(trigger); return Utility::LockBox<Physics::Trigger>(triggerLockBoxKey, trigger); } void PhysicsManager::SetPosition(Utility::LockBox<Physics::Trigger> trigger, const glm::vec3& position) { trigger.Open(triggerLockBoxKey, [&position](Physics::Trigger& trigger) { trigger.SetPosition(Physics::glmToBt(position)); }); } void PhysicsManager::SetShape(Component::Shape* comp, std::shared_ptr<::Physics::Shape> shape) { comp->SetShape(shape); auto rigidBodyComp = comp->entity->GetComponent<Component::RigidBody>(); if (rigidBodyComp) rigidBodyComp->SetCollisionShape(comp->GetShape()); } float PhysicsManager::GetMass(Component::RigidBody* comp) { return comp->GetMass(); } void PhysicsManager::SetShape(Utility::LockBox<Physics::Trigger> trigger, std::shared_ptr<Physics::Shape> shape) { trigger.Open(triggerLockBoxKey, [shape](Physics::Trigger& trigger) { trigger.SetCollisionShape(shape); }); } void PhysicsManager::SetMass(Component::RigidBody* comp, float mass) { // Setting mass is only valid with a shape because it also sets inertia. auto shapeComp = comp->entity->GetComponent<Component::Shape>(); if (shapeComp) comp->SetMass(mass); } void PhysicsManager::SetFriction(Component::RigidBody* comp, float friction) { comp->SetFriction(friction); } void PhysicsManager::SetRollingFriction(Component::RigidBody* comp, float friction) { comp->SetRollingFriction(friction); } void PhysicsManager::SetSpinningFriction(Component::RigidBody* comp, float friction) { comp->SetSpinningFriction(friction); } void PhysicsManager::SetRestitution(Component::RigidBody* comp, float cor) { comp->SetRestitution(cor); } void PhysicsManager::SetLinearDamping(Component::RigidBody* comp, float damping) { comp->SetLinearDamping(damping); } void PhysicsManager::SetAngularDamping(Component::RigidBody* comp, float damping) { comp->SetAngularDamping(damping); } void PhysicsManager::MakeKinematic(Component::RigidBody* comp) { comp->MakeKinematic(); } void PhysicsManager::MakeDynamic(Component::RigidBody* comp) { comp->MakeDynamic(); } void PhysicsManager::ForceTransformSync(Component::RigidBody* comp) { comp->SetForceTransformSync(true); } void PhysicsManager::HaltMovement(Component::RigidBody* comp) { comp->SetHaltMovement(true); } const std::vector<Component::Shape*>& PhysicsManager::GetShapeComponents() const { return shapeComponents.GetAll(); } void PhysicsManager::ClearKilledComponents() { rigidBodyComponents.ClearKilled( [this](Component::RigidBody* body) { if (body->ghost) dynamicsWorld->removeCollisionObject(body->GetBulletCollisionObject()); else dynamicsWorld->removeRigidBody(body->GetBulletRigidBody()); }); shapeComponents.ClearKilled(); } <|endoftext|>
<commit_before>#include <windows.h> #include "PopupMenu.hpp" #define TRAY_ID 666 #define TRAY_MSG 666 struct WindowData { PopupMenu* menu; }; void HandleMenuSelection(PopupMenu::MenuItem item, HWND window) { WindowData* data = (WindowData*)GetWindowLongPtr(window, GWLP_USERDATA); if(item.id == data->menu->GetIdByTitle("exit")) SendMessage(window, WM_CLOSE, 0, 0); } LRESULT CALLBACK HitmonWindowProc( HWND window, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { // Handle messages from tray icon case TRAY_MSG: { switch(lParam) { case WM_LBUTTONDOWN: { WindowData* data = (WindowData*)GetWindowLongPtr(window, GWLP_USERDATA); data->menu->Show(); }break; } }break; case WM_CREATE: { // Configure window data WindowData* data = new WindowData(); data->menu = new PopupMenu(window, HandleMenuSelection); data->menu->AddItem(1, "Do something"); data->menu->AddItem(2, "Do something else"); data->menu->AddItem(3, "exit"); // Set userdata SetWindowLongPtr(window, GWLP_USERDATA, (LONG_PTR)data); }break; case WM_DESTROY: { WindowData* data = (WindowData*)GetWindowLongPtr(window, GWLP_USERDATA); delete data->menu; delete data; PostQuitMessage(0); }break; default: { return DefWindowProc(window, msg, wParam, lParam); } } return 0; } WNDCLASSEX CreateWindowClass(HINSTANCE instance) { WNDCLASSEX mainWClass; mainWClass.cbSize = sizeof(WNDCLASSEX); mainWClass.style = CS_HREDRAW | CS_VREDRAW; mainWClass.lpfnWndProc = HitmonWindowProc; mainWClass.cbClsExtra = 0; mainWClass.cbWndExtra = 0; mainWClass.hInstance = instance; mainWClass.hIcon = LoadIcon(0, IDI_SHIELD); mainWClass.hCursor = LoadCursor(0, IDC_CROSS); mainWClass.hbrBackground = 0; mainWClass.lpszMenuName = 0; mainWClass.lpszClassName = "MainWClass"; mainWClass.hIconSm = 0; return mainWClass; } NOTIFYICONDATA ShowTrayIcon(HWND window) { NOTIFYICONDATA rVal; rVal.cbSize = sizeof(rVal); rVal.hWnd = window; rVal.uID = TRAY_ID; rVal.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; rVal.uCallbackMessage = TRAY_MSG; rVal.hIcon = LoadIcon(0, IDI_SHIELD); strncpy(rVal.szTip, "Hitmon is running...", 128); // Set guid later //rVal.guidItem = ...; Shell_NotifyIcon(NIM_ADD, &rVal); return rVal; } int CALLBACK WinMain( HINSTANCE instance, HINSTANCE prevInstance, LPSTR cmdArgs, int cmdShow) { (void)prevInstance; (void)cmdArgs; (void)cmdShow; // Create window class WNDCLASSEX mainWClass = CreateWindowClass(instance); // Register window class if(RegisterClassEx(&mainWClass) == 0) return -1; // Create window HWND window = CreateWindowEx( 0, // Extended window style of the window created "MainWClass", // Class name from previous call to RegisterClass[Ex] "Hitmon", // Window Name 0, // Window style 64, // Initial x position for window 64, // Initial y position for window 640, // Window width 480, // Window height 0, // Handle to parent window 0, // Handle to menu instance, // A handle to the instance of the module to be associated with the window. 0); // Pointer to params for the window if(window == 0) return -1; // Show tray icon NOTIFYICONDATA trayData = ShowTrayIcon(window); MSG msg; int getMsgRVal; while((getMsgRVal = GetMessage(&msg, 0, 0, 0)) != 0) { if(getMsgRVal == -1) return -1; // TODO: Enable it when I want character input //TranslateMessage(&msg); DispatchMessage(&msg); } // Hide tray icon Shell_NotifyIcon(NIM_DELETE, &trayData); return 0; }<commit_msg>Added TranslateMessage in message loop<commit_after>#include <windows.h> #include "PopupMenu.hpp" #define TRAY_ID 666 #define TRAY_MSG 666 struct WindowData { PopupMenu* menu; }; void HandleMenuSelection(PopupMenu::MenuItem item, HWND window) { WindowData* data = (WindowData*)GetWindowLongPtr(window, GWLP_USERDATA); if(item.id == data->menu->GetIdByTitle("exit")) SendMessage(window, WM_CLOSE, 0, 0); } LRESULT CALLBACK HitmonWindowProc( HWND window, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { // Handle messages from tray icon case TRAY_MSG: { switch(lParam) { case WM_LBUTTONDOWN: { WindowData* data = (WindowData*)GetWindowLongPtr(window, GWLP_USERDATA); data->menu->Show(); }break; } }break; case WM_CREATE: { // Configure window data WindowData* data = new WindowData(); data->menu = new PopupMenu(window, HandleMenuSelection); data->menu->AddItem(1, "Do something"); data->menu->AddItem(2, "Do something else"); data->menu->AddItem(3, "exit"); // Set userdata SetWindowLongPtr(window, GWLP_USERDATA, (LONG_PTR)data); }break; case WM_DESTROY: { WindowData* data = (WindowData*)GetWindowLongPtr(window, GWLP_USERDATA); delete data->menu; delete data; PostQuitMessage(0); }break; default: { return DefWindowProc(window, msg, wParam, lParam); } } return 0; } WNDCLASSEX CreateWindowClass(HINSTANCE instance) { WNDCLASSEX mainWClass; mainWClass.cbSize = sizeof(WNDCLASSEX); mainWClass.style = CS_HREDRAW | CS_VREDRAW; mainWClass.lpfnWndProc = HitmonWindowProc; mainWClass.cbClsExtra = 0; mainWClass.cbWndExtra = 0; mainWClass.hInstance = instance; mainWClass.hIcon = LoadIcon(0, IDI_SHIELD); mainWClass.hCursor = LoadCursor(0, IDC_CROSS); mainWClass.hbrBackground = 0; mainWClass.lpszMenuName = 0; mainWClass.lpszClassName = "MainWClass"; mainWClass.hIconSm = 0; return mainWClass; } NOTIFYICONDATA ShowTrayIcon(HWND window) { NOTIFYICONDATA rVal; rVal.cbSize = sizeof(rVal); rVal.hWnd = window; rVal.uID = TRAY_ID; rVal.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; rVal.uCallbackMessage = TRAY_MSG; rVal.hIcon = LoadIcon(0, IDI_SHIELD); strncpy(rVal.szTip, "Hitmon is running...", 128); // Set guid later //rVal.guidItem = ...; Shell_NotifyIcon(NIM_ADD, &rVal); return rVal; } int CALLBACK WinMain( HINSTANCE instance, HINSTANCE prevInstance, LPSTR cmdArgs, int cmdShow) { (void)prevInstance; (void)cmdArgs; (void)cmdShow; // Create window class WNDCLASSEX mainWClass = CreateWindowClass(instance); // Register window class if(RegisterClassEx(&mainWClass) == 0) return -1; // Create window HWND window = CreateWindowEx( 0, // Extended window style of the window created "MainWClass", // Class name from previous call to RegisterClass[Ex] "Hitmon", // Window Name 0, // Window style 64, // Initial x position for window 64, // Initial y position for window 640, // Window width 480, // Window height 0, // Handle to parent window 0, // Handle to menu instance, // A handle to the instance of the module to be associated with the window. 0); // Pointer to params for the window if(window == 0) return -1; // Show tray icon NOTIFYICONDATA trayData = ShowTrayIcon(window); MSG msg; int getMsgRVal; while((getMsgRVal = GetMessage(&msg, 0, 0, 0)) != 0) { if(getMsgRVal == -1) return -1; TranslateMessage(&msg); DispatchMessage(&msg); } // Hide tray icon Shell_NotifyIcon(NIM_DELETE, &trayData); return 0; }<|endoftext|>
<commit_before>#include "tests/Base.hh" #include "topology/Mesh.hh" #include "topology/MorseSmaleComplex.hh" #include <vector> void test1() { ALEPH_TEST_BEGIN( "Simple mesh"); aleph::topology::Mesh<double> M; M.addVertex( 0.0, 0.0, 0.0 ); M.addVertex( 0.0, 1.0, 0.0 ); M.addVertex( 1.0, 0.0, 0.0 ); M.addVertex( 1.5, 1.0, 0.0 ); std::vector<unsigned> f1 = { 0, 1, 2 }; std::vector<unsigned> f2 = { 2, 1, 3 }; M.addFace( f1.begin(), f1.end() ); M.addFace( f2.begin(), f2.end() ); ALEPH_ASSERT_EQUAL( M.numVertices(), 4 ); ALEPH_ASSERT_EQUAL( M.numFaces() , 2 ); ALEPH_ASSERT_THROW( M.hasEdge(0,1) ); ALEPH_ASSERT_THROW( M.hasEdge(1,0) ); ALEPH_ASSERT_THROW( M.hasEdge(1,2) ); ALEPH_ASSERT_THROW( M.hasEdge(2,1) ); ALEPH_ASSERT_THROW( M.hasEdge(0,2) ); ALEPH_ASSERT_THROW( M.hasEdge(2,0) ); ALEPH_ASSERT_EQUAL( M.numConnectedComponents(), 1 ); { auto st = M.star( 0 ); auto faces = M.faces(); ALEPH_ASSERT_EQUAL( st.numVertices(), 3 ); ALEPH_ASSERT_EQUAL( st.numFaces(), 1 ); ALEPH_ASSERT_THROW( st.hasEdge(0,1) ); ALEPH_ASSERT_THROW( st.hasEdge(1,0) ); ALEPH_ASSERT_THROW( st.hasEdge(1,2) ); ALEPH_ASSERT_THROW( st.hasEdge(2,1) ); ALEPH_ASSERT_THROW( st.hasEdge(0,2) ); ALEPH_ASSERT_THROW( st.hasEdge(2,0) ); ALEPH_ASSERT_EQUAL( faces.front().size(), 3 ); auto v1 = faces.front().at(0); auto v2 = faces.front().at(1); auto v3 = faces.front().at(2); ALEPH_ASSERT_EQUAL( v1, 0 ); ALEPH_ASSERT_EQUAL( v2, 1 ); ALEPH_ASSERT_EQUAL( v3, 2 ); } { auto link = M.link( 0 ); ALEPH_ASSERT_EQUAL( link.size(), 2 ); } ALEPH_TEST_END(); } void test2() { ALEPH_TEST_BEGIN( "More complex mesh" ); aleph::topology::Mesh<double> M; M.addVertex( 0.0, 0.0, 0.0, 0.0 ); M.addVertex( 1.0, 0.0, 0.0, 1.0 ); M.addVertex( 2.0, 0.0, 0.0, 0.0 ); M.addVertex( 0.0, 1.0, 0.0, 1.0 ); M.addVertex( 1.0, 1.0, 0.0, 2.0 ); M.addVertex( 2.0, 1.0, 0.0, 1.0 ); M.addVertex( 0.0, 2.0, 0.0, 0.0 ); M.addVertex( 1.0, 2.0, 0.0, 1.0 ); M.addVertex( 2.0, 2.0, 0.0, 0.0 ); std::vector<unsigned> f1 = { 0, 1, 4, 3 }; std::vector<unsigned> f2 = { 1, 2, 5, 4 }; std::vector<unsigned> f3 = { 4, 5, 8, 7 }; std::vector<unsigned> f4 = { 3, 4, 7, 6 }; M.addFace( f1.begin(), f1.end() ); M.addFace( f2.begin(), f2.end() ); M.addFace( f3.begin(), f3.end() ); M.addFace( f4.begin(), f4.end() ); ALEPH_TEST_END(); } void test3() { ALEPH_TEST_BEGIN( "Simplicial mesh" ); aleph::topology::Mesh<double> M; M.addVertex( 0.0, 0.0, 0.0, 0.0 ); M.addVertex( 1.0, 0.0, 0.0, 1.0 ); M.addVertex( 2.0, 0.0, 0.0, 0.0 ); M.addVertex( 0.0, 1.0, 0.0, 1.0 ); M.addVertex( 1.0, 1.0, 0.0, 2.0 ); M.addVertex( 2.0, 1.0, 0.0, 1.0 ); M.addVertex( 0.0, 2.0, 0.0, 0.0 ); M.addVertex( 1.0, 2.0, 0.0, 1.0 ); M.addVertex( 2.0, 2.0, 0.0, 0.0 ); std::vector<unsigned> f1 = { 0, 1, 4 }; std::vector<unsigned> f2 = { 0, 4, 3 }; std::vector<unsigned> f3 = { 1, 2, 4 }; std::vector<unsigned> f4 = { 2, 5, 4 }; std::vector<unsigned> f5 = { 4, 5, 8 }; std::vector<unsigned> f6 = { 4, 8, 7 }; std::vector<unsigned> f7 = { 3, 4, 6 }; std::vector<unsigned> f8 = { 4, 7, 6 }; M.addFace( f1.begin(), f1.end() ); M.addFace( f2.begin(), f2.end() ); M.addFace( f3.begin(), f3.end() ); M.addFace( f4.begin(), f4.end() ); M.addFace( f5.begin(), f5.end() ); M.addFace( f6.begin(), f6.end() ); M.addFace( f7.begin(), f7.end() ); M.addFace( f8.begin(), f8.end() ); aleph::topology::MorseSmaleComplex<decltype(M)> msc; msc( M ); ALEPH_TEST_END(); } int main(int, char**) { test1(); test2(); test3(); } <commit_msg>Extended tests for meshes<commit_after>#include "tests/Base.hh" #include "topology/Mesh.hh" #include "topology/MorseSmaleComplex.hh" #include <vector> void test1() { ALEPH_TEST_BEGIN( "Simple mesh"); aleph::topology::Mesh<double> M; M.addVertex( 0.0, 0.0, 0.0 ); M.addVertex( 0.0, 1.0, 0.0 ); M.addVertex( 1.0, 0.0, 0.0 ); M.addVertex( 1.5, 1.0, 0.0 ); std::vector<unsigned> f1 = { 0, 1, 2 }; std::vector<unsigned> f2 = { 2, 1, 3 }; M.addFace( f1.begin(), f1.end() ); M.addFace( f2.begin(), f2.end() ); ALEPH_ASSERT_EQUAL( M.numVertices(), 4 ); ALEPH_ASSERT_EQUAL( M.numFaces() , 2 ); ALEPH_ASSERT_THROW( M.hasEdge(0,1) ); ALEPH_ASSERT_THROW( M.hasEdge(1,0) ); ALEPH_ASSERT_THROW( M.hasEdge(1,2) ); ALEPH_ASSERT_THROW( M.hasEdge(2,1) ); ALEPH_ASSERT_THROW( M.hasEdge(0,2) ); ALEPH_ASSERT_THROW( M.hasEdge(2,0) ); ALEPH_ASSERT_EQUAL( M.numConnectedComponents(), 1 ); { auto st = M.star( 0 ); auto faces = M.faces(); ALEPH_ASSERT_EQUAL( st.numVertices(), 3 ); ALEPH_ASSERT_EQUAL( st.numFaces(), 1 ); ALEPH_ASSERT_THROW( st.hasEdge(0,1) ); ALEPH_ASSERT_THROW( st.hasEdge(1,0) ); ALEPH_ASSERT_THROW( st.hasEdge(1,2) ); ALEPH_ASSERT_THROW( st.hasEdge(2,1) ); ALEPH_ASSERT_THROW( st.hasEdge(0,2) ); ALEPH_ASSERT_THROW( st.hasEdge(2,0) ); ALEPH_ASSERT_EQUAL( faces.front().size(), 3 ); auto v1 = faces.front().at(0); auto v2 = faces.front().at(1); auto v3 = faces.front().at(2); ALEPH_ASSERT_EQUAL( v1, 0 ); ALEPH_ASSERT_EQUAL( v2, 1 ); ALEPH_ASSERT_EQUAL( v3, 2 ); } { auto link = M.link( 0 ); ALEPH_ASSERT_EQUAL( link.size(), 2 ); } ALEPH_TEST_END(); } void test2() { ALEPH_TEST_BEGIN( "More complex mesh" ); aleph::topology::Mesh<double> M; M.addVertex( 0.0, 0.0, 0.0, 0.0 ); M.addVertex( 1.0, 0.0, 0.0, 1.0 ); M.addVertex( 2.0, 0.0, 0.0, 0.0 ); M.addVertex( 0.0, 1.0, 0.0, 1.0 ); M.addVertex( 1.0, 1.0, 0.0, 2.0 ); M.addVertex( 2.0, 1.0, 0.0, 1.0 ); M.addVertex( 0.0, 2.0, 0.0, 0.0 ); M.addVertex( 1.0, 2.0, 0.0, 1.0 ); M.addVertex( 2.0, 2.0, 0.0, 0.0 ); std::vector<unsigned> f1 = { 0, 1, 4, 3 }; std::vector<unsigned> f2 = { 1, 2, 5, 4 }; std::vector<unsigned> f3 = { 4, 5, 8, 7 }; std::vector<unsigned> f4 = { 3, 4, 7, 6 }; M.addFace( f1.begin(), f1.end() ); M.addFace( f2.begin(), f2.end() ); M.addFace( f3.begin(), f3.end() ); M.addFace( f4.begin(), f4.end() ); ALEPH_TEST_END(); } void test3() { ALEPH_TEST_BEGIN( "Simplicial mesh" ); aleph::topology::Mesh<double> M; M.addVertex( 0.0, 0.0, 0.0, 0.0 ); M.addVertex( 1.0, 0.0, 0.0, 1.0 ); M.addVertex( 2.0, 0.0, 0.0, 0.0 ); M.addVertex( 0.0, 1.0, 0.0, 1.0 ); M.addVertex( 1.0, 1.0, 0.0, 2.0 ); M.addVertex( 2.0, 1.0, 0.0, 1.0 ); M.addVertex( 0.0, 2.0, 0.0, 0.0 ); M.addVertex( 1.0, 2.0, 0.0, 1.0 ); M.addVertex( 2.0, 2.0, 0.0, 0.0 ); std::vector<unsigned> f1 = { 0, 1, 4 }; std::vector<unsigned> f2 = { 0, 4, 3 }; std::vector<unsigned> f3 = { 1, 2, 4 }; std::vector<unsigned> f4 = { 2, 5, 4 }; std::vector<unsigned> f5 = { 4, 5, 8 }; std::vector<unsigned> f6 = { 4, 8, 7 }; std::vector<unsigned> f7 = { 3, 4, 6 }; std::vector<unsigned> f8 = { 4, 7, 6 }; M.addFace( f1.begin(), f1.end() ); M.addFace( f2.begin(), f2.end() ); M.addFace( f3.begin(), f3.end() ); M.addFace( f4.begin(), f4.end() ); M.addFace( f5.begin(), f5.end() ); M.addFace( f6.begin(), f6.end() ); M.addFace( f7.begin(), f7.end() ); M.addFace( f8.begin(), f8.end() ); { auto l1 = M.link(1); auto l3 = M.link(3); auto l5 = M.link(5); auto l7 = M.link(7); ALEPH_ASSERT_EQUAL( l1.size(), 3 ); ALEPH_ASSERT_EQUAL( l1.size(), l3.size() ); ALEPH_ASSERT_EQUAL( l1.size(), l5.size() ); ALEPH_ASSERT_EQUAL( l1.size(), l7.size() ); auto l4 = M.link(4); ALEPH_ASSERT_EQUAL( l4.size(), 8 ); } aleph::topology::MorseSmaleComplex<decltype(M)> msc; msc( M ); ALEPH_TEST_END(); } int main(int, char**) { test1(); test2(); test3(); } <|endoftext|>
<commit_before>#include <vector> #include <string> #include <fstream> #include "boost/program_options.hpp" #include "boost/algorithm/string.hpp" #include "boost/lexical_cast.hpp" #include "vtrc-client-base/vtrc-client.h" #include "vtrc-common/vtrc-pool-pair.h" #include "vtrc-common/vtrc-exception.h" #include "rfs-iface.h" #include "vtrc-condition-variable.h" #include "vtrc-mutex.h" #include "vtrc-bind.h" #include "vtrc-ref.h" namespace po = boost::program_options; using namespace vtrc; void get_options( po::options_description& desc ) { desc.add_options( ) ("help,?", "help message") ("server,s", po::value<std::string>( ), "server name; <tcp address>:<port> or <pipe/file name>") ("path,p", po::value<std::string>( ), "Init remote path for client") ("pwd,w", "Show current remote path") ("info,i", po::value<std::string>( ), "Show info about remote path") ("list,l", "list remote directory") ("tree,t", "show remote directory as tree") ("pull,g", po::value<std::string>( ), "Download remote file") ("push,u", po::value<std::string>( ), "Upload local file") ("block-size,b", po::value<unsigned>( ), "Block size for pull and push" "; 1-640000") ("mkdir,m", po::value<std::string>( ), "Create remote directory") ("del,d", po::value<std::string>( ), "Remove remote directory" " if it is empty") ; } void connect_to( client::vtrc_client_sptr client, std::string const &name ) { std::vector<std::string> params; std::string::const_reverse_iterator b(name.rbegin( )); std::string::const_reverse_iterator e(name.rend( )); for( ; b!=e ;++b ) { if( *b == ':' ) { std::string::const_reverse_iterator bb(b); ++bb; params.push_back( std::string( name.begin( ), bb.base( )) ); params.push_back( std::string( b.base( ), name.end( ))); break; } } if( params.empty( ) ) { params.push_back( name ); } if( params.size( ) == 1 ) { /// local name client->connect( params[0] ); } else if( params.size( ) == 2 ) { /// tcp client->connect( params[0], params[1]); } } void on_client_ready( vtrc::condition_variable &cond ) { std::cout << "Connection is ready...\n"; cond.notify_all( ); } namespace rfs_examples { /// rfs-directory-list.cpp void list_dir( vtrc::shared_ptr<interfaces::remote_fs> &impl); /// rfs-directory-tree.cpp void tree_dir( vtrc::shared_ptr<interfaces::remote_fs> &impl ); /// rfs-push-file.cpp void push_file( client::vtrc_client_sptr client, const std::string &local_path, size_t block_size ); /// rfs-pull-file.cpp void pull_file( client::vtrc_client_sptr client, vtrc::shared_ptr<interfaces::remote_fs> &impl, const std::string &remote_path, size_t block_size ); /// rfs-mkdir-del.cpp void make_dir( vtrc::shared_ptr<interfaces::remote_fs> &impl, const std::string &path); void make_dir( vtrc::shared_ptr<interfaces::remote_fs> &impl ); void del( vtrc::shared_ptr<interfaces::remote_fs> &impl, const std::string &path); void del( vtrc::shared_ptr<interfaces::remote_fs> &impl ); } int start( const po::variables_map &params ) { if( params.count( "server" ) == 0 ) { throw std::runtime_error("Server is not defined;\n" "Use --help for details"); } /// will use only one thread for io operations. /// because we don't have callbacks or events from server-side common::pool_pair pp( 1 ); std::cout << "Creating client ... " ; client::vtrc_client_sptr client = client::vtrc_client::create( pp ); /// connect slot to 'on_ready' vtrc::condition_variable ready_cond; client->get_on_ready( ).connect( vtrc::bind( on_client_ready, vtrc::ref( ready_cond ) ) ); std::cout << "Ok\n"; std::string path; connect_to( client, params["server"].as<std::string>( ) ); std::cout << "Connected to " << params["server"].as<std::string>( ) << "\n"; vtrc::mutex ready_mutex; vtrc::unique_lock<vtrc::mutex> ready_lock(ready_mutex); ready_cond.wait( ready_lock, vtrc::bind( &client::vtrc_client::ready, client ) ); if( params.count( "path" ) ) { path = params["path"].as<std::string>( ); } std::cout << "Path is: '" << path << "'\nCreating interface..."; vtrc::shared_ptr<interfaces::remote_fs> impl (interfaces::create_remote_fs(client, path)); std::cout << "Success; id is '" << impl->get_handle( ) << "'\n"; std::cout << "Path " << ( impl->exists( ) ? "exists" : "not exists" ) << "\n"; if( params.count( "pwd" ) ) { std::cout << "PWD: " << impl->pwd( ) << "\n"; } if( params.count( "info" ) ) { std::string pi(params["info"].as<std::string>( )); std::cout << "Trying get info about '" << pi << "'..."; interfaces::fs_info inf = impl->info( pi ); std::cout << "Ok.\nInfo:\n"; std::cout << "\texists:\t\t" << (inf.is_exist_ ? "true" : "false") << "\n"; std::cout << "\tdirectory:\t" << (inf.is_directory_ ? "true" : "false") << "\n"; std::cout << "\tempty:\t\t" << (inf.is_empty_ ? "true" : "false") << "\n"; std::cout << "\tregular:\t" << (inf.is_regular_ ? "true" : "false") << "\n"; } if( params.count( "list" ) ) { std::cout << "List dir:\n"; rfs_examples::list_dir( impl ); } if( params.count( "tree" ) ) { std::cout << "Tree dir:\n"; rfs_examples::tree_dir( impl ); } size_t bs = params.count( "block-size" ) ? params["block-size"].as<unsigned>( ) : 4096; if( params.count( "pull" ) ) { std::string path = params["pull"].as<std::string>( ); std::cout << "pull file '" << path << "'\n"; rfs_examples::pull_file( client, impl, path, bs ); } if( params.count( "push" ) ) { std::string path = params["push"].as<std::string>( ); std::cout << "push file '" << path << "'\n"; rfs_examples::push_file( client, path, bs ); } if( params.count( "mkdir" ) ) { std::string path = params["mkdir"].as<std::string>( ); if( path.empty( ) ) { rfs_examples::make_dir( impl ); } else { rfs_examples::make_dir( impl, path ); } } if( params.count( "del" ) ) { std::string path = params["del"].as<std::string>( ); if( path.empty( ) ) { rfs_examples::del( impl ); } else { rfs_examples::del( impl, path ); } } impl.reset( ); // close fs instance pp.stop_all( ); pp.join_all( ); return 0; } <commit_msg>fs examples<commit_after>#include <vector> #include <string> #include <fstream> #include "boost/program_options.hpp" #include "vtrc-client-base/vtrc-client.h" #include "vtrc-common/vtrc-pool-pair.h" #include "vtrc-common/vtrc-exception.h" #include "rfs-iface.h" #include "vtrc-condition-variable.h" #include "vtrc-mutex.h" #include "vtrc-bind.h" #include "vtrc-ref.h" namespace po = boost::program_options; using namespace vtrc; void get_options( po::options_description& desc ) { desc.add_options( ) ("help,?", "help message") ("server,s", po::value<std::string>( ), "server name; <tcp address>:<port> or <pipe/file name>") ("path,p", po::value<std::string>( ), "Init remote path for client") ("pwd,w", "Show current remote path") ("info,i", po::value<std::string>( ), "Show info about remote path") ("list,l", "list remote directory") ("tree,t", "show remote directory as tree") ("pull,g", po::value<std::string>( ), "Download remote file") ("push,u", po::value<std::string>( ), "Upload local file") ("block-size,b", po::value<unsigned>( ), "Block size for pull and push" "; 1-640000") ("mkdir,m", po::value<std::string>( ), "Create remote directory") ("del,d", po::value<std::string>( ), "Remove remote directory" " if it is empty") ; } void connect_to( client::vtrc_client_sptr client, std::string const &name ) { std::vector<std::string> params; std::string::const_reverse_iterator b(name.rbegin( )); std::string::const_reverse_iterator e(name.rend( )); for( ; b!=e ;++b ) { if( *b == ':' ) { std::string::const_reverse_iterator bb(b); ++bb; params.push_back( std::string( name.begin( ), bb.base( )) ); params.push_back( std::string( b.base( ), name.end( ))); break; } } if( params.empty( ) ) { params.push_back( name ); } if( params.size( ) == 1 ) { /// local name client->connect( params[0] ); } else if( params.size( ) == 2 ) { /// tcp client->connect( params[0], params[1]); } } void on_client_ready( vtrc::condition_variable &cond ) { std::cout << "Connection is ready...\n"; cond.notify_all( ); } namespace rfs_examples { /// rfs-directory-list.cpp void list_dir( vtrc::shared_ptr<interfaces::remote_fs> &impl); /// rfs-directory-tree.cpp void tree_dir( vtrc::shared_ptr<interfaces::remote_fs> &impl ); /// rfs-push-file.cpp void push_file( client::vtrc_client_sptr client, const std::string &local_path, size_t block_size ); /// rfs-pull-file.cpp void pull_file( client::vtrc_client_sptr client, vtrc::shared_ptr<interfaces::remote_fs> &impl, const std::string &remote_path, size_t block_size ); /// rfs-mkdir-del.cpp void make_dir( vtrc::shared_ptr<interfaces::remote_fs> &impl, const std::string &path); void make_dir( vtrc::shared_ptr<interfaces::remote_fs> &impl ); void del( vtrc::shared_ptr<interfaces::remote_fs> &impl, const std::string &path); void del( vtrc::shared_ptr<interfaces::remote_fs> &impl ); } int start( const po::variables_map &params ) { if( params.count( "server" ) == 0 ) { throw std::runtime_error("Server is not defined;\n" "Use --help for details"); } /// will use only one thread for io operations. /// because we don't have callbacks or events from server-side common::pool_pair pp( 1 ); std::cout << "Creating client ... " ; client::vtrc_client_sptr client = client::vtrc_client::create( pp ); /// connect slot to 'on_ready' vtrc::condition_variable ready_cond; client->get_on_ready( ).connect( vtrc::bind( on_client_ready, vtrc::ref( ready_cond ) ) ); std::cout << "Ok\n"; std::string path; connect_to( client, params["server"].as<std::string>( ) ); std::cout << "Connected to " << params["server"].as<std::string>( ) << "\n"; vtrc::mutex ready_mutex; vtrc::unique_lock<vtrc::mutex> ready_lock(ready_mutex); ready_cond.wait( ready_lock, vtrc::bind( &client::vtrc_client::ready, client ) ); if( params.count( "path" ) ) { path = params["path"].as<std::string>( ); } std::cout << "Path is: '" << path << "'\nCreating interface..."; vtrc::shared_ptr<interfaces::remote_fs> impl (interfaces::create_remote_fs(client, path)); std::cout << "Success; id is '" << impl->get_handle( ) << "'\n"; std::cout << "Path " << ( impl->exists( ) ? "exists" : "not exists" ) << "\n"; if( params.count( "pwd" ) ) { std::cout << "PWD: " << impl->pwd( ) << "\n"; } if( params.count( "info" ) ) { std::string pi(params["info"].as<std::string>( )); std::cout << "Trying get info about '" << pi << "'..."; interfaces::fs_info inf = impl->info( pi ); std::cout << "Ok.\nInfo:\n"; std::cout << "\texists:\t\t" << (inf.is_exist_ ? "true" : "false") << "\n"; std::cout << "\tdirectory:\t" << (inf.is_directory_ ? "true" : "false") << "\n"; std::cout << "\tempty:\t\t" << (inf.is_empty_ ? "true" : "false") << "\n"; std::cout << "\tregular:\t" << (inf.is_regular_ ? "true" : "false") << "\n"; } if( params.count( "list" ) ) { std::cout << "List dir:\n"; rfs_examples::list_dir( impl ); } if( params.count( "tree" ) ) { std::cout << "Tree dir:\n"; rfs_examples::tree_dir( impl ); } size_t bs = params.count( "block-size" ) ? params["block-size"].as<unsigned>( ) : 4096; if( params.count( "pull" ) ) { std::string path = params["pull"].as<std::string>( ); std::cout << "pull file '" << path << "'\n"; rfs_examples::pull_file( client, impl, path, bs ); } if( params.count( "push" ) ) { std::string path = params["push"].as<std::string>( ); std::cout << "push file '" << path << "'\n"; rfs_examples::push_file( client, path, bs ); } if( params.count( "mkdir" ) ) { std::string path = params["mkdir"].as<std::string>( ); if( path.empty( ) ) { rfs_examples::make_dir( impl ); } else { rfs_examples::make_dir( impl, path ); } } if( params.count( "del" ) ) { std::string path = params["del"].as<std::string>( ); if( path.empty( ) ) { rfs_examples::del( impl ); } else { rfs_examples::del( impl, path ); } } impl.reset( ); // close fs instance pp.stop_all( ); pp.join_all( ); return 0; } <|endoftext|>
<commit_before>/**************************************************************************** * Copyright (C) 2017 Savoir-faire Linux * * Author: Nicolas Jäger <[email protected]> * * Author: Sébastien Blin <[email protected]> * * Author: Guillaume Roguez <[email protected]> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "database.h" // Qt #include <QtSql/QSqlDatabase> #include <QtSql/QSqlError> #include <QtSql/QSqlRecord> #include <QStandardPaths> #include <QDebug> // Std #include <sstream> // Data #include "api/message.h" namespace lrc { using namespace api; static constexpr auto VERSION = "1"; static constexpr auto NAME = "ring.db"; Database::Database() : QObject() { // check support. if (not QSqlDatabase::drivers().contains("QSQLITE")) { throw std::runtime_error("QSQLITE not supported"); } // initalize the database. db_ = QSqlDatabase::addDatabase("QSQLITE"); db_.setDatabaseName(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/" + NAME); // open the database. if (not db_.open()) { throw std::runtime_error("cannot open database"); } // if db is empty we create them. if (db_.tables().empty()) createTables(); } Database::~Database() { } void Database::createTables() { QSqlQuery query; auto tableProfiles = "CREATE TABLE profiles (id INTEGER PRIMARY KEY,\ uri TEXT NOT NULL, \ alias TEXT, \ photo TEXT, \ type INTEGER, \ status INTEGER)"; auto tableConversations = "CREATE TABLE conversations (id INTEGER PRIMARY KEY,\ participant_id INTEGER, \ FOREIGN KEY(participant_id) REFERENCES profiles(id))"; auto tableInteractions = "CREATE TABLE interactions (id INTEGER PRIMARY KEY,\ account_id INTEGER, \ author_id INTEGER, \ conversation_id INTEGER, \ device_id INTEGER, \ group_id INTEGER, \ timestamp INTEGER, \ body TEXT, \ type INTEGER, \ status INTEGER, \ FOREIGN KEY(account_id) REFERENCES profiles(id), \ FOREIGN KEY(author_id) REFERENCES profiles(id), \ FOREIGN KEY(conversation_id) REFERENCES conversations(id))"; // add profiles table if (not db_.tables().contains("profiles", Qt::CaseInsensitive) and not query.exec(tableProfiles)) { throw QueryError(query); } // add conversations table if (not db_.tables().contains("conversations", Qt::CaseInsensitive) and not query.exec(tableConversations)) { throw QueryError(query); } // add interactions table if (not db_.tables().contains("interactions", Qt::CaseInsensitive) and not query.exec(tableInteractions)) { throw QueryError(query); } storeVersion(VERSION); } void Database::storeVersion(const std::string& version) { QSqlQuery query; auto storeVersionQuery = std::string("PRAGMA user_version = ") + version; if (not query.exec(storeVersionQuery.c_str())) throw QueryError(query); } int Database::insertInto(const std::string& table, // "tests" const std::map<std::string, std::string>& bindCol, // {{":id", "id"}, {":forename", "colforname"}, {":name", "colname"}} const std::map<std::string, std::string>& bindsSet) // {{":id", "7"}, {":forename", "alice"}, {":name", "cooper"}} { QSqlQuery query; std::string columns; std::string binds; for (const auto& entry : bindCol) { columns += entry.second + ","; binds += entry.first + ","; } // remove the last ',' columns.pop_back(); binds.pop_back(); auto prepareStr = std::string("INSERT INTO " + table + " (" + columns + ") VALUES (" + binds + ")"); query.prepare(prepareStr.c_str()); for (const auto& entry : bindsSet) query.bindValue(entry.first.c_str(), entry.second.c_str()); if (not query.exec()) throw QueryInsertError(query, table, bindCol, bindsSet); if (not query.exec("SELECT last_insert_rowid()")) throw QueryInsertError(query, table, bindCol, bindsSet); if (!query.next()) return -1; return query.value(0).toInt(); } void Database::update(const std::string& table, // "tests" const std::string& set, // "location=:place, phone:=nmbr" const std::map<std::string, std::string>& bindsSet, // {{":place", "montreal"}, {":nmbr", "514"}} const std::string& where, // "contact=:name AND id=:id const std::map<std::string, std::string>& bindsWhere) // {{":name", "toto"}, {":id", "65"}} { QSqlQuery query; auto prepareStr = std::string("UPDATE " + table + " SET " + set + " WHERE " + where); query.prepare(prepareStr.c_str()); for (const auto& entry : bindsSet) query.bindValue(entry.first.c_str(), entry.second.c_str()); for (const auto& entry : bindsWhere) query.bindValue(entry.first.c_str(), entry.second.c_str()); if (not query.exec()) throw QueryUpdateError(query, table, set, bindsSet, where, bindsWhere); } Database::Result Database::select(const std::string& select, // "id", "body", ... const std::string& table, // "tests" const std::string& where, // "contact=:name AND id=:id const std::map<std::string, std::string>& bindsWhere) // {{":name", "toto"}, {":id", "65"}} { QSqlQuery query; std::string columnsSelect; auto prepareStr = std::string("SELECT " + select + " FROM " + table + " WHERE " + where); query.prepare(prepareStr.c_str()); for (const auto& entry : bindsWhere) query.bindValue(entry.first.c_str(), entry.second.c_str()); if (not query.exec()) throw QuerySelectError(query, select, table, where, bindsWhere); QSqlRecord rec = query.record(); const auto col_num = rec.count(); Database::Result result = {col_num, std::vector<std::string>()}; // for each row while (query.next()) { for (int i = 0 ; i < col_num ; i++) result.payloads.emplace_back(query.value(i).toString().toStdString()); } return std::move(result); } void Database::deleteFrom(const std::string& table, // "tests" const std::string& where, // "contact=:name AND id=:id const std::map<std::string, std::string>& bindsWhere) // {{":name", "toto"}, {":id", "65"}} { QSqlQuery query; auto prepareStr = std::string("DELETE FROM " + table + " WHERE " + where); query.prepare(prepareStr.c_str()); for (const auto& entry : bindsWhere) query.bindValue(entry.first.c_str(), entry.second.c_str()); if(not query.exec()) throw QueryDeleteError(query, table, where, bindsWhere); } Database::QueryError::QueryError(const QSqlQuery& query) : std::runtime_error(query.lastError().text().toStdString()) , query(query) {} Database::QueryInsertError::QueryInsertError(const QSqlQuery& query, const std::string& table, const std::map<std::string, std::string>& bindCol, const std::map<std::string, std::string>& bindsSet) : QueryError(query) , table(table), bindCol(bindCol), bindsSet(bindsSet) {} std::string Database::QueryInsertError::details() { std::ostringstream oss; oss << "paramaters sent :"; oss << "table = " << table.c_str(); for (auto& b : bindCol) oss << " {" << b.first.c_str() << "}, {" << b.second.c_str() <<"}"; for (auto& b : bindsSet) oss << " {" << b.first.c_str() << "}, {" << b.second.c_str() <<"}"; return oss.str(); } Database::QueryUpdateError::QueryUpdateError(const QSqlQuery& query, const std::string& table, const std::string& set, const std::map<std::string, std::string>& bindsSet, const std::string& where, const std::map<std::string, std::string>& bindsWhere) : QueryError(query) , table(table), set(set), bindsSet(bindsSet), where(where), bindsWhere(bindsWhere) {} std::string Database::QueryUpdateError::details() { std::ostringstream oss; oss << "paramaters sent :"; oss << "table = " << table.c_str(); oss << "set = " << set.c_str(); oss << "bindsSet :"; for (auto& b : bindsSet) oss << " {" << b.first.c_str() << "}, {" << b.second.c_str() <<"}"; oss << "where = " << where.c_str(); oss << "bindsWhere :"; for (auto& b : bindsWhere) oss << " {" << b.first.c_str() << "}, {" << b.second.c_str() <<"}"; return oss.str(); } Database::QuerySelectError::QuerySelectError(const QSqlQuery& query, const std::string& select, const std::string& table, const std::string& where, const std::map<std::string, std::string>& bindsWhere) : QueryError(query) , select(select), table(table), where(where), bindsWhere(bindsWhere) {} std::string Database::QuerySelectError::details() { std::ostringstream oss; oss << "paramaters sent :"; oss << "select = " << select.c_str(); oss << "table = " << table.c_str(); oss << "where = " << where.c_str(); oss << "bindsWhere :"; for (auto& b : bindsWhere) oss << " {" << b.first.c_str() << "}, {" << b.second.c_str() <<"}"; return oss.str(); } Database::QueryDeleteError::QueryDeleteError(const QSqlQuery& query, const std::string& table, const std::string& where, const std::map<std::string, std::string>& bindsWhere) : QueryError(query) , table(table), where(where), bindsWhere(bindsWhere) {} std::string Database::QueryDeleteError::details() { std::ostringstream oss; oss << "paramaters sent :"; oss << "table = " << table.c_str(); oss << "where = " << where.c_str(); oss << "bindsWhere :"; for (auto& b : bindsWhere) oss << " {" << b.first.c_str() << "}, {" << b.second.c_str() <<"}"; return oss.str(); } } // namespace lrc <commit_msg>database: fix status and type for interactions and id for conversations.<commit_after>/**************************************************************************** * Copyright (C) 2017 Savoir-faire Linux * * Author: Nicolas Jäger <[email protected]> * * Author: Sébastien Blin <[email protected]> * * Author: Guillaume Roguez <[email protected]> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "database.h" // Qt #include <QtSql/QSqlDatabase> #include <QtSql/QSqlError> #include <QtSql/QSqlRecord> #include <QStandardPaths> #include <QDebug> // Std #include <sstream> // Data #include "api/message.h" namespace lrc { using namespace api; static constexpr auto VERSION = "1"; static constexpr auto NAME = "ring.db"; Database::Database() : QObject() { // check support. if (not QSqlDatabase::drivers().contains("QSQLITE")) { throw std::runtime_error("QSQLITE not supported"); } // initalize the database. db_ = QSqlDatabase::addDatabase("QSQLITE"); db_.setDatabaseName(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/" + NAME); // open the database. if (not db_.open()) { throw std::runtime_error("cannot open database"); } // if db is empty we create them. if (db_.tables().empty()) createTables(); } Database::~Database() { } void Database::createTables() { QSqlQuery query; auto tableProfiles = "CREATE TABLE profiles (id INTEGER PRIMARY KEY,\ uri TEXT NOT NULL, \ alias TEXT, \ photo TEXT, \ type INTEGER, \ status INTEGER)"; auto tableConversations = "CREATE TABLE conversations (id INTEGER,\ participant_id INTEGER, \ FOREIGN KEY(participant_id) REFERENCES profiles(id))"; auto tableInteractions = "CREATE TABLE interactions (id INTEGER PRIMARY KEY,\ account_id INTEGER, \ author_id INTEGER, \ conversation_id INTEGER, \ device_id INTEGER, \ group_id INTEGER, \ timestamp INTEGER, \ body TEXT, \ type TEXT, \ status TEXT, \ FOREIGN KEY(account_id) REFERENCES profiles(id), \ FOREIGN KEY(author_id) REFERENCES profiles(id), \ FOREIGN KEY(conversation_id) REFERENCES conversations(id))"; // add profiles table if (not db_.tables().contains("profiles", Qt::CaseInsensitive) and not query.exec(tableProfiles)) { throw QueryError(query); } // add conversations table if (not db_.tables().contains("conversations", Qt::CaseInsensitive) and not query.exec(tableConversations)) { throw QueryError(query); } // add interactions table if (not db_.tables().contains("interactions", Qt::CaseInsensitive) and not query.exec(tableInteractions)) { throw QueryError(query); } storeVersion(VERSION); } void Database::storeVersion(const std::string& version) { QSqlQuery query; auto storeVersionQuery = std::string("PRAGMA user_version = ") + version; if (not query.exec(storeVersionQuery.c_str())) throw QueryError(query); } int Database::insertInto(const std::string& table, // "tests" const std::map<std::string, std::string>& bindCol, // {{":id", "id"}, {":forename", "colforname"}, {":name", "colname"}} const std::map<std::string, std::string>& bindsSet) // {{":id", "7"}, {":forename", "alice"}, {":name", "cooper"}} { QSqlQuery query; std::string columns; std::string binds; for (const auto& entry : bindCol) { columns += entry.second + ","; binds += entry.first + ","; } // remove the last ',' columns.pop_back(); binds.pop_back(); auto prepareStr = std::string("INSERT INTO " + table + " (" + columns + ") VALUES (" + binds + ")"); query.prepare(prepareStr.c_str()); for (const auto& entry : bindsSet) query.bindValue(entry.first.c_str(), entry.second.c_str()); if (not query.exec()) throw QueryInsertError(query, table, bindCol, bindsSet); if (not query.exec("SELECT last_insert_rowid()")) throw QueryInsertError(query, table, bindCol, bindsSet); if (!query.next()) return -1; return query.value(0).toInt(); } void Database::update(const std::string& table, // "tests" const std::string& set, // "location=:place, phone:=nmbr" const std::map<std::string, std::string>& bindsSet, // {{":place", "montreal"}, {":nmbr", "514"}} const std::string& where, // "contact=:name AND id=:id const std::map<std::string, std::string>& bindsWhere) // {{":name", "toto"}, {":id", "65"}} { QSqlQuery query; auto prepareStr = std::string("UPDATE " + table + " SET " + set + " WHERE " + where); query.prepare(prepareStr.c_str()); for (const auto& entry : bindsSet) query.bindValue(entry.first.c_str(), entry.second.c_str()); for (const auto& entry : bindsWhere) query.bindValue(entry.first.c_str(), entry.second.c_str()); if (not query.exec()) throw QueryUpdateError(query, table, set, bindsSet, where, bindsWhere); } Database::Result Database::select(const std::string& select, // "id", "body", ... const std::string& table, // "tests" const std::string& where, // "contact=:name AND id=:id const std::map<std::string, std::string>& bindsWhere) // {{":name", "toto"}, {":id", "65"}} { QSqlQuery query; std::string columnsSelect; auto prepareStr = std::string("SELECT " + select + " FROM " + table + " WHERE " + where); query.prepare(prepareStr.c_str()); for (const auto& entry : bindsWhere) query.bindValue(entry.first.c_str(), entry.second.c_str()); if (not query.exec()) throw QuerySelectError(query, select, table, where, bindsWhere); QSqlRecord rec = query.record(); const auto col_num = rec.count(); Database::Result result = {col_num, std::vector<std::string>()}; // for each row while (query.next()) { for (int i = 0 ; i < col_num ; i++) result.payloads.emplace_back(query.value(i).toString().toStdString()); } return std::move(result); } void Database::deleteFrom(const std::string& table, // "tests" const std::string& where, // "contact=:name AND id=:id const std::map<std::string, std::string>& bindsWhere) // {{":name", "toto"}, {":id", "65"}} { QSqlQuery query; auto prepareStr = std::string("DELETE FROM " + table + " WHERE " + where); query.prepare(prepareStr.c_str()); for (const auto& entry : bindsWhere) query.bindValue(entry.first.c_str(), entry.second.c_str()); if(not query.exec()) throw QueryDeleteError(query, table, where, bindsWhere); } Database::QueryError::QueryError(const QSqlQuery& query) : std::runtime_error(query.lastError().text().toStdString()) , query(query) {} Database::QueryInsertError::QueryInsertError(const QSqlQuery& query, const std::string& table, const std::map<std::string, std::string>& bindCol, const std::map<std::string, std::string>& bindsSet) : QueryError(query) , table(table), bindCol(bindCol), bindsSet(bindsSet) {} std::string Database::QueryInsertError::details() { std::ostringstream oss; oss << "paramaters sent :"; oss << "table = " << table.c_str(); for (auto& b : bindCol) oss << " {" << b.first.c_str() << "}, {" << b.second.c_str() <<"}"; for (auto& b : bindsSet) oss << " {" << b.first.c_str() << "}, {" << b.second.c_str() <<"}"; return oss.str(); } Database::QueryUpdateError::QueryUpdateError(const QSqlQuery& query, const std::string& table, const std::string& set, const std::map<std::string, std::string>& bindsSet, const std::string& where, const std::map<std::string, std::string>& bindsWhere) : QueryError(query) , table(table), set(set), bindsSet(bindsSet), where(where), bindsWhere(bindsWhere) {} std::string Database::QueryUpdateError::details() { std::ostringstream oss; oss << "paramaters sent :"; oss << "table = " << table.c_str(); oss << "set = " << set.c_str(); oss << "bindsSet :"; for (auto& b : bindsSet) oss << " {" << b.first.c_str() << "}, {" << b.second.c_str() <<"}"; oss << "where = " << where.c_str(); oss << "bindsWhere :"; for (auto& b : bindsWhere) oss << " {" << b.first.c_str() << "}, {" << b.second.c_str() <<"}"; return oss.str(); } Database::QuerySelectError::QuerySelectError(const QSqlQuery& query, const std::string& select, const std::string& table, const std::string& where, const std::map<std::string, std::string>& bindsWhere) : QueryError(query) , select(select), table(table), where(where), bindsWhere(bindsWhere) {} std::string Database::QuerySelectError::details() { std::ostringstream oss; oss << "paramaters sent :"; oss << "select = " << select.c_str(); oss << "table = " << table.c_str(); oss << "where = " << where.c_str(); oss << "bindsWhere :"; for (auto& b : bindsWhere) oss << " {" << b.first.c_str() << "}, {" << b.second.c_str() <<"}"; return oss.str(); } Database::QueryDeleteError::QueryDeleteError(const QSqlQuery& query, const std::string& table, const std::string& where, const std::map<std::string, std::string>& bindsWhere) : QueryError(query) , table(table), where(where), bindsWhere(bindsWhere) {} std::string Database::QueryDeleteError::details() { std::ostringstream oss; oss << "paramaters sent :"; oss << "table = " << table.c_str(); oss << "where = " << where.c_str(); oss << "bindsWhere :"; for (auto& b : bindsWhere) oss << " {" << b.first.c_str() << "}, {" << b.second.c_str() <<"}"; return oss.str(); } } // namespace lrc <|endoftext|>
<commit_before>// Copyright 2018 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Dichotomy loop and default search implementation // // Author: Skal ([email protected]) #include <math.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include "sjpegi.h" using namespace sjpeg; //////////////////////////////////////////////////////////////////////////////// // dichotomy #define DBG_PRINT 0 // convergence is considered reached if |dq| < kdQLimit. static const float kdQLimit = 0.15; static float Clamp(float v, float min, float max) { return (v < min) ? min : (v > max) ? max : v; } bool SearchHook::Setup(const SjpegEncodeParam& param) { for_size = (param.target_mode == SjpegEncodeParam::TARGET_SIZE); target = param.target_value; tolerance = param.tolerance / 100.; qmin = (param.qmin < 0) ? 0 : param.qmin; qmax = (param.qmax > 100) ? 100 : (param.qmax < param.qmin) ? param.qmin : param.qmax; q = Clamp(SjpegEstimateQuality(param.quant_[0], false), qmin, qmax); value = 0; // undefined for at this point return true; } bool SearchHook::Update(float result) { value = result; bool done = (fabs(value - target) < tolerance * target); if (done) return true; if (value > target) { qmax = q; } else { qmin = q; } const float last_q = q; q = (qmin + qmax) / 2.; done = (fabs(q - last_q) < kdQLimit); if (DBG_PRINT) { printf("q=%.2f value:%.1f -> next-q=%.2f\n", last_q, value, q); } return done; } void SearchHook::NextMatrix(int idx, uint8_t dst[64]) { SetQuantMatrix(kDefaultMatrices[idx], GetQFactor(q), dst); } //////////////////////////////////////////////////////////////////////////////// // Helpers for the search void Encoder::StoreRunLevels(DCTCoeffs* coeffs) { assert(use_extra_memory_); assert(reuse_run_levels_); const QuantizeBlockFunc quantize_block = use_trellis_ ? TrellisQuantizeBlock : quantize_block_; if (use_trellis_) InitCodes(true); ResetDCs(); nb_run_levels_ = 0; int16_t* in = in_blocks_; for (int n = 0; n < mb_w_ * mb_h_; ++n) { CheckBuffers(); for (int c = 0; c < nb_comps_; ++c) { for (int i = 0; i < nb_blocks_[c]; ++i) { RunLevel* const run_levels = all_run_levels_ + nb_run_levels_; const int dc = quantize_block(in, c, &quants_[quant_idx_[c]], coeffs, run_levels); coeffs->dc_code_ = GenerateDCDiffCode(dc, &DCs_[c]); nb_run_levels_ += coeffs->nb_coeffs_; ++coeffs; in += 64; } } } } void Encoder::LoopScan() { assert(use_extra_memory_); assert(reuse_run_levels_); if (use_adaptive_quant_) { CollectHistograms(); } else { CollectCoeffs(); // we just need the coeffs } const size_t nb_mbs = mb_w_ * mb_h_ * mcu_blocks_; DCTCoeffs* const base_coeffs = new DCTCoeffs[nb_mbs]; uint8_t opt_quants[2][64]; // Dichotomy passes float best = 0.; // best distance float best_q = 0.; // informative value to return to the user float best_result = 0.; for (int p = 0; p < passes_; ++p) { // set new matrices to evaluate for (int c = 0; c < 2; ++c) { search_hook_->NextMatrix(c, quants_[c].quant_); FinalizeQuantMatrix(&quants_[c], q_bias_); } if (use_adaptive_quant_) { AnalyseHisto(); // adjust quant_[] matrices } float result; if (search_hook_->for_size) { // compute pass to store coeffs / runs / dc_code_ StoreRunLevels(base_coeffs); if (optimize_size_) { StoreOptimalHuffmanTables(nb_mbs, base_coeffs); if (use_trellis_) InitCodes(true); } result = ComputeSize(base_coeffs); } else { // if we're just targeting PSNR, we don't need to compute the // run/levels within the loop. We just need to quantize the coeffs // and measure the distortion. result = ComputePSNR(); } if (DBG_PRINT) printf("pass #%d: q=%f value:%.2f\n", p, search_hook_->q, result); if (p == 0 || fabs(result - search_hook_->target) < best) { // save the matrices for later, if they are better for (int c = 0; c < 2; ++c) { CopyQuantMatrix(quants_[c].quant_, opt_quants[c]); } best = fabs(result - search_hook_->target); best_q = search_hook_->q; best_result = result; } if (search_hook_->Update(result)) break; } // transfer back the final matrices SetQuantMatrices(opt_quants); // return informative values to the user search_hook_->q = best_q; search_hook_->value = best_result; // optimize Huffman table now, if we haven't already during the search if (!search_hook_->for_size) { StoreRunLevels(base_coeffs); if (optimize_size_) { StoreOptimalHuffmanTables(nb_mbs, base_coeffs); } } // finish bitstream WriteDQT(); WriteSOF(); WriteDHT(); WriteSOS(); FinalPassScan(nb_mbs, base_coeffs); delete[] base_coeffs; } //////////////////////////////////////////////////////////////////////////////// // Size & PSNR computation, mostly for dichotomy size_t Encoder::HeaderSize() const { size_t size = 0; size += 20; // APP0 size += app_markers_.size(); if (exif_.size() > 0) { size += 8 + exif_.size(); } if (iccp_.size() > 0) { const size_t chunk_size_max = 0xffff - 12 - 4; const size_t num_chunks = (iccp_.size() - 1) / chunk_size_max + 1; size += num_chunks * (12 + 4 + 2); size += iccp_.size(); } if (xmp_.size() > 0) { size += 2 + 2 + 29 + xmp_.size(); } size += 2 * 65 + 2 + 2; // DQT size += 8 + 3 * nb_comps_ + 2; // SOF size += 6 + 2 * nb_comps_ + 2; // SOS size += 2; // EOI // DHT: for (int c = 0; c < (nb_comps_ == 1 ? 1 : 2); ++c) { // luma, chroma for (int type = 0; type <= 1; ++type) { // dc, ac const HuffmanTable* const h = Huffman_tables_[type * 2 + c]; size += 2 + 3 + 16 + h->nb_syms_; } } return size * 8; } void Encoder::BlocksSize(int nb_mbs, const DCTCoeffs* coeffs, const RunLevel* rl, BitCounter* const bc) const { for (int n = 0; n < nb_mbs; ++n) { const DCTCoeffs& c = coeffs[n]; const int idx = c.idx_; const int q_idx = quant_idx_[idx]; // DC const int dc_len = c.dc_code_ & 0x0f; const uint32_t code = dc_codes_[q_idx][dc_len]; bc->AddPackedCode(code); bc->AddBits(c.dc_code_ >> 4, dc_len); // AC const uint32_t* const codes = ac_codes_[q_idx]; for (int i = 0; i < c.nb_coeffs_; ++i) { int run = rl[i].run_; while (run & ~15) { // escapes bc->AddPackedCode(codes[0xf0]); run -= 16; } const uint32_t suffix = rl[i].level_; const size_t nbits = suffix & 0x0f; const int sym = (run << 4) | nbits; bc->AddPackedCode(codes[sym]); bc->AddBits(suffix >> 4, nbits); } if (c.last_ < 63) bc->AddPackedCode(codes[0x00]); // EOB rl += c.nb_coeffs_; } } float Encoder::ComputeSize(const DCTCoeffs* coeffs) { InitCodes(false); size_t size = HeaderSize(); BitCounter bc; BlocksSize(mb_w_ * mb_h_ * mcu_blocks_, coeffs, all_run_levels_, &bc); size += bc.Size(); return size / 8.f; } //////////////////////////////////////////////////////////////////////////////// static double GetPSNR(uint64_t err, uint64_t size) { return (err > 0 && size > 0) ? 10. * log10(255. * 255. * size / err) : 99.; } float Encoder::ComputePSNR() const { uint64_t error = 0; const int16_t* in = in_blocks_; const size_t nb_mbs = mb_w_ * mb_h_; for (size_t n = 0; n < nb_mbs; ++n) { for (int c = 0; c < nb_comps_; ++c) { const Quantizer* const Q = &quants_[quant_idx_[c]]; for (int i = 0; i < nb_blocks_[c]; ++i) { error += quantize_error_(in, Q); in += 64; } } } return GetPSNR(error, 64ull * nb_mbs * mcu_blocks_); } <commit_msg>make GetPSNR() be the same on ARM and x86<commit_after>// Copyright 2018 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Dichotomy loop and default search implementation // // Author: Skal ([email protected]) #include <math.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include "sjpegi.h" using namespace sjpeg; //////////////////////////////////////////////////////////////////////////////// // dichotomy #define DBG_PRINT 0 // convergence is considered reached if |dq| < kdQLimit. static const float kdQLimit = 0.15; static float Clamp(float v, float min, float max) { return (v < min) ? min : (v > max) ? max : v; } bool SearchHook::Setup(const SjpegEncodeParam& param) { for_size = (param.target_mode == SjpegEncodeParam::TARGET_SIZE); target = param.target_value; tolerance = param.tolerance / 100.; qmin = (param.qmin < 0) ? 0 : param.qmin; qmax = (param.qmax > 100) ? 100 : (param.qmax < param.qmin) ? param.qmin : param.qmax; q = Clamp(SjpegEstimateQuality(param.quant_[0], false), qmin, qmax); value = 0; // undefined for at this point return true; } bool SearchHook::Update(float result) { value = result; bool done = (fabs(value - target) < tolerance * target); if (done) return true; if (value > target) { qmax = q; } else { qmin = q; } const float last_q = q; q = (qmin + qmax) / 2.; done = (fabs(q - last_q) < kdQLimit); if (DBG_PRINT) { printf("q=%.2f value:%.1f -> next-q=%.2f\n", last_q, value, q); } return done; } void SearchHook::NextMatrix(int idx, uint8_t dst[64]) { SetQuantMatrix(kDefaultMatrices[idx], GetQFactor(q), dst); } //////////////////////////////////////////////////////////////////////////////// // Helpers for the search void Encoder::StoreRunLevels(DCTCoeffs* coeffs) { assert(use_extra_memory_); assert(reuse_run_levels_); const QuantizeBlockFunc quantize_block = use_trellis_ ? TrellisQuantizeBlock : quantize_block_; if (use_trellis_) InitCodes(true); ResetDCs(); nb_run_levels_ = 0; int16_t* in = in_blocks_; for (int n = 0; n < mb_w_ * mb_h_; ++n) { CheckBuffers(); for (int c = 0; c < nb_comps_; ++c) { for (int i = 0; i < nb_blocks_[c]; ++i) { RunLevel* const run_levels = all_run_levels_ + nb_run_levels_; const int dc = quantize_block(in, c, &quants_[quant_idx_[c]], coeffs, run_levels); coeffs->dc_code_ = GenerateDCDiffCode(dc, &DCs_[c]); nb_run_levels_ += coeffs->nb_coeffs_; ++coeffs; in += 64; } } } } void Encoder::LoopScan() { assert(use_extra_memory_); assert(reuse_run_levels_); if (use_adaptive_quant_) { CollectHistograms(); } else { CollectCoeffs(); // we just need the coeffs } const size_t nb_mbs = mb_w_ * mb_h_ * mcu_blocks_; DCTCoeffs* const base_coeffs = new DCTCoeffs[nb_mbs]; uint8_t opt_quants[2][64]; // Dichotomy passes float best = 0.; // best distance float best_q = 0.; // informative value to return to the user float best_result = 0.; for (int p = 0; p < passes_; ++p) { // set new matrices to evaluate for (int c = 0; c < 2; ++c) { search_hook_->NextMatrix(c, quants_[c].quant_); FinalizeQuantMatrix(&quants_[c], q_bias_); } if (use_adaptive_quant_) { AnalyseHisto(); // adjust quant_[] matrices } float result; if (search_hook_->for_size) { // compute pass to store coeffs / runs / dc_code_ StoreRunLevels(base_coeffs); if (optimize_size_) { StoreOptimalHuffmanTables(nb_mbs, base_coeffs); if (use_trellis_) InitCodes(true); } result = ComputeSize(base_coeffs); } else { // if we're just targeting PSNR, we don't need to compute the // run/levels within the loop. We just need to quantize the coeffs // and measure the distortion. result = ComputePSNR(); } if (DBG_PRINT) printf("pass #%d: q=%f value:%.2f\n", p, search_hook_->q, result); if (p == 0 || fabs(result - search_hook_->target) < best) { // save the matrices for later, if they are better for (int c = 0; c < 2; ++c) { CopyQuantMatrix(quants_[c].quant_, opt_quants[c]); } best = fabs(result - search_hook_->target); best_q = search_hook_->q; best_result = result; } if (search_hook_->Update(result)) break; } // transfer back the final matrices SetQuantMatrices(opt_quants); // return informative values to the user search_hook_->q = best_q; search_hook_->value = best_result; // optimize Huffman table now, if we haven't already during the search if (!search_hook_->for_size) { StoreRunLevels(base_coeffs); if (optimize_size_) { StoreOptimalHuffmanTables(nb_mbs, base_coeffs); } } // finish bitstream WriteDQT(); WriteSOF(); WriteDHT(); WriteSOS(); FinalPassScan(nb_mbs, base_coeffs); delete[] base_coeffs; } //////////////////////////////////////////////////////////////////////////////// // Size & PSNR computation, mostly for dichotomy size_t Encoder::HeaderSize() const { size_t size = 0; size += 20; // APP0 size += app_markers_.size(); if (exif_.size() > 0) { size += 8 + exif_.size(); } if (iccp_.size() > 0) { const size_t chunk_size_max = 0xffff - 12 - 4; const size_t num_chunks = (iccp_.size() - 1) / chunk_size_max + 1; size += num_chunks * (12 + 4 + 2); size += iccp_.size(); } if (xmp_.size() > 0) { size += 2 + 2 + 29 + xmp_.size(); } size += 2 * 65 + 2 + 2; // DQT size += 8 + 3 * nb_comps_ + 2; // SOF size += 6 + 2 * nb_comps_ + 2; // SOS size += 2; // EOI // DHT: for (int c = 0; c < (nb_comps_ == 1 ? 1 : 2); ++c) { // luma, chroma for (int type = 0; type <= 1; ++type) { // dc, ac const HuffmanTable* const h = Huffman_tables_[type * 2 + c]; size += 2 + 3 + 16 + h->nb_syms_; } } return size * 8; } void Encoder::BlocksSize(int nb_mbs, const DCTCoeffs* coeffs, const RunLevel* rl, BitCounter* const bc) const { for (int n = 0; n < nb_mbs; ++n) { const DCTCoeffs& c = coeffs[n]; const int idx = c.idx_; const int q_idx = quant_idx_[idx]; // DC const int dc_len = c.dc_code_ & 0x0f; const uint32_t code = dc_codes_[q_idx][dc_len]; bc->AddPackedCode(code); bc->AddBits(c.dc_code_ >> 4, dc_len); // AC const uint32_t* const codes = ac_codes_[q_idx]; for (int i = 0; i < c.nb_coeffs_; ++i) { int run = rl[i].run_; while (run & ~15) { // escapes bc->AddPackedCode(codes[0xf0]); run -= 16; } const uint32_t suffix = rl[i].level_; const size_t nbits = suffix & 0x0f; const int sym = (run << 4) | nbits; bc->AddPackedCode(codes[sym]); bc->AddBits(suffix >> 4, nbits); } if (c.last_ < 63) bc->AddPackedCode(codes[0x00]); // EOB rl += c.nb_coeffs_; } } float Encoder::ComputeSize(const DCTCoeffs* coeffs) { InitCodes(false); size_t size = HeaderSize(); BitCounter bc; BlocksSize(mb_w_ * mb_h_ * mcu_blocks_, coeffs, all_run_levels_, &bc); size += bc.Size(); return size / 8.f; } //////////////////////////////////////////////////////////////////////////////// static float GetPSNR(uint64_t err, uint64_t size) { // This expression is written such that it gives the same result on ARM // and x86 (for large values of err/size in particular). Don't change it! return (err > 0 && size > 0) ? -4.3429448f * log(size / (err / 255. / 255.)) : 99.f; } float Encoder::ComputePSNR() const { uint64_t error = 0; const int16_t* in = in_blocks_; const size_t nb_mbs = mb_w_ * mb_h_; for (size_t n = 0; n < nb_mbs; ++n) { for (int c = 0; c < nb_comps_; ++c) { const Quantizer* const Q = &quants_[quant_idx_[c]]; for (int i = 0; i < nb_blocks_[c]; ++i) { error += quantize_error_(in, Q); in += 64; } } } return GetPSNR(error, 64ull * nb_mbs * mcu_blocks_); } <|endoftext|>
<commit_before>/** * Copyright (c) Sjors Gielen, 2010 * See LICENSE for license. */ #include "database.h" #include "config.h" #include "utils.h" #include <mongo.h> #include <cerrno> #include <cassert> #include <sstream> #include <stdio.h> // #define DEBUG #define M (mongo_sync_connection*)m_ #define PROPERTIES std::string(dbc_.database + ".properties").c_str() /** * @brief Constructor. */ dazeus::Database::Database(DatabaseConfig dbc) : m_(0) , lastError_() , dbc_(dbc) { } /** * @brief Destructor. */ dazeus::Database::~Database() { if(m_) mongo_sync_disconnect(M); } /** * @brief Returns the last error in the QSqlDatabase object. */ std::string dazeus::Database::lastError() const { return lastError_; } bool dazeus::Database::open() { #ifdef DEBUG fprintf(stderr, "Initiating connection to Mongo daemon at %s:%d\n", dbc_.hostname.c_str(), dbc_.port); #endif m_ = (void*)mongo_sync_connect(dbc_.hostname.c_str(), dbc_.port, TRUE); if(!m_) { lastError_ = strerror(errno); #ifdef DEBUG fprintf(stderr, "Connection error: %s\n", lastError_.c_str()); #endif return false; } if(!mongo_sync_conn_set_auto_reconnect(M, TRUE)) { lastError_ = strerror(errno); mongo_sync_disconnect(M); #ifdef DEBUG fprintf(stderr, "Cannot set auto-reconnect: %s\n", lastError_.c_str()); #endif return false; } #ifdef DEBUG fprintf(stderr, "Building index on table %s...\n", PROPERTIES); #endif bson *index = bson_build( BSON_TYPE_INT32, "network", 1, BSON_TYPE_INT32, "receiver", 1, BSON_TYPE_INT32, "sender", 1, BSON_TYPE_NONE ); bson_finish(index); if(!mongo_sync_cmd_index_create(M, PROPERTIES, index, 0)) { #ifdef DEBUG fprintf(stderr, "Index create error: %s\n", strerror(errno)); #endif lastError_ = strerror(errno); bson_free(index); return false; } bson_free(index); return true; } /** * @brief Retrieve all properties under a certain namespace. * * All properties whose names start with the given namespace name, then a * single dot, and that match the given scope values, are returned from this * method. * * This method guarantees that if it returns a certain key, property() will * return the correct value of that key given that network, receiver and * sender scope are the same. */ std::vector<std::string> dazeus::Database::propertyKeys( const std::string &ns, const std::string &networkScope, const std::string &receiverScope, const std::string &senderScope ) { std::stringstream regexStr; regexStr << "^\\Q" << ns << "\\E\\."; std::string regex = regexStr.str(); bson *selector = bson_new(); bson_append_regex(selector, "variable", regex.c_str(), ""); if(networkScope.length() > 0) { bson_append_string(selector, "network", networkScope.c_str(), -1); if(receiverScope.length() > 0) { bson_append_string(selector, "receiver", receiverScope.c_str(), -1); if(senderScope.length() > 0) { bson_append_string(selector, "sender", senderScope.c_str(), -1); } else { bson_append_null(selector, "sender"); } } else { bson_append_null(selector, "receiver"); bson_append_null(selector, "sender"); } } else { bson_append_null(selector, "network"); bson_append_null(selector, "receiver"); bson_append_null(selector, "sender"); } bson_finish(selector); mongo_packet *p = mongo_sync_cmd_query(M, PROPERTIES, 0, 0, 0, selector, NULL /* TODO: variable only? */); bson_free(selector); if(!p) { lastError_ = strerror(errno); #ifdef DEBUG fprintf(stderr, "Database error: %s\n", lastError_.c_str()); #endif return std::vector<std::string>(); } mongo_sync_cursor *cursor = mongo_sync_cursor_new(M, PROPERTIES, p); if(!cursor) { lastError_ = strerror(errno); #ifdef DEBUG fprintf(stderr, "Database error: %s\n", lastError_.c_str()); #endif return std::vector<std::string>(); } std::vector<std::string> res; while(mongo_sync_cursor_next(cursor)) { bson *result = mongo_sync_cursor_get_data(cursor); if(!result) { lastError_ = strerror(errno); #ifdef DEBUG fprintf(stderr, "Database error: %s\n", lastError_.c_str()); #endif mongo_sync_cursor_free(cursor); return res; } bson_cursor *c = bson_find(result, "variable"); const char *value; if(!bson_cursor_get_string(c, &value)) { lastError_ = strerror(errno); #ifdef DEBUG fprintf(stderr, "Database error: %s\n", lastError_.c_str()); #endif mongo_sync_cursor_free(cursor); bson_cursor_free(c); return res; } value += ns.length() + 1; res.push_back(value); } return res; } /** * @brief Retrieve property from database. * * The most specific scope will be selected first, i.e. user-specific scope. * If that yields no results, channel-specific scope will be returned, then * network-specific scope, then global scope. * * Variable should be formatted using reverse-domain format, i.e. for the * plugin MyFirstPlugin created by John Doe, to save a 'foo' variable one * could use: * <code>net.jondoe.myfirstplugin.foo</code> */ std::string dazeus::Database::property( const std::string &variable, const std::string &networkScope, const std::string &receiverScope, const std::string &senderScope ) { // variable, [networkScope, [receiverScope, [senderScope]]] // (empty if not given) // db.c. // find() // for everything // find({network:{$in: ['NETWORKNAME',null]}}) // for network scope // find({network:{$in: ['NETWORKNAME',null]}, receiver:{$in: ['RECEIVER',null]}}) // for receiver scope // find({network:..., receiver:..., sender:{$in: ['SENDER',null]}}) // for sender scope // .sort({'a':-1,'b':-1,'c':-1}).limit(1) // Reverse sort and limit(1) will make sure we only receive the most // specific result. This works, as long as the assumption is true that // no specific fields are set without their less specific fields also // being set (i.e. receiver can't be empty if sender is non-empty). bson *query = bson_build_full( BSON_TYPE_DOCUMENT, "$orderby", TRUE, bson_build(BSON_TYPE_INT32, "network", -1, BSON_TYPE_INT32, "receiver", -1, BSON_TYPE_INT32, "sender", -1, BSON_TYPE_NONE), BSON_TYPE_NONE ); /* '$query':{ 'variable':'foo', 'network':{'$in':['bla',null]}, 'receiver':{'$in':['moo', null]}, } */ bson *selector = bson_new(); bson *network = 0, *receiver = 0, *sender = 0; bson_append_string(selector, "variable", variable.c_str(), -1); if(networkScope.length() > 0) { network = bson_build_full( BSON_TYPE_ARRAY, "$in", TRUE, bson_build(BSON_TYPE_STRING, "1", networkScope.c_str(), -1, BSON_TYPE_NULL, "2", BSON_TYPE_NONE), BSON_TYPE_NONE ); bson_finish(network); bson_append_document(selector, "network", network); if(receiverScope.length() > 0) { receiver = bson_build_full( BSON_TYPE_ARRAY, "$in", TRUE, bson_build(BSON_TYPE_STRING, "1", receiverScope.c_str(), -1, BSON_TYPE_NULL, "2", BSON_TYPE_NONE), BSON_TYPE_NONE ); bson_finish(receiver); bson_append_document(selector, "receiver", receiver); if(senderScope.length() > 0) { sender = bson_build_full( BSON_TYPE_ARRAY, "$in", TRUE, bson_build(BSON_TYPE_STRING, "1", senderScope.c_str(), -1, BSON_TYPE_NULL, "2", BSON_TYPE_NONE), BSON_TYPE_NONE ); bson_finish(sender); bson_append_document(selector, "sender", sender); } } } bson_finish(selector); bson_append_document(query, "$query", selector); bson_finish(query); mongo_packet *p = mongo_sync_cmd_query(M, PROPERTIES, 0, 0, 1, query, NULL /* TODO: value only? */); bson_free(query); bson_free(selector); if(network) bson_free(network); if(receiver) bson_free(receiver); if(sender) bson_free(sender); if(!p) { lastError_ = strerror(errno); return std::string(); } mongo_sync_cursor *cursor = mongo_sync_cursor_new(M, PROPERTIES, p); if(!cursor) { lastError_ = strerror(errno); return std::string(); } if(!mongo_sync_cursor_next(cursor)) { #ifdef DEBUG fprintf(stderr, "Variable %s not found within given scope.\n", variable.c_str()); #endif } bson *result = mongo_sync_cursor_get_data(cursor); if(!result) { lastError_ = strerror(errno); mongo_sync_cursor_free(cursor); return std::string(); } bson_cursor *c = bson_find(result, "value"); const char *value; if(!bson_cursor_get_string(c, &value)) { lastError_ = strerror(errno); #ifdef DEBUG fprintf(stderr, "Database error: %s\n", lastError_.c_str()); #endif mongo_sync_cursor_free(cursor); bson_cursor_free(c); return std::string(); } std::string res(value); bson_free(result); bson_cursor_free(c); // only one result assert(!mongo_sync_cursor_next(cursor)); mongo_sync_cursor_free(cursor); return res; } void dazeus::Database::setProperty( const std::string &variable, const std::string &value, const std::string &networkScope, const std::string &receiverScope, const std::string &senderScope ) { /** selector: {network:'foo',receiver:'bar',sender:null,variable:'bla.blob'} object: {'$set':{ 'value': 'bla'}} */ bson *object = bson_build_full( BSON_TYPE_DOCUMENT, "$set", TRUE, bson_build( BSON_TYPE_STRING, "value", value.c_str(), -1, BSON_TYPE_NONE), BSON_TYPE_NONE); bson_finish(object); bson *selector = bson_build( BSON_TYPE_STRING, "variable", variable.c_str(), -1, BSON_TYPE_NONE); if(networkScope.length() > 0) { bson_append_string(selector, "network", networkScope.c_str(), -1); if(receiverScope.length() > 0) { bson_append_string(selector, "receiver", receiverScope.c_str(), -1); if(senderScope.length() > 0) { bson_append_string(selector, "sender", senderScope.c_str(), -1); } else { bson_append_null(selector, "sender"); } } else { bson_append_null(selector, "receiver"); bson_append_null(selector, "sender"); } } else { bson_append_null(selector, "network"); bson_append_null(selector, "receiver"); bson_append_null(selector, "sender"); } bson_finish(selector); // if the value length is zero, run a delete instead if(value.length() == 0) { if(!mongo_sync_cmd_delete(M, PROPERTIES, 0, selector)) { lastError_ = strerror(errno); #ifdef DEBUG fprintf(stderr, "Error: %s\n", lastError_.c_str()); #endif } } else if(!mongo_sync_cmd_update(M, PROPERTIES, MONGO_WIRE_FLAG_UPDATE_UPSERT, selector, object)) { lastError_ = strerror(errno); #ifdef DEBUG fprintf(stderr, "Error: %s\n", lastError_.c_str()); #endif } bson_free(object); bson_free(selector); } <commit_msg>Don't give the .c_str() of a temporary string to mongo.<commit_after>/** * Copyright (c) Sjors Gielen, 2010 * See LICENSE for license. */ #include "database.h" #include "config.h" #include "utils.h" #include <mongo.h> #include <cerrno> #include <cassert> #include <sstream> #include <stdio.h> // #define DEBUG #define M (mongo_sync_connection*)m_ /** * @brief Constructor. */ dazeus::Database::Database(DatabaseConfig dbc) : m_(0) , lastError_() , dbc_(dbc) { } /** * @brief Destructor. */ dazeus::Database::~Database() { if(m_) mongo_sync_disconnect(M); } /** * @brief Returns the last error in the QSqlDatabase object. */ std::string dazeus::Database::lastError() const { return lastError_; } bool dazeus::Database::open() { #ifdef DEBUG fprintf(stderr, "Initiating connection to Mongo daemon at %s:%d\n", dbc_.hostname.c_str(), dbc_.port); #endif m_ = (void*)mongo_sync_connect(dbc_.hostname.c_str(), dbc_.port, TRUE); if(!m_) { lastError_ = strerror(errno); #ifdef DEBUG fprintf(stderr, "Connection error: %s\n", lastError_.c_str()); #endif return false; } if(!mongo_sync_conn_set_auto_reconnect(M, TRUE)) { lastError_ = strerror(errno); mongo_sync_disconnect(M); #ifdef DEBUG fprintf(stderr, "Cannot set auto-reconnect: %s\n", lastError_.c_str()); #endif return false; } #ifdef DEBUG fprintf(stderr, "Building index on table %s...\n", PROPERTIES); #endif bson *index = bson_build( BSON_TYPE_INT32, "network", 1, BSON_TYPE_INT32, "receiver", 1, BSON_TYPE_INT32, "sender", 1, BSON_TYPE_NONE ); bson_finish(index); std::string properties = dbc_.database + ".properties"; if(!mongo_sync_cmd_index_create(M, properties.c_str(), index, 0)) { #ifdef DEBUG fprintf(stderr, "Index create error: %s\n", strerror(errno)); #endif lastError_ = strerror(errno); bson_free(index); return false; } bson_free(index); return true; } /** * @brief Retrieve all properties under a certain namespace. * * All properties whose names start with the given namespace name, then a * single dot, and that match the given scope values, are returned from this * method. * * This method guarantees that if it returns a certain key, property() will * return the correct value of that key given that network, receiver and * sender scope are the same. */ std::vector<std::string> dazeus::Database::propertyKeys( const std::string &ns, const std::string &networkScope, const std::string &receiverScope, const std::string &senderScope ) { std::stringstream regexStr; regexStr << "^\\Q" << ns << "\\E\\."; std::string regex = regexStr.str(); bson *selector = bson_new(); bson_append_regex(selector, "variable", regex.c_str(), ""); if(networkScope.length() > 0) { bson_append_string(selector, "network", networkScope.c_str(), -1); if(receiverScope.length() > 0) { bson_append_string(selector, "receiver", receiverScope.c_str(), -1); if(senderScope.length() > 0) { bson_append_string(selector, "sender", senderScope.c_str(), -1); } else { bson_append_null(selector, "sender"); } } else { bson_append_null(selector, "receiver"); bson_append_null(selector, "sender"); } } else { bson_append_null(selector, "network"); bson_append_null(selector, "receiver"); bson_append_null(selector, "sender"); } bson_finish(selector); std::string properties = dbc_.database + ".properties"; mongo_packet *p = mongo_sync_cmd_query(M, properties.c_str(), 0, 0, 0, selector, NULL /* TODO: variable only? */); bson_free(selector); if(!p) { lastError_ = strerror(errno); #ifdef DEBUG fprintf(stderr, "Database error: %s\n", lastError_.c_str()); #endif return std::vector<std::string>(); } mongo_sync_cursor *cursor = mongo_sync_cursor_new(M, properties.c_str(), p); if(!cursor) { lastError_ = strerror(errno); #ifdef DEBUG fprintf(stderr, "Database error: %s\n", lastError_.c_str()); #endif return std::vector<std::string>(); } std::vector<std::string> res; while(mongo_sync_cursor_next(cursor)) { bson *result = mongo_sync_cursor_get_data(cursor); if(!result) { lastError_ = strerror(errno); #ifdef DEBUG fprintf(stderr, "Database error: %s\n", lastError_.c_str()); #endif mongo_sync_cursor_free(cursor); return res; } bson_cursor *c = bson_find(result, "variable"); const char *value; if(!bson_cursor_get_string(c, &value)) { lastError_ = strerror(errno); #ifdef DEBUG fprintf(stderr, "Database error: %s\n", lastError_.c_str()); #endif mongo_sync_cursor_free(cursor); bson_cursor_free(c); return res; } value += ns.length() + 1; res.push_back(value); } return res; } /** * @brief Retrieve property from database. * * The most specific scope will be selected first, i.e. user-specific scope. * If that yields no results, channel-specific scope will be returned, then * network-specific scope, then global scope. * * Variable should be formatted using reverse-domain format, i.e. for the * plugin MyFirstPlugin created by John Doe, to save a 'foo' variable one * could use: * <code>net.jondoe.myfirstplugin.foo</code> */ std::string dazeus::Database::property( const std::string &variable, const std::string &networkScope, const std::string &receiverScope, const std::string &senderScope ) { // variable, [networkScope, [receiverScope, [senderScope]]] // (empty if not given) // db.c. // find() // for everything // find({network:{$in: ['NETWORKNAME',null]}}) // for network scope // find({network:{$in: ['NETWORKNAME',null]}, receiver:{$in: ['RECEIVER',null]}}) // for receiver scope // find({network:..., receiver:..., sender:{$in: ['SENDER',null]}}) // for sender scope // .sort({'a':-1,'b':-1,'c':-1}).limit(1) // Reverse sort and limit(1) will make sure we only receive the most // specific result. This works, as long as the assumption is true that // no specific fields are set without their less specific fields also // being set (i.e. receiver can't be empty if sender is non-empty). bson *query = bson_build_full( BSON_TYPE_DOCUMENT, "$orderby", TRUE, bson_build(BSON_TYPE_INT32, "network", -1, BSON_TYPE_INT32, "receiver", -1, BSON_TYPE_INT32, "sender", -1, BSON_TYPE_NONE), BSON_TYPE_NONE ); /* '$query':{ 'variable':'foo', 'network':{'$in':['bla',null]}, 'receiver':{'$in':['moo', null]}, } */ bson *selector = bson_new(); bson *network = 0, *receiver = 0, *sender = 0; bson_append_string(selector, "variable", variable.c_str(), -1); if(networkScope.length() > 0) { network = bson_build_full( BSON_TYPE_ARRAY, "$in", TRUE, bson_build(BSON_TYPE_STRING, "1", networkScope.c_str(), -1, BSON_TYPE_NULL, "2", BSON_TYPE_NONE), BSON_TYPE_NONE ); bson_finish(network); bson_append_document(selector, "network", network); if(receiverScope.length() > 0) { receiver = bson_build_full( BSON_TYPE_ARRAY, "$in", TRUE, bson_build(BSON_TYPE_STRING, "1", receiverScope.c_str(), -1, BSON_TYPE_NULL, "2", BSON_TYPE_NONE), BSON_TYPE_NONE ); bson_finish(receiver); bson_append_document(selector, "receiver", receiver); if(senderScope.length() > 0) { sender = bson_build_full( BSON_TYPE_ARRAY, "$in", TRUE, bson_build(BSON_TYPE_STRING, "1", senderScope.c_str(), -1, BSON_TYPE_NULL, "2", BSON_TYPE_NONE), BSON_TYPE_NONE ); bson_finish(sender); bson_append_document(selector, "sender", sender); } } } bson_finish(selector); bson_append_document(query, "$query", selector); bson_finish(query); std::string properties = dbc_.database + ".properties"; mongo_packet *p = mongo_sync_cmd_query(M, properties.c_str(), 0, 0, 1, query, NULL /* TODO: value only? */); bson_free(query); bson_free(selector); if(network) bson_free(network); if(receiver) bson_free(receiver); if(sender) bson_free(sender); if(!p) { lastError_ = strerror(errno); return std::string(); } mongo_sync_cursor *cursor = mongo_sync_cursor_new(M, properties.c_str(), p); if(!cursor) { lastError_ = strerror(errno); return std::string(); } if(!mongo_sync_cursor_next(cursor)) { #ifdef DEBUG fprintf(stderr, "Variable %s not found within given scope.\n", variable.c_str()); #endif } bson *result = mongo_sync_cursor_get_data(cursor); if(!result) { lastError_ = strerror(errno); mongo_sync_cursor_free(cursor); return std::string(); } bson_cursor *c = bson_find(result, "value"); const char *value; if(!bson_cursor_get_string(c, &value)) { lastError_ = strerror(errno); #ifdef DEBUG fprintf(stderr, "Database error: %s\n", lastError_.c_str()); #endif mongo_sync_cursor_free(cursor); bson_cursor_free(c); return std::string(); } std::string res(value); bson_free(result); bson_cursor_free(c); // only one result assert(!mongo_sync_cursor_next(cursor)); mongo_sync_cursor_free(cursor); return res; } void dazeus::Database::setProperty( const std::string &variable, const std::string &value, const std::string &networkScope, const std::string &receiverScope, const std::string &senderScope ) { /** selector: {network:'foo',receiver:'bar',sender:null,variable:'bla.blob'} object: {'$set':{ 'value': 'bla'}} */ bson *object = bson_build_full( BSON_TYPE_DOCUMENT, "$set", TRUE, bson_build( BSON_TYPE_STRING, "value", value.c_str(), -1, BSON_TYPE_NONE), BSON_TYPE_NONE); bson_finish(object); bson *selector = bson_build( BSON_TYPE_STRING, "variable", variable.c_str(), -1, BSON_TYPE_NONE); if(networkScope.length() > 0) { bson_append_string(selector, "network", networkScope.c_str(), -1); if(receiverScope.length() > 0) { bson_append_string(selector, "receiver", receiverScope.c_str(), -1); if(senderScope.length() > 0) { bson_append_string(selector, "sender", senderScope.c_str(), -1); } else { bson_append_null(selector, "sender"); } } else { bson_append_null(selector, "receiver"); bson_append_null(selector, "sender"); } } else { bson_append_null(selector, "network"); bson_append_null(selector, "receiver"); bson_append_null(selector, "sender"); } bson_finish(selector); std::string properties = dbc_.database + ".properties"; // if the value length is zero, run a delete instead if(value.length() == 0) { if(!mongo_sync_cmd_delete(M, properties.c_str(), 0, selector)) { lastError_ = strerror(errno); #ifdef DEBUG fprintf(stderr, "Error: %s\n", lastError_.c_str()); #endif } } else if(!mongo_sync_cmd_update(M, properties.c_str(), MONGO_WIRE_FLAG_UPDATE_UPSERT, selector, object)) { lastError_ = strerror(errno); #ifdef DEBUG fprintf(stderr, "Error: %s\n", lastError_.c_str()); #endif } bson_free(object); bson_free(selector); } <|endoftext|>
<commit_before> #include <rosplan_planning_system/PlanDispatch/SimplePlanDispatcher.h> #include "rosplan_planning_system/PlanDispatch/SimplePlanDispatcher.h" namespace KCL_rosplan { /*-------------*/ /* constructor */ /*-------------*/ SimplePlanDispatcher::SimplePlanDispatcher(ros::NodeHandle& nh) : PlanDispatcher(nh) { node_handle = &nh; // knowledge base services std::stringstream ss; ss << "/" << kb_ << "/query_state"; queryKnowledgeClient = node_handle->serviceClient<rosplan_knowledge_msgs::KnowledgeQueryService>(ss.str()); ss.str(""); reset(); } SimplePlanDispatcher::~SimplePlanDispatcher() { } void SimplePlanDispatcher::reset() { PlanDispatcher::reset(); current_action = 0; } /*-------------------*/ /* Plan subscription */ /*-------------------*/ void SimplePlanDispatcher::planCallback(const rosplan_dispatch_msgs::CompletePlan plan) { ROS_INFO("KCL: (%s) Plan received.", ros::this_node::getName().c_str()); plan_received = true; mission_start_time = ros::WallTime::now().toSec(); current_plan = plan; } /*-----------------*/ /* action dispatch */ /*-----------------*/ /* * Loop through and publish planned actions */ bool SimplePlanDispatcher::dispatchPlan(double missionStartTime, double planStartTime) { ROS_INFO("KCL: (%s) Dispatching plan", ros::this_node::getName().c_str()); ros::Rate loop_rate(10); replan_requested = false; while (ros::ok() && current_plan.plan.size() > current_action) { // loop while dispatch is paused while (ros::ok() && dispatch_paused) { ros::spinOnce(); loop_rate.sleep(); } // cancel plan if(plan_cancelled) { break; } // get next action rosplan_dispatch_msgs::ActionDispatch currentMessage = current_plan.plan[current_action]; // check action preconditions if(!checkPreconditions(currentMessage)) { ROS_INFO("KCL: (%s) Preconditions not achieved [%i, %s]", ros::this_node::getName().c_str(), currentMessage.action_id, currentMessage.name.c_str()); // publish feedback (precondition false) rosplan_dispatch_msgs::ActionFeedback fb; fb.action_id = currentMessage.action_id; fb.status = "precondition false"; publishFeedback(fb); replan_requested = true; } else { std:: string params = "("; for (size_t i = 0; i < currentMessage.parameters.size(); ++i) { if (i > 0) params += ", "; params += currentMessage.parameters[i].value; } params += ")"; // dispatch action ROS_INFO("KCL: (%s) Dispatching action [%i, %s%s, %f, %f]", ros::this_node::getName().c_str(), currentMessage.action_id, currentMessage.name.c_str(), params.c_str(), (currentMessage.dispatch_time+planStartTime-missionStartTime), currentMessage.duration); action_dispatch_publisher.publish(currentMessage); // publish feedback (action dispatched) rosplan_dispatch_msgs::ActionFeedback fb; fb.action_id = currentMessage.action_id; fb.status = "action dispatched"; publishFeedback(fb); double late_print = (ros::WallTime::now().toSec() - (currentMessage.dispatch_time+planStartTime)); if(late_print>0.1) { ROS_INFO("KCL: (%s) Action [%i] is %f second(s) late", ros::this_node::getName().c_str(), currentMessage.action_id, late_print); } // wait for action to complete while (ros::ok() && !action_completed[current_action]) { ros::spinOnce(); loop_rate.sleep(); } } // get ready for next action current_action++; action_received[current_action] = false; action_completed[current_action] = false; // finish dispatch and replan if(replan_requested) return false; } ROS_INFO("KCL: (%s) Dispatch complete.", ros::this_node::getName().c_str()); return true; } /*------------------*/ /* general feedback */ /*------------------*/ /** * listen to and process actionFeedback topic. */ void SimplePlanDispatcher::feedbackCallback(const rosplan_dispatch_msgs::ActionFeedback::ConstPtr& msg) { // create error if the action is unrecognised ROS_INFO("KCL: (%s) Feedback received [%i, %s]", ros::this_node::getName().c_str(), msg->action_id, msg->status.c_str()); if(current_action != (unsigned int)msg->action_id) ROS_ERROR("KCL: (%s) Unexpected action ID: %d; current action: %d", ros::this_node::getName().c_str(), msg->action_id, current_action); // action enabled if(!action_received[msg->action_id] && (0 == msg->status.compare("action enabled"))) action_received[msg->action_id] = true; // action completed (successfuly) if(!action_completed[msg->action_id] && 0 == msg->status.compare("action achieved")) action_completed[msg->action_id] = true; // action completed (failed) if(!action_completed[msg->action_id] && 0 == msg->status.compare("action failed")) { replan_requested = true; action_completed[msg->action_id] = true; } } } // close namespace /*-------------*/ /* Main method */ /*-------------*/ int main(int argc, char **argv) { ros::init(argc,argv,"rosplan_simple_plan_dispatcher"); ros::NodeHandle nh("~"); KCL_rosplan::SimplePlanDispatcher spd(nh); // subscribe to planner output std::string planTopic = "complete_plan"; nh.getParam("plan_topic", planTopic); ros::Subscriber plan_sub = nh.subscribe(planTopic, 1, &KCL_rosplan::SimplePlanDispatcher::planCallback, &spd); std::string feedbackTopic = "action_feedback"; nh.getParam("action_feedback_topic", feedbackTopic); ros::Subscriber feedback_sub = nh.subscribe(feedbackTopic, 1, &KCL_rosplan::SimplePlanDispatcher::feedbackCallback, &spd); ROS_INFO("KCL: (%s) Ready to receive", ros::this_node::getName().c_str()); ros::spin(); return 0; } <commit_msg>For our application, we have been using the Simple Dispatcher. We at times dispatch and complete actions very rapidly. There have been instances where the Simple Dispatcher will drop important messages ('action achieved') because its subscription buffer size for feedback/status is only 1. This can cause our system to abruptly stop dispatching new commands because it is not informed that it has successfully completed the prior action. Increasing the buffer size of the action feedback status from to 1 to 1000 has solved our issue.<commit_after> #include <rosplan_planning_system/PlanDispatch/SimplePlanDispatcher.h> #include "rosplan_planning_system/PlanDispatch/SimplePlanDispatcher.h" namespace KCL_rosplan { /*-------------*/ /* constructor */ /*-------------*/ SimplePlanDispatcher::SimplePlanDispatcher(ros::NodeHandle& nh) : PlanDispatcher(nh) { node_handle = &nh; // knowledge base services std::stringstream ss; ss << "/" << kb_ << "/query_state"; queryKnowledgeClient = node_handle->serviceClient<rosplan_knowledge_msgs::KnowledgeQueryService>(ss.str()); ss.str(""); reset(); } SimplePlanDispatcher::~SimplePlanDispatcher() { } void SimplePlanDispatcher::reset() { PlanDispatcher::reset(); current_action = 0; } /*-------------------*/ /* Plan subscription */ /*-------------------*/ void SimplePlanDispatcher::planCallback(const rosplan_dispatch_msgs::CompletePlan plan) { ROS_INFO("KCL: (%s) Plan received.", ros::this_node::getName().c_str()); plan_received = true; mission_start_time = ros::WallTime::now().toSec(); current_plan = plan; } /*-----------------*/ /* action dispatch */ /*-----------------*/ /* * Loop through and publish planned actions */ bool SimplePlanDispatcher::dispatchPlan(double missionStartTime, double planStartTime) { ROS_INFO("KCL: (%s) Dispatching plan", ros::this_node::getName().c_str()); ros::Rate loop_rate(10); replan_requested = false; while (ros::ok() && current_plan.plan.size() > current_action) { // loop while dispatch is paused while (ros::ok() && dispatch_paused) { ros::spinOnce(); loop_rate.sleep(); } // cancel plan if(plan_cancelled) { break; } // get next action rosplan_dispatch_msgs::ActionDispatch currentMessage = current_plan.plan[current_action]; // check action preconditions if(!checkPreconditions(currentMessage)) { ROS_INFO("KCL: (%s) Preconditions not achieved [%i, %s]", ros::this_node::getName().c_str(), currentMessage.action_id, currentMessage.name.c_str()); // publish feedback (precondition false) rosplan_dispatch_msgs::ActionFeedback fb; fb.action_id = currentMessage.action_id; fb.status = "precondition false"; publishFeedback(fb); replan_requested = true; } else { std:: string params = "("; for (size_t i = 0; i < currentMessage.parameters.size(); ++i) { if (i > 0) params += ", "; params += currentMessage.parameters[i].value; } params += ")"; // dispatch action ROS_INFO("KCL: (%s) Dispatching action [%i, %s%s, %f, %f]", ros::this_node::getName().c_str(), currentMessage.action_id, currentMessage.name.c_str(), params.c_str(), (currentMessage.dispatch_time+planStartTime-missionStartTime), currentMessage.duration); action_dispatch_publisher.publish(currentMessage); // publish feedback (action dispatched) rosplan_dispatch_msgs::ActionFeedback fb; fb.action_id = currentMessage.action_id; fb.status = "action dispatched"; publishFeedback(fb); double late_print = (ros::WallTime::now().toSec() - (currentMessage.dispatch_time+planStartTime)); if(late_print>0.1) { ROS_INFO("KCL: (%s) Action [%i] is %f second(s) late", ros::this_node::getName().c_str(), currentMessage.action_id, late_print); } // wait for action to complete while (ros::ok() && !action_completed[current_action]) { ros::spinOnce(); loop_rate.sleep(); } } // get ready for next action current_action++; action_received[current_action] = false; action_completed[current_action] = false; // finish dispatch and replan if(replan_requested) return false; } ROS_INFO("KCL: (%s) Dispatch complete.", ros::this_node::getName().c_str()); return true; } /*------------------*/ /* general feedback */ /*------------------*/ /** * listen to and process actionFeedback topic. */ void SimplePlanDispatcher::feedbackCallback(const rosplan_dispatch_msgs::ActionFeedback::ConstPtr& msg) { // create error if the action is unrecognised ROS_INFO("KCL: (%s) Feedback received [%i, %s]", ros::this_node::getName().c_str(), msg->action_id, msg->status.c_str()); if(current_action != (unsigned int)msg->action_id) ROS_ERROR("KCL: (%s) Unexpected action ID: %d; current action: %d", ros::this_node::getName().c_str(), msg->action_id, current_action); // action enabled if(!action_received[msg->action_id] && (0 == msg->status.compare("action enabled"))) action_received[msg->action_id] = true; // action completed (successfuly) if(!action_completed[msg->action_id] && 0 == msg->status.compare("action achieved")) action_completed[msg->action_id] = true; // action completed (failed) if(!action_completed[msg->action_id] && 0 == msg->status.compare("action failed")) { replan_requested = true; action_completed[msg->action_id] = true; } } } // close namespace /*-------------*/ /* Main method */ /*-------------*/ int main(int argc, char **argv) { ros::init(argc,argv,"rosplan_simple_plan_dispatcher"); ros::NodeHandle nh("~"); KCL_rosplan::SimplePlanDispatcher spd(nh); // subscribe to planner output std::string planTopic = "complete_plan"; nh.getParam("plan_topic", planTopic); ros::Subscriber plan_sub = nh.subscribe(planTopic, 1, &KCL_rosplan::SimplePlanDispatcher::planCallback, &spd); std::string feedbackTopic = "action_feedback"; nh.getParam("action_feedback_topic", feedbackTopic); ros::Subscriber feedback_sub = nh.subscribe(feedbackTopic, 1000, &KCL_rosplan::SimplePlanDispatcher::feedbackCallback, &spd); ROS_INFO("KCL: (%s) Ready to receive", ros::this_node::getName().c_str()); ros::spin(); return 0; } <|endoftext|>
<commit_before>/* Copyright (C) 2003 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <NDBT_Table.hpp> #include <NdbTimer.hpp> #include <NDBT.hpp> class NdbOut& operator <<(class NdbOut& ndbout, const NDBT_Table & tab) { ndbout << "-- " << tab.getName() << " --" << endl; ndbout << "Version: " << tab.getObjectVersion() << endl; ndbout << "Fragment type: " << (unsigned) tab.getFragmentType() << endl; ndbout << "K Value: " << tab.getKValue()<< endl; ndbout << "Min load factor: " << tab.getMinLoadFactor()<< endl; ndbout << "Max load factor: " << tab.getMaxLoadFactor()<< endl; ndbout << "Temporary table: " << (tab.getStoredTable() ? "no" : "yes") << endl; ndbout << "Number of attributes: " << tab.getNoOfColumns() << endl; ndbout << "Number of primary keys: " << tab.getNoOfPrimaryKeys() << endl; ndbout << "Length of frm data: " << tab.getFrmLength() << endl; ndbout << "SingleUserMode: " << tab.getSingleUserMode() << endl; //<< ((tab.getTupleKey() == TupleId) ? " tupleid" : "") <<endl; ndbout << "TableStatus: "; switch(tab.getObjectStatus()){ case NdbDictionary::Object::New: ndbout << "New" << endl; break; case NdbDictionary::Object::Changed: ndbout << "Changed" << endl; break; case NdbDictionary::Object::Retrieved: ndbout << "Retrieved" << endl; break; default: ndbout << "Unknown(" << (unsigned) tab.getObjectStatus() << ")" << endl; } ndbout << "-- Attributes -- " << endl; int noOfAttributes = tab.getNoOfColumns(); for(int i = 0; i<noOfAttributes; i++){ ndbout << (* (const NDBT_Attribute*)tab.getColumn(i)) << endl; } return ndbout; } class NdbOut& operator <<(class NdbOut&, const NdbDictionary::Index & idx) { ndbout << idx.getName(); ndbout << "("; for (unsigned i=0; i < idx.getNoOfColumns(); i++) { const NdbDictionary::Column *col = idx.getColumn(i); ndbout << col->getName(); if (i < idx.getNoOfColumns()-1) ndbout << ", "; } ndbout << ")"; ndbout << " - "; switch (idx.getType()) { case NdbDictionary::Object::UniqueHashIndex: ndbout << "UniqueHashIndex"; break; case NdbDictionary::Object::OrderedIndex: ndbout << "OrderedIndex"; break; default: ndbout << "Type " << (unsigned) idx.getType(); break; } return ndbout; } <commit_msg>remove warning<commit_after>/* Copyright (C) 2003 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <NDBT_Table.hpp> #include <NdbTimer.hpp> #include <NDBT.hpp> class NdbOut& operator <<(class NdbOut& ndbout, const NDBT_Table & tab) { ndbout << "-- " << tab.getName() << " --" << endl; ndbout << "Version: " << tab.getObjectVersion() << endl; ndbout << "Fragment type: " << (unsigned) tab.getFragmentType() << endl; ndbout << "K Value: " << tab.getKValue()<< endl; ndbout << "Min load factor: " << tab.getMinLoadFactor()<< endl; ndbout << "Max load factor: " << tab.getMaxLoadFactor()<< endl; ndbout << "Temporary table: " << (tab.getStoredTable() ? "no" : "yes") << endl; ndbout << "Number of attributes: " << tab.getNoOfColumns() << endl; ndbout << "Number of primary keys: " << tab.getNoOfPrimaryKeys() << endl; ndbout << "Length of frm data: " << tab.getFrmLength() << endl; ndbout << "SingleUserMode: " << (Uint32) tab.getSingleUserMode() << endl; //<< ((tab.getTupleKey() == TupleId) ? " tupleid" : "") <<endl; ndbout << "TableStatus: "; switch(tab.getObjectStatus()){ case NdbDictionary::Object::New: ndbout << "New" << endl; break; case NdbDictionary::Object::Changed: ndbout << "Changed" << endl; break; case NdbDictionary::Object::Retrieved: ndbout << "Retrieved" << endl; break; default: ndbout << "Unknown(" << (unsigned) tab.getObjectStatus() << ")" << endl; } ndbout << "-- Attributes -- " << endl; int noOfAttributes = tab.getNoOfColumns(); for(int i = 0; i<noOfAttributes; i++){ ndbout << (* (const NDBT_Attribute*)tab.getColumn(i)) << endl; } return ndbout; } class NdbOut& operator <<(class NdbOut&, const NdbDictionary::Index & idx) { ndbout << idx.getName(); ndbout << "("; for (unsigned i=0; i < idx.getNoOfColumns(); i++) { const NdbDictionary::Column *col = idx.getColumn(i); ndbout << col->getName(); if (i < idx.getNoOfColumns()-1) ndbout << ", "; } ndbout << ")"; ndbout << " - "; switch (idx.getType()) { case NdbDictionary::Object::UniqueHashIndex: ndbout << "UniqueHashIndex"; break; case NdbDictionary::Object::OrderedIndex: ndbout << "OrderedIndex"; break; default: ndbout << "Type " << (unsigned) idx.getType(); break; } return ndbout; } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include "../src/base/lib_common2.hpp" #include "../src/base/lib_common3.hpp" #include "../src/base/useot.hpp" using namespace nOT::nUtils; class cUseOtTest: public testing::Test { protected: std::shared_ptr<nOT::nUse::cUseOT> useOt; std::string nym1; std::string toNym; std::string fromAcc; std::string fromNym; int32_t amount; virtual void SetUp() { nym1 = "alice"; toNym = "FT's Test Nym"; fromNym = "Trader Bob"; fromAcc = "Bob's Tokens"; amount = 100; useOt = std::make_shared<nOT::nUse::cUseOT>("test"); } virtual void TearDown() { } }; TEST_F(cUseOtTest, OutPayments) { EXPECT_FALSE(useOt->OutpaymentsShow(nym1, 200, 0)); EXPECT_FALSE(useOt->OutpaymentsShow(nym1, -1, 0)); } TEST_F(cUseOtTest, VoucherCreate) { EXPECT_FALSE(useOt->VoucherWithdraw(nym1, -20, "bitcoins", "some memo", 0)); auto accID = useOt->AccountGetId(fromAcc); auto ballance = opentxs::OTAPI_Wrap::GetAccountWallet_Balance(accID); EXPECT_FALSE(useOt->VoucherWithdraw(toNym, ballance + 1, fromAcc, "", false)); EXPECT_TRUE(useOt->VoucherWithdraw(toNym, amount, fromAcc, "", false)); EXPECT_TRUE(useOt->OutpaymentsShow(fromNym, 0, false)); EXPECT_EQ(ballance - amount, opentxs::OTAPI_Wrap::GetAccountWallet_Balance(accID)); } TEST_F(cUseOtTest, VoucherDeposit) { auto accID = useOt->AccountGetId(fromAcc); auto ballance = opentxs::OTAPI_Wrap::GetAccountWallet_Balance(accID) - amount; EXPECT_TRUE(useOt->VoucherDeposit(fromAcc, toNym, 0, false)); EXPECT_TRUE(useOt->AccountInAccept(fromAcc, 0, false, false)); EXPECT_EQ(ballance, opentxs::OTAPI_Wrap::GetAccountWallet_Balance(accID)); EXPECT_FALSE(useOt->OutpaymentsShow(fromNym, 0, false)); } /* TEST_F(cUseOtTest, VoucherSend) { std::string fromNym = "FT's Test Nym"; auto result = useOt->VoucherSend(fromNym, 0, false); EXPECT_TRUE(result); }*/ <commit_msg>working unittests for vouchers<commit_after>#include "gtest/gtest.h" #include "../src/base/lib_common2.hpp" #include "../src/base/lib_common3.hpp" #include "../src/base/useot.hpp" using namespace nOT::nUtils; class cUseOtTest: public testing::Test { protected: std::shared_ptr<nOT::nUse::cUseOT> useOt; std::string nym1; std::string toNym; std::string fromAcc; std::string fromNym; int32_t amount; virtual void SetUp() { nym1 = "Trader Bob"; toNym = "FT's Test Nym"; fromNym = "Trader Bob"; fromAcc = "Bob's Tokens"; amount = 100; useOt = std::make_shared<nOT::nUse::cUseOT>("test"); } virtual void TearDown() { } }; TEST_F(cUseOtTest, OutPayments) { EXPECT_FALSE(useOt->OutpaymentsShow(nym1, 200, 0)); EXPECT_FALSE(useOt->OutpaymentsShow(nym1, -1, 0)); } TEST_F(cUseOtTest, VoucherCreate) { EXPECT_FALSE(useOt->VoucherWithdraw(nym1, -20, "bitcoins", "some memo", 0)); auto accID = useOt->AccountGetId(fromAcc); auto ballance = opentxs::OTAPI_Wrap::GetAccountWallet_Balance(accID); EXPECT_FALSE(useOt->VoucherWithdraw(toNym, ballance + 1, fromAcc, "", false)); ASSERT_TRUE(useOt->VoucherWithdraw(toNym, amount, fromAcc, "", false)); ASSERT_TRUE(useOt->OutpaymentsShow(fromNym, 0, false)); EXPECT_EQ(ballance - amount, opentxs::OTAPI_Wrap::GetAccountWallet_Balance(accID)); } TEST_F(cUseOtTest, VoucherDeposit) { auto accID = useOt->AccountGetId(fromAcc); auto currentBallance = opentxs::OTAPI_Wrap::GetAccountWallet_Balance(accID); ASSERT_TRUE(useOt->VoucherDeposit(fromAcc, fromNym, 0, false)); EXPECT_TRUE(useOt->AccountInAccept(fromAcc, 0, false, false)); EXPECT_EQ(currentBallance + amount, opentxs::OTAPI_Wrap::GetAccountWallet_Balance(accID)); //EXPECT_FALSE(useOt->OutpaymentsShow(fromNym, 0, false)); } /* TEST_F(cUseOtTest, VoucherSend) { std::string fromNym = "FT's Test Nym"; auto result = useOt->VoucherSend(fromNym, 0, false); EXPECT_TRUE(result); }*/ <|endoftext|>
<commit_before>#ifndef _SDD_DD_STACK_HH_ #define _SDD_DD_STACK_HH_ #include <algorithm> #include <vector> #include "sdd/dd/default_value.hh" #include "sdd/util/hash.hh" namespace sdd { namespace dd { /*------------------------------------------------------------------------------------------------*/ template <typename T> struct stack { std::vector<T> elements; T operator[] (std::size_t i) const { if (i < this->elements.size()) return this->elements[i]; else return default_value<T>::value(); } template <typename Shift> stack<T>& shift(const stack<T>& rhs, Shift&& sh) { std::size_t max_size = std::max(size(*this), size(rhs)); this->elements.resize(max_size, default_value<T>::value()); for (int i = 0; i != max_size; ++i) this->elements[i] = sh(this->elements[i], rhs[i]); return canonize(*this); } template <typename Rebuild> stack<T>& rebuild(const stack<T>& rhs, Rebuild&& rb) { std::size_t max_size = std::max(size(*this), size(rhs)); this->elements.resize(max_size, default_value<T>::value()); for (int i = 0; i != max_size; ++i) this->elements[i] = rb(this->elements[i], rhs[i]); return canonize(*this); } }; template <typename T> stack<T> push (const stack<T>& s, const T& e) { if (s.elements.empty() && (e == default_value<T>::value())) return s; else { stack<T> result; result.elements.reserve(s.elements.size() + 1); result.elements.push_back(e); for (const auto& x : s.elements) result.elements.push_back(x); return result; } } template <typename T> stack<T> pop (const stack<T>& s) { if (s.elements.empty()) return s; else { stack<T> result; result.elements.reserve(s.elements.size() - 1); for (int i = 1; i != s.elements.size(); ++i) result.elements.push_back(s.elements[i]); return result; } } template <typename T> T head (const stack<T>& s) { if (s.elements.empty()) return default_value<T>::value(); else return s.elements.front(); } template <typename T> std::ostream& operator<< (std::ostream& os, const stack<T>& s) { os << "["; for (const auto& x : s.elements) os << " " << x; return os << " ]"; } template <typename T> std::size_t size (const stack<T>& s) { return s.elements.size(); } template <typename T> stack<T>& canonize (stack<T>& s) { for (std::size_t i = s.elements.size() ; i > 0; --i) { if (s[i-1] == default_value<T>::value()) s.elements.pop_back(); else break; } s.elements.shrink_to_fit(); return s; } template <typename T, typename Common> stack<T> common (const std::vector<std::reference_wrapper<const stack<T>>>& ss, Common&& cm) { std::size_t max_size = 0; for (const auto& s : ss) max_size = std::max(max_size, size(s.get())); stack<T> result; result.elements.reserve(max_size); std::vector<T> values; values.reserve(ss.size()); for (int i = 0; i != max_size; ++i) { for (const auto& s : ss) values.push_back(s.get()[i]); result.elements.push_back(cm(values.begin(), values.end())); values.clear(); } return canonize(result); } /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief Equality of two stack. /// @related stack template <typename T> inline bool operator==(const stack<T>& lhs, const stack<T>& rhs) noexcept { return lhs.elements == rhs.elements; } /*------------------------------------------------------------------------------------------------*/ }} // namespace sdd::dd namespace std { /*------------------------------------------------------------------------------------------------*/ /// @brief Hash specialization for sdd::dd::stack template <typename T> struct hash<sdd::dd::stack<T>> { std::size_t operator()(const sdd::dd::stack<T>& s) const { if (s.elements.empty()) { return sdd::util::hash(0); } else { return sdd::util::hash(s.elements.cbegin(), s.elements.cend()); } } }; /*------------------------------------------------------------------------------------------------*/ } // namespace std #endif // _SDD_DD_SPARSE_STACK_HH_ <commit_msg>Remove useless template parameters.<commit_after>#ifndef _SDD_DD_STACK_HH_ #define _SDD_DD_STACK_HH_ #include <algorithm> #include <vector> #include "sdd/dd/default_value.hh" #include "sdd/util/hash.hh" namespace sdd { namespace dd { /*------------------------------------------------------------------------------------------------*/ template <typename T> struct stack { std::vector<T> elements; T operator[] (std::size_t i) const { if (i < this->elements.size()) return this->elements[i]; else return default_value<T>::value(); } template <typename Shift> stack& shift(const stack& rhs, Shift&& sh) { std::size_t max_size = std::max(size(*this), size(rhs)); this->elements.resize(max_size, default_value<T>::value()); for (int i = 0; i != max_size; ++i) this->elements[i] = sh(this->elements[i], rhs[i]); return canonize(*this); } template <typename Rebuild> stack& rebuild(const stack& rhs, Rebuild&& rb) { std::size_t max_size = std::max(size(*this), size(rhs)); this->elements.resize(max_size, default_value<T>::value()); for (int i = 0; i != max_size; ++i) this->elements[i] = rb(this->elements[i], rhs[i]); return canonize(*this); } }; template <typename T> stack<T> push (const stack<T>& s, const T& e) { if (s.elements.empty() && (e == default_value<T>::value())) return s; else { stack<T> result; result.elements.reserve(s.elements.size() + 1); result.elements.push_back(e); for (const auto& x : s.elements) result.elements.push_back(x); return result; } } template <typename T> stack<T> pop (const stack<T>& s) { if (s.elements.empty()) return s; else { stack<T> result; result.elements.reserve(s.elements.size() - 1); for (int i = 1; i != s.elements.size(); ++i) result.elements.push_back(s.elements[i]); return result; } } template <typename T> T head (const stack<T>& s) { if (s.elements.empty()) return default_value<T>::value(); else return s.elements.front(); } template <typename T> std::ostream& operator<< (std::ostream& os, const stack<T>& s) { os << "["; for (const auto& x : s.elements) os << " " << x; return os << " ]"; } template <typename T> std::size_t size (const stack<T>& s) { return s.elements.size(); } template <typename T> stack<T>& canonize (stack<T>& s) { for (std::size_t i = s.elements.size() ; i > 0; --i) { if (s[i-1] == default_value<T>::value()) s.elements.pop_back(); else break; } s.elements.shrink_to_fit(); return s; } template <typename T, typename Common> stack<T> common (const std::vector<std::reference_wrapper<const stack<T>>>& ss, Common&& cm) { std::size_t max_size = 0; for (const auto& s : ss) max_size = std::max(max_size, size(s.get())); stack<T> result; result.elements.reserve(max_size); std::vector<T> values; values.reserve(ss.size()); for (int i = 0; i != max_size; ++i) { for (const auto& s : ss) values.push_back(s.get()[i]); result.elements.push_back(cm(values.begin(), values.end())); values.clear(); } return canonize(result); } /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief Equality of two stack. /// @related stack template <typename T> inline bool operator==(const stack<T>& lhs, const stack<T>& rhs) noexcept { return lhs.elements == rhs.elements; } /*------------------------------------------------------------------------------------------------*/ }} // namespace sdd::dd namespace std { /*------------------------------------------------------------------------------------------------*/ /// @brief Hash specialization for sdd::dd::stack template <typename T> struct hash<sdd::dd::stack<T>> { std::size_t operator()(const sdd::dd::stack<T>& s) const { if (s.elements.empty()) { return sdd::util::hash(0); } else { return sdd::util::hash(s.elements.cbegin(), s.elements.cend()); } } }; /*------------------------------------------------------------------------------------------------*/ } // namespace std #endif // _SDD_DD_SPARSE_STACK_HH_ <|endoftext|>
<commit_before>#ifndef _PROFILE_HPP_ #define _PROFILE_HPP_ #include <chrono> #include <functional> #include <iostream> #include <iomanip> #define profile(name, fun) if(profile_block p = profile_block(name, fun)) class profile_block { public: profile_block(std::string name, std::function<void(std::string, long long)> f = COUT_LOG) : block_name(name), func(f) { start = std::chrono::high_resolution_clock::now(); } ~profile_block() { auto elapsed = std::chrono::high_resolution_clock::now() - start; long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count(); if(func) { func(block_name, microseconds); } } operator bool() const { return true; } static std::function<void(std::string, long long)> COUT_LOG; private: std::chrono::high_resolution_clock::time_point start; std::string block_name; std::function<void(std::string, long long)> func; }; std::function<void(std::string, long long)> profile_block::COUT_LOG = [] (std::string block_name, long long elapsed) { std::cout << std::fixed << std::setprecision(3) << "[PROFILE] " << block_name << " completed in " << ((float)elapsed) / 1000.f << " milliseconds" << std::endl; }; #endif<commit_msg>Start adding functionality to profile.hpp<commit_after>#ifndef _PROFILE_HPP_ #define _PROFILE_HPP_ #include <chrono> #include <functional> #include <iostream> #include <iomanip> #define profile(name, fun) if(profile_block p = profile_block(name, fun)) enum steps_enum { STEP1, STEP2, SORT, MEMORY_TRANSFERS }; std::map<steps_enum,std::string> step_names = { { STEP1, "Sph step 1" }, { STEP2, "Sph step 2" }, { SORT, "Sort" }, { MEMORY_TRANSFERS, "Memory transfers" } }; std::map<steps_enum,long long> step_run_length = { { STEP1, 0 }, { STEP2, 0 }, { SORT, 0 }, { MEMORY_TRANSFERS, 0 } }; class profile_block { public: profile_block(std::string name, std::function<void(std::string, long long)> f = COUT_LOG) : block_name(name), func(f) { start = std::chrono::high_resolution_clock::now(); } ~profile_block() { auto elapsed = std::chrono::high_resolution_clock::now() - start; long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count(); if(func) { func(block_name, microseconds); } } operator bool() const { return true; } static std::function<void(std::string, long long)> COUT_LOG; private: std::chrono::high_resolution_clock::time_point start; std::string block_name; std::function<void(std::string, long long)> func; }; std::function<void(std::string, long long)> profile_block::COUT_LOG = [] (std::string block_name, long long elapsed) { std::cout << std::fixed << std::setprecision(3) << "[PROFILE] " << block_name << " completed in " << ((float)elapsed) / 1000.f << " milliseconds" << std::endl; }; #endif<|endoftext|>
<commit_before><commit_msg>Sketcher: Use move semantics wherever sensible<commit_after><|endoftext|>
<commit_before>#include <iostream> #include <algorithm> #include <ev.h> #include <unistd.h> #include <fcntl.h> #include "service.h" #include "dinit-log.h" #include "cpbuffer.h" LogLevel log_level = LogLevel::WARN; LogLevel cons_log_level = LogLevel::WARN; static bool log_to_console = false; // whether we should output log messages to // console immediately static bool log_current_line; // Whether the current line is being logged static ServiceSet *service_set = nullptr; // Reference to service set // Buffer for current log line: constexpr static int log_linebuf_len = 120; // TODO needed? static char * lineBuf = new char[log_linebuf_len]; static int lineBuf_idx = 0; // Buffer of log lines: // (One for main log, one for console) static CPBuffer<4096> log_buffer[2]; // Each line is represented as a string of characters terminated by a // newline. (If the newline is missing, the line is not complete). constexpr static int DLOG_MAIN = 0; // main log facility constexpr static int DLOG_CONS = 1; // console constexpr static char DLOG_MAIN_FLAG = 1 << DLOG_MAIN; constexpr static char DLOG_CONS_FLAG = 1 << DLOG_CONS; static int current_index[2] = { 0, 0 }; // current/next message slot for (main, console) static bool partway[2] = { false, false }; // part-way through writing log line? static int msg_index[2] = { 0, 0 }; // index into the current message static struct ev_io eviocb[2]; static bool discarded[2] = { false, false }; // have discarded a log line? static bool special[2] = { false, false }; // writing from a special buffer? static char *special_buf[2] = { nullptr, nullptr }; // special buffer static void release_console() { ev_io_stop(ev_default_loop(EVFLAG_AUTO), &eviocb[DLOG_CONS]); if (! log_to_console) { int flags = fcntl(1, F_GETFL, 0); fcntl(1, F_SETFL, flags & ~O_NONBLOCK); service_set->pullConsoleQueue(); } } static void log_conn_callback(struct ev_loop * loop, ev_io * w, int revents) noexcept { if (special[DLOG_CONS]) { char * start = special_buf[DLOG_CONS] + msg_index[DLOG_CONS]; char * end = std::find(special_buf[DLOG_CONS] + msg_index[DLOG_CONS], (char *)nullptr, '\n'); int r = write(1, start, end - start + 1); if (r >= 0) { if (start + r > end) { // All written: go on to next message in queue special[DLOG_CONS] = false; partway[DLOG_CONS] = false; msg_index[DLOG_CONS] = 0; } else { msg_index[DLOG_CONS] += r; return; } } else { // spurious readiness - EAGAIN or EWOULDBLOCK? // other error? // TODO } return; } else { // Writing from the regular circular buffer // TODO issue special message if we have discarded a log message if (current_index[DLOG_CONS] == 0) { release_console(); return; } char *ptr = log_buffer[DLOG_CONS].get_ptr(0); int len = log_buffer[DLOG_CONS].get_contiguous_length(ptr); char *creptr = ptr + len; // contiguous region end char *eptr = std::find(ptr, creptr, '\n'); bool will_complete = false; // will complete this message? if (eptr != creptr) { eptr++; // include '\n' will_complete = true; } len = eptr - ptr; int r = write(1, ptr, len); if (r >= 0) { // msg_index[DLOG_CONS] += r; bool complete = (r == len) && will_complete; log_buffer[DLOG_CONS].consume(len); partway[DLOG_CONS] = ! complete; if (complete) { current_index[DLOG_CONS] -= len; if (current_index[DLOG_CONS] == 0 || !log_to_console) { // No more messages buffered / stop logging to console: release_console(); } } } else { // TODO // EAGAIN / EWOULDBLOCK? // error? return; } } // We've written something by the time we get here. We could fall through to below, but // let's give other events a chance to be processed by returning now. return; } void init_log(ServiceSet *sset) noexcept { service_set = sset; enable_console_log(true); } // Enable or disable console logging. If disabled, console logging will be disabled on the // completion of output of the current message (if any), at which point the first service record // queued in the service set will acquire the console. void enable_console_log(bool enable) noexcept { if (enable && ! log_to_console) { // Console is fd 1 - stdout // Set non-blocking IO: int flags = fcntl(1, F_GETFL, 0); fcntl(1, F_SETFL, flags | O_NONBLOCK); // Activate watcher: ev_io_init(&eviocb[DLOG_CONS], log_conn_callback, 1, EV_WRITE); if (current_index[DLOG_CONS] > 0) { ev_io_start(ev_default_loop(EVFLAG_AUTO), &eviocb[DLOG_CONS]); } log_to_console = true; } else if (! enable && log_to_console) { log_to_console = false; if (! partway[DLOG_CONS]) { if (current_index[DLOG_CONS] > 0) { // Try to flush any messages that are currently buffered. (Console is non-blocking // so it will fail gracefully). log_conn_callback(ev_default_loop(EVFLAG_AUTO), &eviocb[DLOG_CONS], EV_WRITE); } else { release_console(); } } // (if we're partway through logging a message, we release the console when // finished). } } // Variadic method to calculate the sum of string lengths: static int sum_length(const char *arg) noexcept { return std::strlen(arg); } template <typename U, typename ... T> static int sum_length(U first, T ... args) noexcept { return sum_length(first) + sum_length(args...); } // Variadic method to append strings to a buffer: static void append(CPBuffer<4096> &buf, const char *s) { buf.append(s, std::strlen(s)); } template <typename U, typename ... T> static void append(CPBuffer<4096> &buf, U u, T ... t) { append(buf, u); append(buf, t...); } // Variadic method to log a sequence of strings as a single message: template <typename ... T> static void do_log(T ... args) noexcept { int amount = sum_length(args...); if (log_buffer[DLOG_CONS].get_free() >= amount) { append(log_buffer[DLOG_CONS], args...); bool was_first = (current_index[DLOG_CONS] == 0); current_index[DLOG_CONS] += amount; if (was_first && log_to_console) { ev_io_start(ev_default_loop(EVFLAG_AUTO), & eviocb[DLOG_CONS]); } } else { // TODO mark a discarded message } } // Variadic method to potentially log a sequence of strings as a single message with the given log level: template <typename ... T> static void do_log(LogLevel lvl, T ... args) noexcept { if (lvl >= cons_log_level) { do_log(args...); } } // Log a message. A newline will be appended. void log(LogLevel lvl, const char *msg) noexcept { do_log(lvl, "dinit: ", msg, "\n"); } // Log a multi-part message beginning void logMsgBegin(LogLevel lvl, const char *msg) noexcept { // TODO use buffer log_current_line = lvl >= log_level; if (log_current_line) { if (log_to_console) { std::cout << "dinit: " << msg; } } } // Continue a multi-part log message void logMsgPart(const char *msg) noexcept { // TODO use buffer if (log_current_line) { if (log_to_console) { std::cout << msg; } } } // Complete a multi-part log message void logMsgEnd(const char *msg) noexcept { // TODO use buffer if (log_current_line) { if (log_to_console) { std::cout << msg << std::endl; } } } void logServiceStarted(const char *service_name) noexcept { do_log("[ OK ] ", service_name, "\n"); } void logServiceFailed(const char *service_name) noexcept { do_log("[FAILED] ", service_name, "\n"); } void logServiceStopped(const char *service_name) noexcept { do_log("[STOPPD] ", service_name, "\n"); } <commit_msg>Refactoring. Move buffered output management (variables) into a class.<commit_after>#include <iostream> #include <algorithm> #include <ev.h> #include <unistd.h> #include <fcntl.h> #include "service.h" #include "dinit-log.h" #include "cpbuffer.h" LogLevel log_level = LogLevel::WARN; LogLevel cons_log_level = LogLevel::WARN; static bool log_to_console = false; // whether we should output log messages to // console immediately static bool log_current_line; // Whether the current line is being logged static ServiceSet *service_set = nullptr; // Reference to service set static void log_conn_callback(struct ev_loop *loop, struct ev_io *w, int revents) noexcept; class BufferedLogStream { public: CPBuffer<4096> log_buffer; struct ev_io eviocb; // Outgoing: bool partway = false; // if we are partway throught output of a log message bool discarded = false; // if we have discarded a message // Incoming: int current_index = 0; // current/next incoming message index // ^^ TODO is this always just the length of log_buffer? // A "special message" is not stored in the circular buffer; instead // it is delivered from an external buffer not managed by BufferedLogger. bool special = false; // currently outputting special message? char *special_buf; // buffer containing special message int msg_index; // index into special message void init(int fd) { ev_io_init(&eviocb, log_conn_callback, fd, EV_WRITE); eviocb.data = this; } }; // Two log streams: // (One for main log, one for console) static BufferedLogStream log_stream[2]; constexpr static int DLOG_MAIN = 0; // main log facility constexpr static int DLOG_CONS = 1; // console static void release_console() { ev_io_stop(ev_default_loop(EVFLAG_AUTO), & log_stream[DLOG_CONS].eviocb); if (! log_to_console) { int flags = fcntl(1, F_GETFL, 0); fcntl(1, F_SETFL, flags & ~O_NONBLOCK); service_set->pullConsoleQueue(); } } static void log_conn_callback(struct ev_loop * loop, ev_io * w, int revents) noexcept { auto &log_stream = *static_cast<BufferedLogStream *>(w->data); if (log_stream.special) { char * start = log_stream.special_buf + log_stream.msg_index; char * end = std::find(log_stream.special_buf + log_stream.msg_index, (char *)nullptr, '\n'); int r = write(w->fd, start, end - start + 1); if (r >= 0) { if (start + r > end) { // All written: go on to next message in queue log_stream.special = false; log_stream.partway = false; log_stream.msg_index = 0; } else { log_stream.msg_index += r; return; } } else { // spurious readiness - EAGAIN or EWOULDBLOCK? // other error? // TODO } return; } else { // Writing from the regular circular buffer // TODO issue special message if we have discarded a log message if (log_stream.current_index == 0) { release_console(); return; } char *ptr = log_stream.log_buffer.get_ptr(0); int len = log_stream.log_buffer.get_contiguous_length(ptr); char *creptr = ptr + len; // contiguous region end char *eptr = std::find(ptr, creptr, '\n'); bool will_complete = false; // will complete this message? if (eptr != creptr) { eptr++; // include '\n' will_complete = true; } len = eptr - ptr; int r = write(w->fd, ptr, len); if (r >= 0) { bool complete = (r == len) && will_complete; log_stream.log_buffer.consume(len); log_stream.partway = ! complete; if (complete) { log_stream.current_index -= len; if (log_stream.current_index == 0 || !log_to_console) { // No more messages buffered / stop logging to console: release_console(); } } } else { // TODO // EAGAIN / EWOULDBLOCK? // error? return; } } // We've written something by the time we get here. We could fall through to below, but // let's give other events a chance to be processed by returning now. return; } void init_log(ServiceSet *sset) noexcept { service_set = sset; enable_console_log(true); } // Enable or disable console logging. If disabled, console logging will be disabled on the // completion of output of the current message (if any), at which point the first service record // queued in the service set will acquire the console. void enable_console_log(bool enable) noexcept { if (enable && ! log_to_console) { // Console is fd 1 - stdout // Set non-blocking IO: int flags = fcntl(1, F_GETFL, 0); fcntl(1, F_SETFL, flags | O_NONBLOCK); // Activate watcher: //ev_io_init(& log_stream[DLOG_CONS].eviocb, log_conn_callback, 1, EV_WRITE); log_stream[DLOG_CONS].init(STDOUT_FILENO); if (log_stream[DLOG_CONS].current_index > 0) { ev_io_start(ev_default_loop(EVFLAG_AUTO), & log_stream[DLOG_CONS].eviocb); } log_to_console = true; } else if (! enable && log_to_console) { log_to_console = false; if (! log_stream[DLOG_CONS].partway) { if (log_stream[DLOG_CONS].current_index > 0) { // Try to flush any messages that are currently buffered. (Console is non-blocking // so it will fail gracefully). log_conn_callback(ev_default_loop(EVFLAG_AUTO), & log_stream[DLOG_CONS].eviocb, EV_WRITE); } else { release_console(); } } // (if we're partway through logging a message, we release the console when // finished). } } // Variadic method to calculate the sum of string lengths: static int sum_length(const char *arg) noexcept { return std::strlen(arg); } template <typename U, typename ... T> static int sum_length(U first, T ... args) noexcept { return sum_length(first) + sum_length(args...); } // Variadic method to append strings to a buffer: static void append(CPBuffer<4096> &buf, const char *s) { buf.append(s, std::strlen(s)); } template <typename U, typename ... T> static void append(CPBuffer<4096> &buf, U u, T ... t) { append(buf, u); append(buf, t...); } // Variadic method to log a sequence of strings as a single message: template <typename ... T> static void do_log(T ... args) noexcept { int amount = sum_length(args...); if (log_stream[DLOG_CONS].log_buffer.get_free() >= amount) { append(log_stream[DLOG_CONS].log_buffer, args...); bool was_first = (log_stream[DLOG_CONS].current_index == 0); log_stream[DLOG_CONS].current_index += amount; if (was_first && log_to_console) { ev_io_start(ev_default_loop(EVFLAG_AUTO), & log_stream[DLOG_CONS].eviocb); } } else { // TODO mark a discarded message } } // Variadic method to potentially log a sequence of strings as a single message with the given log level: template <typename ... T> static void do_log(LogLevel lvl, T ... args) noexcept { if (lvl >= cons_log_level) { do_log(args...); } } // Log a message. A newline will be appended. void log(LogLevel lvl, const char *msg) noexcept { do_log(lvl, "dinit: ", msg, "\n"); } // Log a multi-part message beginning void logMsgBegin(LogLevel lvl, const char *msg) noexcept { // TODO use buffer log_current_line = lvl >= log_level; if (log_current_line) { if (log_to_console) { std::cout << "dinit: " << msg; } } } // Continue a multi-part log message void logMsgPart(const char *msg) noexcept { // TODO use buffer if (log_current_line) { if (log_to_console) { std::cout << msg; } } } // Complete a multi-part log message void logMsgEnd(const char *msg) noexcept { // TODO use buffer if (log_current_line) { if (log_to_console) { std::cout << msg << std::endl; } } } void logServiceStarted(const char *service_name) noexcept { do_log("[ OK ] ", service_name, "\n"); } void logServiceFailed(const char *service_name) noexcept { do_log("[FAILED] ", service_name, "\n"); } void logServiceStopped(const char *service_name) noexcept { do_log("[STOPPD] ", service_name, "\n"); } <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "reconfig_params.h" namespace proton { ReconfigParams:: ReconfigParams(const DocumentDBConfig::ComparisonResult &res) : _res(res) { } bool ReconfigParams::configHasChanged() const { return _res.rankProfilesChanged || _res.rankingConstantsChanged || _res.indexschemaChanged || _res.attributesChanged || _res.summaryChanged || _res.summarymapChanged || _res.juniperrcChanged || _res.documenttypesChanged || _res.documentTypeRepoChanged || _res.importedFieldsChanged || _res.tuneFileDocumentDBChanged || _res.schemaChanged || _res.maintenanceChanged; } bool ReconfigParams::shouldSchemaChange() const { return _res.schemaChanged; } bool ReconfigParams::shouldMatchersChange() const { return _res.rankProfilesChanged || _res.rankingConstantsChanged || shouldSchemaChange(); } bool ReconfigParams::shouldIndexManagerChange() const { return _res.indexschemaChanged; } bool ReconfigParams::shouldAttributeManagerChange() const { return _res.attributesChanged || _res.importedFieldsChanged; } bool ReconfigParams::shouldSummaryManagerChange() const { return _res.summaryChanged || _res.summarymapChanged || _res.juniperrcChanged; } bool ReconfigParams::shouldSubDbsChange() const { return shouldMatchersChange() || shouldAttributeManagerChange() || shouldSummaryManagerChange(); } bool ReconfigParams::shouldMaintenanceControllerChange() const { return configHasChanged(); } bool ReconfigParams::shouldAttributeWriterChange() const { return shouldAttributeManagerChange() || _res.documentTypeRepoChanged; } } // namespace proton <commit_msg>Also change feedview when documenttype config changes.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "reconfig_params.h" namespace proton { ReconfigParams:: ReconfigParams(const DocumentDBConfig::ComparisonResult &res) : _res(res) { } bool ReconfigParams::configHasChanged() const { return _res.rankProfilesChanged || _res.rankingConstantsChanged || _res.indexschemaChanged || _res.attributesChanged || _res.summaryChanged || _res.summarymapChanged || _res.juniperrcChanged || _res.documenttypesChanged || _res.documentTypeRepoChanged || _res.importedFieldsChanged || _res.tuneFileDocumentDBChanged || _res.schemaChanged || _res.maintenanceChanged; } bool ReconfigParams::shouldSchemaChange() const { return _res.schemaChanged; } bool ReconfigParams::shouldMatchersChange() const { return _res.rankProfilesChanged || _res.rankingConstantsChanged || shouldSchemaChange(); } bool ReconfigParams::shouldIndexManagerChange() const { return _res.indexschemaChanged; } bool ReconfigParams::shouldAttributeManagerChange() const { return _res.attributesChanged || _res.importedFieldsChanged; } bool ReconfigParams::shouldSummaryManagerChange() const { return _res.summaryChanged || _res.summarymapChanged || _res.juniperrcChanged || _res.documentTypeRepoChanged || _res.documenttypesChanged } bool ReconfigParams::shouldSubDbsChange() const { return shouldMatchersChange() || shouldAttributeManagerChange() || shouldSummaryManagerChange() || _res.documentTypeRepoChanged || _res.documenttypesChanged; } bool ReconfigParams::shouldMaintenanceControllerChange() const { return configHasChanged(); } bool ReconfigParams::shouldAttributeWriterChange() const { return shouldAttributeManagerChange() || _res.documentTypeRepoChanged; } } // namespace proton <|endoftext|>
<commit_before><commit_msg>Sketcher: Fix #3658 Levenberg-Marquardt solver precision issues<commit_after><|endoftext|>
<commit_before>#include "HttpPlugin.hh" #include "G4Application.hh" using namespace g4; namespace http { void HttpPlugin::OnRunInitialized() { _server->Start(); _action = new HttpEventAction(_server->GetState()); G4Application::GetInstance()->GetRunManager()->AddAction(_action); } HttpPlugin::HttpPlugin() : _action(0) { _server = HttpServer::GetInstance(); } HttpPlugin::~HttpPlugin() { _server->Stop(); } } MAKE_G4_PLUGIN( http::HttpPlugin) <commit_msg>Trivial change in httpPlugin<commit_after>#include "HttpPlugin.hh" #include "G4Application.hh" using namespace g4; namespace http { void HttpPlugin::OnRunInitialized() { _server->Start(); _action = new HttpEventAction(_server->GetState()); G4Application::GetInstance()->GetRunManager()->AddAction(_action); } HttpPlugin::HttpPlugin() : _action(0) { _server = HttpServer::GetInstance(); } HttpPlugin::~HttpPlugin() { _server->Stop(); // Thread joined, should be safe to delete. delete _server; } } MAKE_G4_PLUGIN( http::HttpPlugin) <|endoftext|>
<commit_before>#include <Refal2.h> namespace Refal2 { //----------------------------------------------------------------------------- // CPrintHelper void CPrintHelper::Variable( std::ostream& outputStream, const TVariableIndex variable ) const { outputStream << "V" << variable; } void CPrintHelper::Label( std::ostream& outputStream, const TLabel label ) const { outputStream << "L:"; if( PrintLabelWithModule() ) { outputStream << ( label / LabelMask ) << ":"; } outputStream << ( label % LabelMask ); } //----------------------------------------------------------------------------- // CUnit bool CUnit::IsEqualWith( const CUnit& unit ) const { if( type != unit.type ) { return false; } switch( type ) { case UT_Char: return ( c == unit.c ); break; case UT_Label: return ( label == unit.label ); break; case UT_Number: return ( number == unit.number ); break; case UT_Variable: return ( variable == unit.variable ); break; case UT_LeftParen: case UT_RightParen: case UT_LeftBracket: case UT_RightBracket: return true; default: break; } assert( false ); return false; } void CUnit::Print( std::ostream& outputStream, const CPrintHelper& printHelper ) const { switch( GetType() ) { case UT_Char: outputStream << "'" << Char() << "' "; break; case UT_Label: outputStream << "/"; printHelper.Label( outputStream, Label() ); outputStream << "/ "; break; case UT_Number: outputStream << "/" << Number() << "/ "; break; case UT_Variable: printHelper.Variable( outputStream, Variable() ); outputStream << " "; break; case UT_LeftParen: outputStream << "( "; break; case UT_RightParen: outputStream << ") "; break; case UT_LeftBracket: outputStream << "< "; break; case UT_RightBracket: outputStream << "> "; break; default: assert( false ); break; } } //----------------------------------------------------------------------------- // CUnitList void CUnitList::Print( const CUnitNode* begin, const CUnitNode* end, std::ostream& outputStream, const CPrintHelper& printHelper ) { assert( begin != nullptr ); assert( end != nullptr ); const CUnitNode* node = begin; while( node != end ) { node->Print( outputStream, printHelper ); node = node->Next(); assert( node != nullptr ); } node->Print( outputStream, printHelper ); } void CUnitList::Print( std::ostream& outputStream, const CPrintHelper& printHelper ) const { if( !IsEmpty() ) { Print( GetFirst(), GetLast(), outputStream, printHelper ); } } void CUnitList::HandyPrint( std::ostream& outputStream, const CPrintHelper& printHelper ) const { bool lastWasChar = false; for( const CUnitNode* node = GetFirst(); node != 0; node = node->Next() ) { if( node->GetType() == UT_Char ) { if( !lastWasChar ) { outputStream << "'"; lastWasChar = true; } } else { if( lastWasChar ) { outputStream << "'"; lastWasChar = false; } } switch( node->GetType() ) { case UT_Char: outputStream << node->Char(); break; case UT_Label: outputStream << "/"; printHelper.Label( outputStream, node->Label() ); outputStream << "/"; break; case UT_Number: outputStream << "/" << node->Number() << "/"; break; case UT_LeftParen: outputStream << "("; break; case UT_RightParen: outputStream << ")"; break; case UT_LeftBracket: outputStream << "<"; break; case UT_RightBracket: outputStream << ">"; break; case UT_Variable: default: assert( false ); break; } } if( lastWasChar ) { outputStream << "'"; } outputStream << std::endl; } void CUnitList::StrangePrint( std::ostream& outputStream, const CPrintHelper& printHelper ) const { for( const CUnitNode* node = GetFirst(); node != 0; node = node->Next() ) { switch( node->GetType() ) { case UT_Char: outputStream<< node->Char(); break; case UT_Label: outputStream << "'"; printHelper.Label( outputStream, node->Label() ); outputStream << "'"; break; case UT_Number: std::cout << "'" << node->Number() << "'"; break; case UT_LeftParen: std::cout << "("; break; case UT_RightParen: std::cout << ")"; break; case UT_Variable: case UT_LeftBracket: case UT_RightBracket: default: assert( false ); break; } } std::cout << std::endl; } void CUnitList::Duplicate( const CUnitNode* fromNode, const CUnitNode* toNode, CUnitNode*& fromNodeCopy, CUnitNode*& toNodeCopy ) { CNodeList::Duplicate( fromNode, toNode, fromNodeCopy, toNodeCopy ); CUnitNode* source = const_cast<CUnitNode*>( fromNode ); CUnitNode* dest = fromNodeCopy; while( true ) { assert( !source->IsLeftBracket() && !source->IsRightBracket() ); if( source->IsLeftParen() || source->IsRightParen() ) { assert( source->GetType() == dest->GetType() ); source->PairedParen() = dest; } if( source == toNode ) { assert( dest == toNodeCopy ); break; } source = source->Next(); dest = dest->Next(); } source = const_cast<CUnitNode*>( fromNode ); while( true ) { if( source->IsLeftParen() ) { CUnitNode* destLeftParen = source->PairedParen(); assert( destLeftParen->IsLeftParen() ); CUnitNode* sourceRightParen = destLeftParen->PairedParen(); assert( sourceRightParen->IsRightParen() ); CUnitNode* destRightParen = sourceRightParen->PairedParen(); assert( destRightParen->IsRightParen() ); // correct source list source->PairedParen() = sourceRightParen; sourceRightParen->PairedParen() = source; // correct duplicated list destLeftParen->PairedParen() = destRightParen; destRightParen->PairedParen() = destLeftParen; } if( source == toNode ) { break; } source = source->Next(); } } //----------------------------------------------------------------------------- } // end of namespace Refal2 <commit_msg>Duplicate more efficient<commit_after>#include <Refal2.h> namespace Refal2 { //----------------------------------------------------------------------------- // CPrintHelper void CPrintHelper::Variable( std::ostream& outputStream, const TVariableIndex variable ) const { outputStream << "V" << variable; } void CPrintHelper::Label( std::ostream& outputStream, const TLabel label ) const { outputStream << "L:"; if( PrintLabelWithModule() ) { outputStream << ( label / LabelMask ) << ":"; } outputStream << ( label % LabelMask ); } //----------------------------------------------------------------------------- // CUnit bool CUnit::IsEqualWith( const CUnit& unit ) const { if( type != unit.type ) { return false; } switch( type ) { case UT_Char: return ( c == unit.c ); break; case UT_Label: return ( label == unit.label ); break; case UT_Number: return ( number == unit.number ); break; case UT_Variable: return ( variable == unit.variable ); break; case UT_LeftParen: case UT_RightParen: case UT_LeftBracket: case UT_RightBracket: return true; default: break; } assert( false ); return false; } void CUnit::Print( std::ostream& outputStream, const CPrintHelper& printHelper ) const { switch( GetType() ) { case UT_Char: outputStream << "'" << Char() << "' "; break; case UT_Label: outputStream << "/"; printHelper.Label( outputStream, Label() ); outputStream << "/ "; break; case UT_Number: outputStream << "/" << Number() << "/ "; break; case UT_Variable: printHelper.Variable( outputStream, Variable() ); outputStream << " "; break; case UT_LeftParen: outputStream << "( "; break; case UT_RightParen: outputStream << ") "; break; case UT_LeftBracket: outputStream << "< "; break; case UT_RightBracket: outputStream << "> "; break; default: assert( false ); break; } } //----------------------------------------------------------------------------- // CUnitList void CUnitList::Print( const CUnitNode* begin, const CUnitNode* end, std::ostream& outputStream, const CPrintHelper& printHelper ) { assert( begin != nullptr ); assert( end != nullptr ); const CUnitNode* node = begin; while( node != end ) { node->Print( outputStream, printHelper ); node = node->Next(); assert( node != nullptr ); } node->Print( outputStream, printHelper ); } void CUnitList::Print( std::ostream& outputStream, const CPrintHelper& printHelper ) const { if( !IsEmpty() ) { Print( GetFirst(), GetLast(), outputStream, printHelper ); } } void CUnitList::HandyPrint( std::ostream& outputStream, const CPrintHelper& printHelper ) const { bool lastWasChar = false; for( const CUnitNode* node = GetFirst(); node != 0; node = node->Next() ) { if( node->GetType() == UT_Char ) { if( !lastWasChar ) { outputStream << "'"; lastWasChar = true; } } else { if( lastWasChar ) { outputStream << "'"; lastWasChar = false; } } switch( node->GetType() ) { case UT_Char: outputStream << node->Char(); break; case UT_Label: outputStream << "/"; printHelper.Label( outputStream, node->Label() ); outputStream << "/"; break; case UT_Number: outputStream << "/" << node->Number() << "/"; break; case UT_LeftParen: outputStream << "("; break; case UT_RightParen: outputStream << ")"; break; case UT_LeftBracket: outputStream << "<"; break; case UT_RightBracket: outputStream << ">"; break; case UT_Variable: default: assert( false ); break; } } if( lastWasChar ) { outputStream << "'"; } outputStream << std::endl; } void CUnitList::StrangePrint( std::ostream& outputStream, const CPrintHelper& printHelper ) const { for( const CUnitNode* node = GetFirst(); node != 0; node = node->Next() ) { switch( node->GetType() ) { case UT_Char: outputStream<< node->Char(); break; case UT_Label: outputStream << "'"; printHelper.Label( outputStream, node->Label() ); outputStream << "'"; break; case UT_Number: std::cout << "'" << node->Number() << "'"; break; case UT_LeftParen: std::cout << "("; break; case UT_RightParen: std::cout << ")"; break; case UT_Variable: case UT_LeftBracket: case UT_RightBracket: default: assert( false ); break; } } std::cout << std::endl; } void CUnitList::Duplicate( const CUnitNode* fromNode, const CUnitNode* toNode, CUnitNode*& fromNodeCopy, CUnitNode*& toNodeCopy ) { CNodeList::Duplicate( fromNode, toNode, fromNodeCopy, toNodeCopy ); CUnitNode* node = fromNodeCopy; assert( !node->IsLeftBracket() && !node->IsRightBracket() ); CUnitNode* lastAddedLeftParen = node->IsLeftParen() ? node : nullptr; do { node = node->Next(); assert( !node->IsLeftBracket() && !node->IsRightBracket() ); if( node->IsLeftParen() ) { node->PairedParen() = lastAddedLeftParen; lastAddedLeftParen = node; } else if( node->IsRightParen() ) { CUnitNode* leftParen = lastAddedLeftParen; assert( leftParen != nullptr ); lastAddedLeftParen = lastAddedLeftParen->PairedParen(); node->PairedParen() = leftParen; leftParen->PairedParen() = node; } } while( node != toNodeCopy ); assert( lastAddedLeftParen == nullptr ); } //----------------------------------------------------------------------------- } // end of namespace Refal2 <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #if defined __linux__ || defined BSD #include <sys/ioctl.h> #include <netinet/in.h> #include <net/if.h> #elif defined WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #include <iphlpapi.h> #endif #include "libtorrent/enum_net.hpp" namespace libtorrent { namespace { address sockaddr_to_address(sockaddr const* sin) { if (sin->sa_family == AF_INET) { typedef asio::ip::address_v4::bytes_type bytes_t; bytes_t b; memcpy(&b[0], &((sockaddr_in const*)sin)->sin_addr, b.size()); return address_v4(b); } else if (sin->sa_family == AF_INET6) { typedef asio::ip::address_v6::bytes_type bytes_t; bytes_t b; memcpy(&b[0], &((sockaddr_in6 const*)sin)->sin6_addr, b.size()); return address_v6(b); } return address(); } } bool in_subnet(address const& addr, ip_interface const& iface) { if (addr.is_v4() != iface.interface_address.is_v4()) return false; // since netmasks seems unreliable for IPv6 interfaces // (MacOS X returns AF_INET addresses as bitmasks) assume // that any IPv6 address belongs to the subnet of any // interface with an IPv6 address if (addr.is_v6()) return true; return (addr.to_v4().to_ulong() & iface.netmask.to_v4().to_ulong()) == (iface.interface_address.to_v4().to_ulong() & iface.netmask.to_v4().to_ulong()); } bool in_local_network(asio::io_service& ios, address const& addr, asio::error_code& ec) { std::vector<ip_interface> const& net = enum_net_interfaces(ios, ec); if (ec) return false; for (std::vector<ip_interface>::const_iterator i = net.begin() , end(net.end()); i != end; ++i) { if (in_subnet(addr, *i)) return true; } return false; } std::vector<ip_interface> enum_net_interfaces(asio::io_service& ios, asio::error_code& ec) { std::vector<ip_interface> ret; #if defined __linux__ || defined BSD int s = socket(AF_INET, SOCK_DGRAM, 0); if (s < 0) { ec = asio::error::fault; return ret; } ifconf ifc; char buf[1024]; ifc.ifc_len = sizeof(buf); ifc.ifc_buf = buf; if (ioctl(s, SIOCGIFCONF, &ifc) < 0) { close(s); ec = asio::error_code(errno, asio::error::system_category); return ret; } char *ifr = (char*)ifc.ifc_req; int remaining = ifc.ifc_len; while (remaining) { ifreq const& item = *reinterpret_cast<ifreq*>(ifr); if (item.ifr_addr.sa_family == AF_INET || item.ifr_addr.sa_family == AF_INET6) { ip_interface iface; iface.interface_address = sockaddr_to_address(&item.ifr_addr); ifreq netmask = item; if (ioctl(s, SIOCGIFNETMASK, &netmask) < 0) { close(s); ec = asio::error_code(errno, asio::error::system_category); return ret; } iface.netmask = sockaddr_to_address(&netmask.ifr_addr); ret.push_back(iface); } #if defined BSD int current_size = item.ifr_addr.sa_len + IFNAMSIZ; #elif defined __linux__ int current_size = sizeof(ifreq); #endif ifr += current_size; remaining -= current_size; } close(s); #elif defined WIN32 SOCKET s = socket(AF_INET, SOCK_DGRAM, 0); if (s == SOCKET_ERROR) { ec = asio::error::fault; return ret; } INTERFACE_INFO buffer[30]; DWORD size; if (WSAIoctl(s, SIO_GET_INTERFACE_LIST, 0, 0, buffer, sizeof(buffer), &size, 0, 0) != 0) { closesocket(s); ec = asio::error::fault; return ret; } closesocket(s); int n = size / sizeof(INTERFACE_INFO); ip_interface iface; for (int i = 0; i < n; ++i) { iface.interface_address = sockaddr_to_address(&buffer[i].iiAddress.Address); iface.netmask = sockaddr_to_address(&buffer[i].iiNetmask.Address); if (iface.interface_address == address_v4::any()) continue; ret.push_back(iface); } #else #warning THIS OS IS NOT RECOGNIZED, enum_net_interfaces WILL PROBABLY NOT WORK // make a best guess of the interface we're using and its IP udp::resolver r(ios); udp::resolver::iterator i = r.resolve(udp::resolver::query(asio::ip::host_name(), "0")); ip_interface iface; for (;i != udp::resolver_iterator(); ++i) { iface.interface_address = i->endpoint().address(); if (iface.interface_address.is_v4()) iface.netmask = iface.interface_address.to_v4().netmask(); ret.push_back(iface); } #endif return ret; } address router_for_interface(address const interface, asio::error_code& ec) { #ifdef WIN32 // Load Iphlpapi library HMODULE iphlp = LoadLibraryA("Iphlpapi.dll"); if (!iphlp) { ec = asio::error::fault; return address_v4::any(); } // Get GetAdaptersInfo() pointer typedef DWORD (WINAPI *GetAdaptersInfo_t)(PIP_ADAPTER_INFO, PULONG); GetAdaptersInfo_t GetAdaptersInfo = (GetAdaptersInfo_t)GetProcAddress(iphlp, "GetAdaptersInfo"); if (!GetAdaptersInfo) { FreeLibrary(iphlp); ec = asio::error::fault; return address_v4::any(); } PIP_ADAPTER_INFO adapter_info = 0; ULONG out_buf_size = 0; if (GetAdaptersInfo(adapter_info, &out_buf_size) != ERROR_BUFFER_OVERFLOW) { FreeLibrary(iphlp); ec = asio::error::fault; return address_v4::any(); } adapter_info = (IP_ADAPTER_INFO*)malloc(out_buf_size); if (!adapter_info) { FreeLibrary(iphlp); ec = asio::error::fault; return address_v4::any(); } address ret; if (GetAdaptersInfo(adapter_info, &out_buf_size) == NO_ERROR) { PIP_ADAPTER_INFO adapter = adapter_info; while (adapter != 0) { if (interface == address::from_string(adapter->IpAddressList.IpAddress.String, ec)) { ret = address::from_string(adapter->GatewayList.IpAddress.String, ec); break; } adapter = adapter->Next; } } // Free memory free(adapter_info); FreeLibrary(iphlp); return ret; #else // TODO: temporary implementation if (!interface.is_v4()) { ec = asio::error::fault; return address_v4::any(); } return address_v4((interface.to_v4().to_ulong() & 0xffffff00) | 1); #endif } } <commit_msg>fixes to make enum_net.cpp actually work<commit_after>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #if defined __linux__ || defined BSD #include <sys/ioctl.h> #include <netinet/in.h> #include <net/if.h> #elif defined WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #include <iphlpapi.h> #endif #include "libtorrent/enum_net.hpp" #include <asio/ip/host_name.hpp> namespace libtorrent { namespace { address sockaddr_to_address(sockaddr const* sin) { if (sin->sa_family == AF_INET) { typedef asio::ip::address_v4::bytes_type bytes_t; bytes_t b; memcpy(&b[0], &((sockaddr_in const*)sin)->sin_addr, b.size()); return address_v4(b); } else if (sin->sa_family == AF_INET6) { typedef asio::ip::address_v6::bytes_type bytes_t; bytes_t b; memcpy(&b[0], &((sockaddr_in6 const*)sin)->sin6_addr, b.size()); return address_v6(b); } return address(); } } bool in_subnet(address const& addr, ip_interface const& iface) { if (addr.is_v4() != iface.interface_address.is_v4()) return false; // since netmasks seems unreliable for IPv6 interfaces // (MacOS X returns AF_INET addresses as bitmasks) assume // that any IPv6 address belongs to the subnet of any // interface with an IPv6 address if (addr.is_v6()) return true; return (addr.to_v4().to_ulong() & iface.netmask.to_v4().to_ulong()) == (iface.interface_address.to_v4().to_ulong() & iface.netmask.to_v4().to_ulong()); } bool in_local_network(asio::io_service& ios, address const& addr, asio::error_code& ec) { std::vector<ip_interface> const& net = enum_net_interfaces(ios, ec); if (ec) return false; for (std::vector<ip_interface>::const_iterator i = net.begin() , end(net.end()); i != end; ++i) { if (in_subnet(addr, *i)) return true; } return false; } std::vector<ip_interface> enum_net_interfaces(asio::io_service& ios, asio::error_code& ec) { std::vector<ip_interface> ret; // covers linux, MacOS X and BSD distributions #if defined __linux__ || (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ int s = socket(AF_INET, SOCK_DGRAM, 0); if (s < 0) { ec = asio::error::fault; return ret; } ifconf ifc; char buf[1024]; ifc.ifc_len = sizeof(buf); ifc.ifc_buf = buf; if (ioctl(s, SIOCGIFCONF, &ifc) < 0) { close(s); ec = asio::error_code(errno, asio::error::system_category); return ret; } char *ifr = (char*)ifc.ifc_req; int remaining = ifc.ifc_len; while (remaining) { ifreq const& item = *reinterpret_cast<ifreq*>(ifr); if (item.ifr_addr.sa_family == AF_INET || item.ifr_addr.sa_family == AF_INET6) { ip_interface iface; iface.interface_address = sockaddr_to_address(&item.ifr_addr); ifreq netmask = item; if (ioctl(s, SIOCGIFNETMASK, &netmask) < 0) { if (iface.interface_address.is_v6()) { // this is expected to fail (at least on MacOS X) iface.netmask = address_v6::any(); } else { close(s); ec = asio::error_code(errno, asio::error::system_category); return ret; } } else { iface.netmask = sockaddr_to_address(&netmask.ifr_addr); } ret.push_back(iface); } #if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ int current_size = item.ifr_addr.sa_len + IFNAMSIZ; #elif defined __linux__ int current_size = sizeof(ifreq); #endif ifr += current_size; remaining -= current_size; } close(s); #elif defined WIN32 SOCKET s = socket(AF_INET, SOCK_DGRAM, 0); if (s == SOCKET_ERROR) { ec = asio::error_code(WSAGetLastError(), asio::error::system_category); return ret; } INTERFACE_INFO buffer[30]; DWORD size; if (WSAIoctl(s, SIO_GET_INTERFACE_LIST, 0, 0, buffer, sizeof(buffer), &size, 0, 0) != 0) { ec = asio::error_code(WSAGetLastError(), asio::error::system_category); closesocket(s); return ret; } closesocket(s); int n = size / sizeof(INTERFACE_INFO); ip_interface iface; for (int i = 0; i < n; ++i) { iface.interface_address = sockaddr_to_address(&buffer[i].iiAddress.Address); iface.netmask = sockaddr_to_address(&buffer[i].iiNetmask.Address); if (iface.interface_address == address_v4::any()) continue; ret.push_back(iface); } #else #warning THIS OS IS NOT RECOGNIZED, enum_net_interfaces WILL PROBABLY NOT WORK // make a best guess of the interface we're using and its IP udp::resolver r(ios); udp::resolver::iterator i = r.resolve(udp::resolver::query(asio::ip::host_name(ec), "0"), ec); if (ec) return ret; ip_interface iface; for (;i != udp::resolver_iterator(); ++i) { iface.interface_address = i->endpoint().address(); if (iface.interface_address.is_v4()) iface.netmask = address_v4::netmask(iface.interface_address.to_v4()); ret.push_back(iface); } #endif return ret; } address router_for_interface(address const interface, asio::error_code& ec) { #ifdef WIN32 // Load Iphlpapi library HMODULE iphlp = LoadLibraryA("Iphlpapi.dll"); if (!iphlp) { ec = asio::error::fault; return address_v4::any(); } // Get GetAdaptersInfo() pointer typedef DWORD (WINAPI *GetAdaptersInfo_t)(PIP_ADAPTER_INFO, PULONG); GetAdaptersInfo_t GetAdaptersInfo = (GetAdaptersInfo_t)GetProcAddress(iphlp, "GetAdaptersInfo"); if (!GetAdaptersInfo) { FreeLibrary(iphlp); ec = asio::error::fault; return address_v4::any(); } PIP_ADAPTER_INFO adapter_info = 0; ULONG out_buf_size = 0; if (GetAdaptersInfo(adapter_info, &out_buf_size) != ERROR_BUFFER_OVERFLOW) { FreeLibrary(iphlp); ec = asio::error::fault; return address_v4::any(); } adapter_info = (IP_ADAPTER_INFO*)malloc(out_buf_size); if (!adapter_info) { FreeLibrary(iphlp); ec = asio::error::fault; return address_v4::any(); } address ret; if (GetAdaptersInfo(adapter_info, &out_buf_size) == NO_ERROR) { PIP_ADAPTER_INFO adapter = adapter_info; while (adapter != 0) { if (interface == address::from_string(adapter->IpAddressList.IpAddress.String, ec)) { ret = address::from_string(adapter->GatewayList.IpAddress.String, ec); break; } adapter = adapter->Next; } } // Free memory free(adapter_info); FreeLibrary(iphlp); return ret; #else // TODO: temporary implementation if (!interface.is_v4()) { ec = asio::error::fault; return address_v4::any(); } return address_v4((interface.to_v4().to_ulong() & 0xffffff00) | 1); #endif } } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Native Client Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // C headers #include <cassert> #include <cstdio> // C++ headers #include <sstream> #include <string> // NaCl #include "ppapi/cpp/input_event.h" #include "ppapi/cpp/instance.h" #include "ppapi/cpp/module.h" #include "ppapi/cpp/point.h" #include "ppapi/cpp/var.h" namespace { const char* const kDidChangeView = "DidChangeView"; const char* const kHandleInputEvent = "DidHandleInputEvent"; const char* const kDidChangeFocus = "DidChangeFocus"; const char* const kHaveFocus = "HaveFocus"; const char* const kDontHaveFocus = "DontHaveFocus"; // Convert a given modifier to a descriptive string. Note that the actual // declared type of modifier in each of the event classes is uint32_t, but it is // expected to be interpreted as a bitfield of 'or'ed PP_InputEvent_Modifier // values. std::string ModifierToString(uint32_t modifier) { std::string s; if (modifier & PP_INPUTEVENT_MODIFIER_SHIFTKEY) { s += "shift "; } if (modifier & PP_INPUTEVENT_MODIFIER_CONTROLKEY) { s += "ctrl "; } if (modifier & PP_INPUTEVENT_MODIFIER_ALTKEY) { s += "alt "; } if (modifier & PP_INPUTEVENT_MODIFIER_METAKEY) { s += "meta "; } if (modifier & PP_INPUTEVENT_MODIFIER_ISKEYPAD) { s += "keypad "; } if (modifier & PP_INPUTEVENT_MODIFIER_ISAUTOREPEAT) { s += "autorepeat "; } if (modifier & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN) { s += "left-button-down "; } if (modifier & PP_INPUTEVENT_MODIFIER_MIDDLEBUTTONDOWN) { s += "middle-button-down "; } if (modifier & PP_INPUTEVENT_MODIFIER_RIGHTBUTTONDOWN) { s += "right-button-down "; } if (modifier & PP_INPUTEVENT_MODIFIER_CAPSLOCKKEY) { s += "caps-lock "; } if (modifier & PP_INPUTEVENT_MODIFIER_NUMLOCKKEY) { s += "num-lock "; } return s; } std::string MouseButtonToString(PP_InputEvent_MouseButton button) { switch (button) { case PP_INPUTEVENT_MOUSEBUTTON_NONE: return "None"; case PP_INPUTEVENT_MOUSEBUTTON_LEFT: return "Left"; case PP_INPUTEVENT_MOUSEBUTTON_MIDDLE: return "Middle"; case PP_INPUTEVENT_MOUSEBUTTON_RIGHT: return "Right"; default: std::ostringstream stream; stream << "Unrecognized (" << static_cast<int32_t>(button) << ")"; return stream.str(); } } } // namespace class EventInstance : public pp::Instance { public: explicit EventInstance(PP_Instance instance) : pp::Instance(instance) { RequestInputEvents(PP_INPUTEVENT_CLASS_MOUSE | PP_INPUTEVENT_CLASS_WHEEL); RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD); } virtual ~EventInstance() {} /// Clicking outside of the instance's bounding box /// will create a DidChangeFocus event (the NaCl instance is /// out of focus). Clicking back inside the instance's /// bounding box will create another DidChangeFocus event /// (the NaCl instance is back in focus). The default is /// that the instance is out of focus. void DidChangeFocus(bool focus) { PostMessage(pp::Var(kDidChangeFocus)); if (focus == true) { PostMessage(pp::Var(kHaveFocus)); } else { PostMessage(pp::Var(kDontHaveFocus)); } } /// Scrolling the mouse wheel causes a DidChangeView event. void DidChangeView(const pp::Rect& position, const pp::Rect& clip) { PostMessage(pp::Var(kDidChangeView)); } void GotKeyEvent(const pp::KeyboardInputEvent& key_event, const std::string& kind) { std::ostringstream stream; stream << pp_instance() << ":" << " Key event:" << kind << " modifier:" << ModifierToString(key_event.GetModifiers()) << " key_code:" << key_event.GetKeyCode() << " time:" << key_event.GetTimeStamp() << " text:" << key_event.GetCharacterText().DebugString() << "\n"; PostMessage(stream.str()); } void GotMouseEvent(const pp::MouseInputEvent& mouse_event, const std::string& kind) { std::ostringstream stream; stream << pp_instance() << ":" << " Mouse event:" << kind << " modifier:" << ModifierToString(mouse_event.GetModifiers()) << " button:" << MouseButtonToString(mouse_event.GetButton()) << " x:" << mouse_event.GetPosition().x() << " y:" << mouse_event.GetPosition().y() << " click_count:" << mouse_event.GetClickCount() << " time:" << mouse_event.GetTimeStamp() << "\n"; PostMessage(stream.str()); } void GotWheelEvent(const pp::WheelInputEvent& wheel_event) { std::ostringstream stream; stream << pp_instance() << ": Wheel event." << " modifier:" << ModifierToString(wheel_event.GetModifiers()) << " deltax:" << wheel_event.GetDelta().x() << " deltay:" << wheel_event.GetDelta().y() << " wheel_ticks_x:" << wheel_event.GetTicks().x() << " wheel_ticks_y:"<< wheel_event.GetTicks().y() << " scroll_by_page: " << (wheel_event.GetScrollByPage() ? "true" : "false") << "\n"; PostMessage(stream.str()); } // Handle an incoming input event by switching on type and dispatching // to the appropriate subtype handler. // // HandleInputEvent operates on the main Pepper thread. In large // real-world applications, you'll want to create a separate thread // that puts events in a queue and handles them independant of the main // thread so as not to slow down the browser. There is an additional // version of this example in the examples directory that demonstrates // this best practice. virtual bool HandleInputEvent(const pp::InputEvent& event) { PostMessage(pp::Var(kHandleInputEvent)); switch (event.GetType()) { case PP_INPUTEVENT_TYPE_UNDEFINED: break; case PP_INPUTEVENT_TYPE_MOUSEDOWN: GotMouseEvent(pp::MouseInputEvent(event), "Down"); break; case PP_INPUTEVENT_TYPE_MOUSEUP: GotMouseEvent(pp::MouseInputEvent(event), "Up"); break; case PP_INPUTEVENT_TYPE_MOUSEMOVE: GotMouseEvent(pp::MouseInputEvent(event), "Move"); break; case PP_INPUTEVENT_TYPE_MOUSEENTER: GotMouseEvent(pp::MouseInputEvent(event), "Enter"); break; case PP_INPUTEVENT_TYPE_MOUSELEAVE: GotMouseEvent(pp::MouseInputEvent(event), "Leave"); break; case PP_INPUTEVENT_TYPE_WHEEL: GotWheelEvent(pp::WheelInputEvent(event)); break; case PP_INPUTEVENT_TYPE_RAWKEYDOWN: GotKeyEvent(pp::KeyboardInputEvent(event), "RawKeyDown"); break; case PP_INPUTEVENT_TYPE_KEYDOWN: GotKeyEvent(pp::KeyboardInputEvent(event), "Down"); break; case PP_INPUTEVENT_TYPE_KEYUP: GotKeyEvent(pp::KeyboardInputEvent(event), "Up"); break; case PP_INPUTEVENT_TYPE_CHAR: GotKeyEvent(pp::KeyboardInputEvent(event), "Character"); break; case PP_INPUTEVENT_TYPE_CONTEXTMENU: GotKeyEvent(pp::KeyboardInputEvent(event), "Context"); break; default: assert(false); return false; } return true; } }; // The EventModule provides an implementation of pp::Module that creates // EventInstance objects when invoked. This is part of the glue code that makes // our example accessible to ppapi. class EventModule : public pp::Module { public: EventModule() : pp::Module() {} virtual ~EventModule() {} virtual pp::Instance* CreateInstance(PP_Instance instance) { return new EventInstance(instance); } }; // Implement the required pp::CreateModule function that creates our specific // kind of Module (in this case, EventModule). This is part of the glue code // that makes our example accessible to ppapi. namespace pp { Module* CreateModule() { return new EventModule(); } } <commit_msg>I noticed this when doing the recent multi-threaded input_events -- these newer event types (if not handled) cause compile-time warnings.<commit_after>// Copyright (c) 2011 The Native Client Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // C headers #include <cassert> #include <cstdio> // C++ headers #include <sstream> #include <string> // NaCl #include "ppapi/cpp/input_event.h" #include "ppapi/cpp/instance.h" #include "ppapi/cpp/module.h" #include "ppapi/cpp/point.h" #include "ppapi/cpp/var.h" namespace { const char* const kDidChangeView = "DidChangeView"; const char* const kHandleInputEvent = "DidHandleInputEvent"; const char* const kDidChangeFocus = "DidChangeFocus"; const char* const kHaveFocus = "HaveFocus"; const char* const kDontHaveFocus = "DontHaveFocus"; // Convert a given modifier to a descriptive string. Note that the actual // declared type of modifier in each of the event classes is uint32_t, but it is // expected to be interpreted as a bitfield of 'or'ed PP_InputEvent_Modifier // values. std::string ModifierToString(uint32_t modifier) { std::string s; if (modifier & PP_INPUTEVENT_MODIFIER_SHIFTKEY) { s += "shift "; } if (modifier & PP_INPUTEVENT_MODIFIER_CONTROLKEY) { s += "ctrl "; } if (modifier & PP_INPUTEVENT_MODIFIER_ALTKEY) { s += "alt "; } if (modifier & PP_INPUTEVENT_MODIFIER_METAKEY) { s += "meta "; } if (modifier & PP_INPUTEVENT_MODIFIER_ISKEYPAD) { s += "keypad "; } if (modifier & PP_INPUTEVENT_MODIFIER_ISAUTOREPEAT) { s += "autorepeat "; } if (modifier & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN) { s += "left-button-down "; } if (modifier & PP_INPUTEVENT_MODIFIER_MIDDLEBUTTONDOWN) { s += "middle-button-down "; } if (modifier & PP_INPUTEVENT_MODIFIER_RIGHTBUTTONDOWN) { s += "right-button-down "; } if (modifier & PP_INPUTEVENT_MODIFIER_CAPSLOCKKEY) { s += "caps-lock "; } if (modifier & PP_INPUTEVENT_MODIFIER_NUMLOCKKEY) { s += "num-lock "; } return s; } std::string MouseButtonToString(PP_InputEvent_MouseButton button) { switch (button) { case PP_INPUTEVENT_MOUSEBUTTON_NONE: return "None"; case PP_INPUTEVENT_MOUSEBUTTON_LEFT: return "Left"; case PP_INPUTEVENT_MOUSEBUTTON_MIDDLE: return "Middle"; case PP_INPUTEVENT_MOUSEBUTTON_RIGHT: return "Right"; default: std::ostringstream stream; stream << "Unrecognized (" << static_cast<int32_t>(button) << ")"; return stream.str(); } } } // namespace class EventInstance : public pp::Instance { public: explicit EventInstance(PP_Instance instance) : pp::Instance(instance) { RequestInputEvents(PP_INPUTEVENT_CLASS_MOUSE | PP_INPUTEVENT_CLASS_WHEEL); RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD); } virtual ~EventInstance() {} /// Clicking outside of the instance's bounding box /// will create a DidChangeFocus event (the NaCl instance is /// out of focus). Clicking back inside the instance's /// bounding box will create another DidChangeFocus event /// (the NaCl instance is back in focus). The default is /// that the instance is out of focus. void DidChangeFocus(bool focus) { PostMessage(pp::Var(kDidChangeFocus)); if (focus == true) { PostMessage(pp::Var(kHaveFocus)); } else { PostMessage(pp::Var(kDontHaveFocus)); } } /// Scrolling the mouse wheel causes a DidChangeView event. void DidChangeView(const pp::Rect& position, const pp::Rect& clip) { PostMessage(pp::Var(kDidChangeView)); } void GotKeyEvent(const pp::KeyboardInputEvent& key_event, const std::string& kind) { std::ostringstream stream; stream << pp_instance() << ":" << " Key event:" << kind << " modifier:" << ModifierToString(key_event.GetModifiers()) << " key_code:" << key_event.GetKeyCode() << " time:" << key_event.GetTimeStamp() << " text:" << key_event.GetCharacterText().DebugString() << "\n"; PostMessage(stream.str()); } void GotMouseEvent(const pp::MouseInputEvent& mouse_event, const std::string& kind) { std::ostringstream stream; stream << pp_instance() << ":" << " Mouse event:" << kind << " modifier:" << ModifierToString(mouse_event.GetModifiers()) << " button:" << MouseButtonToString(mouse_event.GetButton()) << " x:" << mouse_event.GetPosition().x() << " y:" << mouse_event.GetPosition().y() << " click_count:" << mouse_event.GetClickCount() << " time:" << mouse_event.GetTimeStamp() << "\n"; PostMessage(stream.str()); } void GotWheelEvent(const pp::WheelInputEvent& wheel_event) { std::ostringstream stream; stream << pp_instance() << ": Wheel event." << " modifier:" << ModifierToString(wheel_event.GetModifiers()) << " deltax:" << wheel_event.GetDelta().x() << " deltay:" << wheel_event.GetDelta().y() << " wheel_ticks_x:" << wheel_event.GetTicks().x() << " wheel_ticks_y:"<< wheel_event.GetTicks().y() << " scroll_by_page: " << (wheel_event.GetScrollByPage() ? "true" : "false") << "\n"; PostMessage(stream.str()); } // Handle an incoming input event by switching on type and dispatching // to the appropriate subtype handler. // // HandleInputEvent operates on the main Pepper thread. In large // real-world applications, you'll want to create a separate thread // that puts events in a queue and handles them independant of the main // thread so as not to slow down the browser. There is an additional // version of this example in the examples directory that demonstrates // this best practice. virtual bool HandleInputEvent(const pp::InputEvent& event) { PostMessage(pp::Var(kHandleInputEvent)); switch (event.GetType()) { case PP_INPUTEVENT_TYPE_UNDEFINED: break; case PP_INPUTEVENT_TYPE_MOUSEDOWN: GotMouseEvent(pp::MouseInputEvent(event), "Down"); break; case PP_INPUTEVENT_TYPE_MOUSEUP: GotMouseEvent(pp::MouseInputEvent(event), "Up"); break; case PP_INPUTEVENT_TYPE_MOUSEMOVE: GotMouseEvent(pp::MouseInputEvent(event), "Move"); break; case PP_INPUTEVENT_TYPE_MOUSEENTER: GotMouseEvent(pp::MouseInputEvent(event), "Enter"); break; case PP_INPUTEVENT_TYPE_MOUSELEAVE: GotMouseEvent(pp::MouseInputEvent(event), "Leave"); break; case PP_INPUTEVENT_TYPE_WHEEL: GotWheelEvent(pp::WheelInputEvent(event)); break; case PP_INPUTEVENT_TYPE_RAWKEYDOWN: GotKeyEvent(pp::KeyboardInputEvent(event), "RawKeyDown"); break; case PP_INPUTEVENT_TYPE_KEYDOWN: GotKeyEvent(pp::KeyboardInputEvent(event), "Down"); break; case PP_INPUTEVENT_TYPE_KEYUP: GotKeyEvent(pp::KeyboardInputEvent(event), "Up"); break; case PP_INPUTEVENT_TYPE_CHAR: GotKeyEvent(pp::KeyboardInputEvent(event), "Character"); break; case PP_INPUTEVENT_TYPE_CONTEXTMENU: GotKeyEvent(pp::KeyboardInputEvent(event), "Context"); break; // Note that if we receive an IME event we just send a message back // to the browser to indicate we have received it. case PP_INPUTEVENT_TYPE_IME_COMPOSITION_START: PostMessage(pp::Var("PP_INPUTEVENT_TYPE_IME_COMPOSITION_START")); break; case PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE: PostMessage(pp::Var("PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE")); break; case PP_INPUTEVENT_TYPE_IME_COMPOSITION_END: PostMessage(pp::Var("PP_INPUTEVENT_TYPE_IME_COMPOSITION_END")); break; case PP_INPUTEVENT_TYPE_IME_TEXT: PostMessage(pp::Var("PP_INPUTEVENT_TYPE_IME_COMPOSITION_TEXT")); break; default: assert(false); return false; } return true; } }; // The EventModule provides an implementation of pp::Module that creates // EventInstance objects when invoked. This is part of the glue code that makes // our example accessible to ppapi. class EventModule : public pp::Module { public: EventModule() : pp::Module() {} virtual ~EventModule() {} virtual pp::Instance* CreateInstance(PP_Instance instance) { return new EventInstance(instance); } }; // Implement the required pp::CreateModule function that creates our specific // kind of Module (in this case, EventModule). This is part of the glue code // that makes our example accessible to ppapi. namespace pp { Module* CreateModule() { return new EventModule(); } } <|endoftext|>
<commit_before>// // base.hpp // ~~~~~~~~ // // Copyright (c) 2014 Rick Yang (rick68 at gmail dot com) // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // #ifndef EIGENJS_BASIC_HPP #define EIGENJS_BASIC_HPP #include <v8.h> #include <node.h> #include <nan.h> #include <boost/mpl/and.hpp> #include <boost/mpl/or.hpp> #include <eigen3/Eigen/Dense> #include <complex> #include <memory> #include <type_traits> #include "Complex_fwd.hpp" #include "Matrix_fwd.hpp" #include "CMatrix_fwd.hpp" #include "Vector_fwd.hpp" #include "CVector_fwd.hpp" #include "RowVector_fwd.hpp" #include "CRowVector_fwd.hpp" #include "MatrixBlock_fwd.hpp" #include "CMatrixBlock_fwd.hpp" #include "detail/unwrap_eigen_block.hpp" #include "detail/is_eigen_block.hpp" #include "detail/is_eigen_matrix.hpp" namespace EigenJS { namespace detail { template <typename ScalarType> struct std_complex_dummy_ptr { typedef ScalarType scalar_type; typedef std::complex<scalar_type> value_type; NAN_INLINE value_type& operator*() { return value_; } NAN_INLINE const value_type& operator*() const { return value_; } NAN_INLINE value_type* operator->() { return &value_; } NAN_INLINE const value_type* operator->() const { return &value_; } private: value_type value_; }; } // namespace detail template < template <typename, typename, const char*> class Derived , typename ScalarType , typename ValueType , const char* ClassName > struct base : node::ObjectWrap { typedef Derived<ScalarType, ValueType, ClassName> derived_type; typedef ScalarType scalar_type; typedef typename detail::unwrap_eigen_block<ValueType>::type value_type; typedef typename std::conditional< std::is_same< value_type , typename detail::std_complex_dummy_ptr<scalar_type>::value_type >::value , detail::std_complex_dummy_ptr<scalar_type> , std::shared_ptr<value_type> >::type pointer_type; static NAN_INLINE bool is_scalar(const v8::Handle<v8::Value>& arg) { return arg->IsNumber() ? true : false; } static NAN_INLINE bool is_complex(const v8::Handle<v8::Value>& arg) { return Complex<scalar_type>::base_type::has_instance(arg); } static NAN_INLINE bool is_complex_or_saclar(const v8::Handle<v8::Value>& arg) { return Complex<scalar_type>::base_type::has_instance(arg) || arg->IsNumber() ? true : false; } static NAN_INLINE bool is_matrix(const v8::Handle<v8::Value>& arg) { return Matrix<scalar_type, value_type>::base_type::has_instance(arg); } static NAN_INLINE bool is_cmatrix(const v8::Handle<v8::Value>& arg) { return CMatrix<scalar_type, value_type>::base_type::has_instance(arg); } static NAN_INLINE bool is_vector(const v8::Handle<v8::Value>& arg) { return Vector<scalar_type, value_type>::base_type::has_instance(arg); } static NAN_INLINE bool is_cvector(const v8::Handle<v8::Value>& arg) { return CVector<scalar_type, value_type>::base_type::has_instance(arg); } static NAN_INLINE bool is_rowvector(const v8::Handle<v8::Value>& arg) { return RowVector<scalar_type, value_type>::base_type::has_instance(arg); } static NAN_INLINE bool is_crowvector(const v8::Handle<v8::Value>& arg) { return CRowVector<scalar_type, value_type>::base_type::has_instance(arg); } static NAN_INLINE bool is_matrixblock(const v8::Handle<v8::Value>& arg) { return MatrixBlock<scalar_type, value_type>::base_type::has_instance(arg); } static NAN_INLINE bool is_cmatrixblock(const v8::Handle<v8::Value>& arg) { return CMatrixBlock<scalar_type, value_type>::base_type::has_instance(arg); } static NAN_INLINE bool has_instance(const v8::Handle<v8::Value>& value) { NanScope(); v8::Local<v8::FunctionTemplate> tpl = NanNew(function_template); return tpl->HasInstance(value); } template <typename T> static NAN_INLINE v8::Local<v8::Object> new_instance(const T& args, int argc, v8::Handle<v8::Value> argv[]) { v8::Local<v8::Function> ctor = NanNew(constructor); v8::Local<v8::Object> instance = ctor->NewInstance(argc, argv); return instance; } template <typename T, int Rows, int Cols> static NAN_INLINE bool is_out_of_range( const Eigen::Matrix<T, Rows, Cols>& eigen_matrix , const typename Eigen::Matrix<T, Rows, Cols>::Index& row , const typename Eigen::Matrix<T, Rows, Cols>::Index& col) { return row < 0 || row >= eigen_matrix.rows() || col < 0 || col >= eigen_matrix.cols() ? NanThrowError("Row or column numbers are out of range"), true : false; } template < typename XprType , int BlockRows , int BlockCols , bool InnerPanel > static NAN_INLINE bool is_out_of_range( const Eigen::Block< XprType , BlockRows , BlockCols , InnerPanel >& eigen_block , const typename XprType::Index& row , const typename XprType::Index& col) { return row < 0 || row >= eigen_block.rows() || col < 0 || col >= eigen_block.cols() ? NanThrowError("Row or column numbers are out of range"), true : false; } template <typename T, typename U> static NAN_INLINE typename std::enable_if< boost::mpl::and_< boost::mpl::or_< detail::is_eigen_block<typename T::value_type> , detail::is_eigen_matrix<typename T::value_type> > , boost::mpl::or_< detail::is_eigen_block<typename U::value_type> , detail::is_eigen_matrix<typename U::value_type> > >::value , bool >::type is_nonconformate_arguments( const T* const& op1 , const U* const& op2) { return (*op1)->rows() != (*op2)->rows() || (*op1)->cols() != (*op2)->cols() ? NanThrowError("Nonconformant arguments"), true : false; } template <typename T, typename U> static NAN_INLINE typename std::enable_if< boost::mpl::and_< boost::mpl::or_< detail::is_eigen_block<typename T::value_type> , detail::is_eigen_matrix<typename T::value_type> > , boost::mpl::or_< detail::is_eigen_block<typename U::value_type> , detail::is_eigen_matrix<typename U::value_type> > >::value , bool >::type is_invalid_matrix_product( const T* const& op1 , const U* const& op2) { return (*op1)->cols() != (*op2)->rows() ? NanThrowError("Invalid matrix product"), true : false; } public: NAN_INLINE value_type& operator*() { return *value_ptr_; } NAN_INLINE const value_type& operator*() const { return *value_ptr_; } NAN_INLINE value_type* operator->() { return value_ptr_.get(); } NAN_INLINE const value_type* operator->() const { return value_ptr_.get(); } NAN_INLINE operator const pointer_type&() const { return value_ptr_; } protected: base() : value_ptr_(new value_type()) {} explicit base(const Complex<scalar_type>&) : value_ptr_() {} explicit base(const pointer_type& value_ptr) : value_ptr_(value_ptr) {} ~base() {} static v8::Persistent<v8::FunctionTemplate> function_template; static v8::Persistent<v8::Function> constructor; private: friend derived_type; pointer_type value_ptr_; }; template< template <typename, typename, const char*> class Derived , typename ScalarType , typename ValueType , const char* ClassName > v8::Persistent<v8::FunctionTemplate> base<Derived, ScalarType, ValueType, ClassName>::function_template; template< template <typename, typename, const char*> class Derived , typename ScalarType , typename ValueType , const char* ClassName > v8::Persistent<v8::Function> base<Derived, ScalarType, ValueType, ClassName>::constructor; } // namespace EigenJS #endif // EIGENJS_BASIC_HPP <commit_msg>src: improve code<commit_after>// // base.hpp // ~~~~~~~~ // // Copyright (c) 2014 Rick Yang (rick68 at gmail dot com) // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // #ifndef EIGENJS_BASIC_HPP #define EIGENJS_BASIC_HPP #include <v8.h> #include <node.h> #include <nan.h> #include <boost/mpl/and.hpp> #include <boost/mpl/or.hpp> #include <eigen3/Eigen/Dense> #include <complex> #include <memory> #include <type_traits> #include "Complex_fwd.hpp" #include "Matrix_fwd.hpp" #include "CMatrix_fwd.hpp" #include "Vector_fwd.hpp" #include "CVector_fwd.hpp" #include "RowVector_fwd.hpp" #include "CRowVector_fwd.hpp" #include "MatrixBlock_fwd.hpp" #include "CMatrixBlock_fwd.hpp" #include "detail/unwrap_eigen_block.hpp" #include "detail/is_eigen_block.hpp" #include "detail/is_eigen_matrix.hpp" namespace EigenJS { namespace detail { template <typename ScalarType> struct std_complex_dummy_ptr { typedef ScalarType scalar_type; typedef std::complex<scalar_type> value_type; NAN_INLINE value_type& operator*() { return value_; } NAN_INLINE const value_type& operator*() const { return value_; } NAN_INLINE value_type* operator->() { return &value_; } NAN_INLINE const value_type* operator->() const { return &value_; } private: value_type value_; }; } // namespace detail template < template <typename, typename, const char*> class Derived , typename ScalarType , typename ValueType , const char* ClassName > struct base : node::ObjectWrap { typedef Derived<ScalarType, ValueType, ClassName> derived_type; typedef ScalarType scalar_type; typedef typename detail::unwrap_eigen_block<ValueType>::type value_type; typedef typename std::conditional< std::is_same< value_type , typename detail::std_complex_dummy_ptr<scalar_type>::value_type >::value , detail::std_complex_dummy_ptr<scalar_type> , std::shared_ptr<value_type> >::type pointer_type; static NAN_INLINE bool is_scalar(const v8::Handle<v8::Value>& arg) { return arg->IsNumber() ? true : false; } static NAN_INLINE bool is_complex(const v8::Handle<v8::Value>& arg) { return Complex<scalar_type>::base_type::has_instance(arg); } static NAN_INLINE bool is_complex_or_saclar(const v8::Handle<v8::Value>& arg) { return Complex<scalar_type>::base_type::has_instance(arg) || arg->IsNumber() ? true : false; } static NAN_INLINE bool is_matrix(const v8::Handle<v8::Value>& arg) { return Matrix<scalar_type>::base_type::has_instance(arg); } static NAN_INLINE bool is_cmatrix(const v8::Handle<v8::Value>& arg) { return CMatrix<scalar_type>::base_type::has_instance(arg); } static NAN_INLINE bool is_vector(const v8::Handle<v8::Value>& arg) { return Vector<scalar_type>::base_type::has_instance(arg); } static NAN_INLINE bool is_cvector(const v8::Handle<v8::Value>& arg) { return CVector<scalar_type>::base_type::has_instance(arg); } static NAN_INLINE bool is_rowvector(const v8::Handle<v8::Value>& arg) { return RowVector<scalar_type>::base_type::has_instance(arg); } static NAN_INLINE bool is_crowvector(const v8::Handle<v8::Value>& arg) { return CRowVector<scalar_type>::base_type::has_instance(arg); } static NAN_INLINE bool is_matrixblock(const v8::Handle<v8::Value>& arg) { return MatrixBlock<scalar_type>::base_type::has_instance(arg); } static NAN_INLINE bool is_cmatrixblock(const v8::Handle<v8::Value>& arg) { return CMatrixBlock<scalar_type>::base_type::has_instance(arg); } static NAN_INLINE bool has_instance(const v8::Handle<v8::Value>& value) { NanScope(); v8::Local<v8::FunctionTemplate> tpl = NanNew(function_template); return tpl->HasInstance(value); } template <typename T> static NAN_INLINE v8::Local<v8::Object> new_instance(const T& args, int argc, v8::Handle<v8::Value> argv[]) { v8::Local<v8::Function> ctor = NanNew(constructor); v8::Local<v8::Object> instance = ctor->NewInstance(argc, argv); return instance; } template <typename T, int Rows, int Cols> static NAN_INLINE bool is_out_of_range( const Eigen::Matrix<T, Rows, Cols>& eigen_matrix , const typename Eigen::Matrix<T, Rows, Cols>::Index& row , const typename Eigen::Matrix<T, Rows, Cols>::Index& col) { return row < 0 || row >= eigen_matrix.rows() || col < 0 || col >= eigen_matrix.cols() ? NanThrowError("Row or column numbers are out of range"), true : false; } template < typename XprType , int BlockRows , int BlockCols , bool InnerPanel > static NAN_INLINE bool is_out_of_range( const Eigen::Block< XprType , BlockRows , BlockCols , InnerPanel >& eigen_block , const typename XprType::Index& row , const typename XprType::Index& col) { return row < 0 || row >= eigen_block.rows() || col < 0 || col >= eigen_block.cols() ? NanThrowError("Row or column numbers are out of range"), true : false; } template <typename T, typename U> static NAN_INLINE typename std::enable_if< boost::mpl::and_< boost::mpl::or_< detail::is_eigen_block<typename T::value_type> , detail::is_eigen_matrix<typename T::value_type> > , boost::mpl::or_< detail::is_eigen_block<typename U::value_type> , detail::is_eigen_matrix<typename U::value_type> > >::value , bool >::type is_nonconformate_arguments( const T* const& op1 , const U* const& op2) { return (*op1)->rows() != (*op2)->rows() || (*op1)->cols() != (*op2)->cols() ? NanThrowError("Nonconformant arguments"), true : false; } template <typename T, typename U> static NAN_INLINE typename std::enable_if< boost::mpl::and_< boost::mpl::or_< detail::is_eigen_block<typename T::value_type> , detail::is_eigen_matrix<typename T::value_type> > , boost::mpl::or_< detail::is_eigen_block<typename U::value_type> , detail::is_eigen_matrix<typename U::value_type> > >::value , bool >::type is_invalid_matrix_product( const T* const& op1 , const U* const& op2) { return (*op1)->cols() != (*op2)->rows() ? NanThrowError("Invalid matrix product"), true : false; } public: NAN_INLINE value_type& operator*() { return *value_ptr_; } NAN_INLINE const value_type& operator*() const { return *value_ptr_; } NAN_INLINE value_type* operator->() { return value_ptr_.get(); } NAN_INLINE const value_type* operator->() const { return value_ptr_.get(); } NAN_INLINE operator const pointer_type&() const { return value_ptr_; } protected: base() : value_ptr_(new value_type()) {} explicit base(const Complex<scalar_type>&) : value_ptr_() {} explicit base(const pointer_type& value_ptr) : value_ptr_(value_ptr) {} ~base() {} static v8::Persistent<v8::FunctionTemplate> function_template; static v8::Persistent<v8::Function> constructor; private: friend derived_type; pointer_type value_ptr_; }; template< template <typename, typename, const char*> class Derived , typename ScalarType , typename ValueType , const char* ClassName > v8::Persistent<v8::FunctionTemplate> base<Derived, ScalarType, ValueType, ClassName>::function_template; template< template <typename, typename, const char*> class Derived , typename ScalarType , typename ValueType , const char* ClassName > v8::Persistent<v8::Function> base<Derived, ScalarType, ValueType, ClassName>::constructor; } // namespace EigenJS #endif // EIGENJS_BASIC_HPP <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2015 CantTouchDis <[email protected]> Copyright (c) 2015 brio1009 <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "./ObjParser.h" #include <glm/glm.hpp> #include <cstdio> #include <cstring> #include <vector> #include <string> using std::string; using std::vector; using glm::vec3; using glm::vec2; namespace { // reads a line of the file to the buffer vector. Returns the last character. int readLine(FILE* file, vector<char>* buffer) { // ensure buffer is clear. buffer->clear(); int character = EOF; // read as long as we are allowed to. while ((character = fgetc(file)) != EOF && character != '\n') { buffer->push_back(static_cast<char>(character)); } // append 0 to ensure buffer.data works like a cstring. buffer->push_back('\0'); return character; } void addQuad( unsigned int (&vInd)[4], unsigned int (&nInd)[4], unsigned int (&uvInd)[4], vector<unsigned int>* vIndices, vector<unsigned int>* nIndices, vector<unsigned int>* uvIndices) { // vertex indices vIndices->push_back(vInd[0]); vIndices->push_back(vInd[1]); vIndices->push_back(vInd[2]); vIndices->push_back(vInd[2]); vIndices->push_back(vInd[3]); vIndices->push_back(vInd[0]); // normal indices nIndices->push_back(nInd[0]); nIndices->push_back(nInd[1]); nIndices->push_back(nInd[2]); nIndices->push_back(nInd[2]); nIndices->push_back(nInd[3]); nIndices->push_back(nInd[0]); // uv Indices uvIndices->push_back(uvInd[0]); uvIndices->push_back(uvInd[1]); uvIndices->push_back(uvInd[2]); uvIndices->push_back(uvInd[2]); uvIndices->push_back(uvInd[3]); uvIndices->push_back(uvInd[0]); } void addTriangle( unsigned int (&vInd)[4], unsigned int (&nInd)[4], unsigned int (&uvInd)[4], vector<unsigned int>* vIndices, vector<unsigned int>* nIndices, vector<unsigned int>* uvIndices) { // vertex indices vIndices->push_back(vInd[0]); vIndices->push_back(vInd[1]); vIndices->push_back(vInd[2]); // normal indices nIndices->push_back(nInd[0]); nIndices->push_back(nInd[1]); nIndices->push_back(nInd[2]); // uv Indices uvIndices->push_back(uvInd[0]); uvIndices->push_back(uvInd[1]); uvIndices->push_back(uvInd[2]); } void addFace( const vector<char>& buffer, vector<unsigned int>* vIndices, vector<unsigned int>* nIndices, vector<unsigned int>* uvIndices) { // Faces can either be: // 1. vertices only // 2. vertices + texture // 3. vertices + normal + texture // Four Vertices 3. unsigned int vInd[4], nInd[4], uvInd[4]; int numMatches = sscanf(buffer.data(), "%*s" " %d/%d/%d" " %d/%d/%d" " %d/%d/%d" " %d/%d/%d", &vInd[0], &uvInd[0], &nInd[0], &vInd[1], &uvInd[1], &nInd[1], &vInd[2], &uvInd[2], &nInd[2], &vInd[3], &uvInd[3], &nInd[3]); if (numMatches == 12) { // Parsed correctly a quad. addQuad(vInd, nInd, uvInd, vIndices, nIndices, uvIndices); return; } numMatches = sscanf(buffer.data(), "%*s" " %d//%d" " %d//%d" " %d//%d" " %d//%d", &vInd[0], &nInd[0], &vInd[1], &nInd[1], &vInd[2], &nInd[2], &vInd[3], &nInd[3]); uvInd[0] = 0; uvInd[1] = 0; uvInd[2] = 0; uvInd[3] = 0; if (numMatches == 8) { // Parsed correctly a quad. addQuad(vInd, nInd, uvInd, vIndices, nIndices, uvIndices); return; } numMatches = sscanf(buffer.data(), "%*s" " %d/%d" " %d/%d" " %d/%d" " %d/%d", &vInd[0], &uvInd[0], &vInd[1], &uvInd[1], &vInd[2], &uvInd[2], &vInd[3], &uvInd[3]); nInd[0] = 0; nInd[1] = 0; nInd[2] = 0; nInd[3] = 0; if (numMatches == 8) { // Parsed correctly a quad. addQuad(vInd, nInd, uvInd, vIndices, nIndices, uvIndices); return; } numMatches = sscanf(buffer.data(), "%*s" " %d" " %d" " %d" " %d", &vInd[0], &vInd[1], &vInd[2], &vInd[3]); uvInd[0] = 0; uvInd[1] = 0; uvInd[2] = 0; uvInd[3] = 0; if (numMatches == 4) { // Parsed correctly a quad. addQuad(vInd, nInd, uvInd, vIndices, nIndices, uvIndices); return; } // Triangle Vertices+Texture+Normal numMatches = sscanf(buffer.data(), "%*s" " %d/%d/%d" " %d/%d/%d" " %d/%d/%d", &vInd[0], &uvInd[0], &nInd[0], &vInd[1], &uvInd[1], &nInd[1], &vInd[2], &uvInd[2], &nInd[2]); if (numMatches == 9) { // Parsed correctly a quad. addTriangle(vInd, nInd, uvInd, vIndices, nIndices, uvIndices); return; } // Triangle Vertices+Normal numMatches = sscanf(buffer.data(), "%*s" " %d//%d" " %d//%d" " %d//%d", &vInd[0], &nInd[0], &vInd[1], &nInd[1], &vInd[2], &nInd[2]); uvInd[0] = 0; uvInd[1] = 0; uvInd[2] = 0; uvInd[3] = 0; if (numMatches == 6) { // Parsed correctly a quad. addTriangle(vInd, nInd, uvInd, vIndices, nIndices, uvIndices); return; } // Triangle Vertices+Texture numMatches = sscanf(buffer.data(), "%*s" " %d/%d" " %d/%d" " %d/%d", &vInd[0], &uvInd[0], &vInd[1], &uvInd[1], &vInd[2], &uvInd[2]); nInd[0] = 0; nInd[1] = 0; nInd[2] = 0; nInd[3] = 0; if (numMatches == 6) { // Parsed correctly a quad. addTriangle(vInd, nInd, uvInd, vIndices, nIndices, uvIndices); return; } // Triangle Vertices only numMatches = sscanf(buffer.data(), "%*s" " %d" " %d" " %d", &vInd[0], &vInd[1], &vInd[2]); uvInd[0] = 0; uvInd[1] = 0; uvInd[2] = 0; uvInd[3] = 0; if (numMatches == 6) { // Parsed correctly a quad. addTriangle(vInd, nInd, uvInd, vIndices, nIndices, uvIndices); return; } return; } void interpretLine( const vector<char>& buffer, vector<vec3>* vertices, vector<vec3>* normals, vector<vec2>* uvCoords, vector<unsigned int>* vIndices, vector<unsigned int>* nIndices, vector<unsigned int>* uvIndices) { if (strncmp(buffer.data(), "v ", 2) == 0) { // This line contains vertex data. vec3 vertex; sscanf(buffer.data(), "%*s %f %f %f", &vertex.x, &vertex.y, &vertex.z); vertices->push_back(vertex); } if (strncmp(buffer.data(), "vn ", 3) == 0) { // This line contains a normal. vec3 normal; sscanf(buffer.data(), "%*s %f %f %f", &normal.x, &normal.y, &normal.z); normals->push_back(normal); } if (strncmp(buffer.data(), "vt ", 3) == 0) { // This line contains uv coordinates. vec2 uv; sscanf(buffer.data(), "%*s %f %f", &uv.x, &uv.y); uvCoords->push_back(uv); } if (strncmp(buffer.data(), "f ", 2) == 0) { addFace(buffer, vIndices, nIndices, uvIndices); } } } // namespace namespace parser { // _____________________________________________________________________________ bool parseObjFile( const string& filename, vector<vec3>* vertices, vector<vec3>* normals, vector<vec2>* uvCoords) { // opengl-tutorial.org like obj parser. // Open the file. #ifdef WINDOWS FILE* file = nullptr; fopen_s(&file, filename.c_str(), "rb"); #else FILE* file = fopen(filename.c_str(), "r"); #endif // WINDOWS // Is the file ready to be read? if (!file) { fprintf(stderr, "ERROR: could not open file %s\n", filename.c_str()); return false; } // Tmp variables to store read informations. vector<unsigned int> vIndices, nIndices, uvIndices; vector<vec3> tmpVertices; vector<vec3> tmpNormals; vector<vec2> tmpUVCoords; // stores the line. vector<char> buffer; // Read the file line by line into buffer. while (readLine(file, &buffer) != EOF) { // The line is now stored in buffer. interpretLine(buffer, &tmpVertices, &tmpNormals, &tmpUVCoords, &vIndices, &nIndices, &uvIndices); } // Last line of the file is parsed here. interpretLine(buffer, &tmpVertices, &tmpNormals, &tmpUVCoords, &vIndices, &nIndices, &uvIndices); // We are done reading the file. fclose(file); // Now we remove the indeces and store every face in the output vectors. size_t numIndices = vIndices.size(); // Resize the output vectors. vertices->clear(); vertices->reserve(numIndices); normals->clear(); normals->reserve(numIndices); uvCoords->clear(); uvCoords->reserve(numIndices); for (size_t i = 0; i < numIndices; ++i) { vertices->push_back(tmpVertices[vIndices[i] - 1]); if (tmpNormals.size() > nIndices[i] - 1) normals->push_back(tmpNormals[nIndices[i] - 1]); // If file has no tex coordinates defined ignore them! if (uvIndices[i] != 0) uvCoords->push_back(tmpUVCoords[uvIndices[i] - 1]); } printf("parsed a obj file with %lu faces\n", numIndices / 3); return true; } } // namespace parser <commit_msg>Fixed a problem with negative indices.<commit_after>/* The MIT License (MIT) Copyright (c) 2015 CantTouchDis <[email protected]> Copyright (c) 2015 brio1009 <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "./ObjParser.h" #include <glm/glm.hpp> #include <cstdio> #include <cstring> #include <vector> #include <string> using std::string; using std::vector; using glm::vec3; using glm::vec2; namespace { // reads a line of the file to the buffer vector. Returns the last character. int readLine(FILE* file, vector<char>* buffer) { // ensure buffer is clear. buffer->clear(); int character = EOF; // read as long as we are allowed to. while ((character = fgetc(file)) != EOF && character != '\n') { buffer->push_back(static_cast<char>(character)); } // append 0 to ensure buffer.data works like a cstring. buffer->push_back('\0'); return character; } void addQuad( unsigned int (&vInd)[4], unsigned int (&nInd)[4], unsigned int (&uvInd)[4], vector<unsigned int>* vIndices, vector<unsigned int>* nIndices, vector<unsigned int>* uvIndices) { // vertex indices vIndices->push_back(vInd[0]); vIndices->push_back(vInd[1]); vIndices->push_back(vInd[2]); vIndices->push_back(vInd[2]); vIndices->push_back(vInd[3]); vIndices->push_back(vInd[0]); // normal indices nIndices->push_back(nInd[0]); nIndices->push_back(nInd[1]); nIndices->push_back(nInd[2]); nIndices->push_back(nInd[2]); nIndices->push_back(nInd[3]); nIndices->push_back(nInd[0]); // uv Indices uvIndices->push_back(uvInd[0]); uvIndices->push_back(uvInd[1]); uvIndices->push_back(uvInd[2]); uvIndices->push_back(uvInd[2]); uvIndices->push_back(uvInd[3]); uvIndices->push_back(uvInd[0]); } void addTriangle( unsigned int (&vInd)[4], unsigned int (&nInd)[4], unsigned int (&uvInd)[4], vector<unsigned int>* vIndices, vector<unsigned int>* nIndices, vector<unsigned int>* uvIndices) { // vertex indices vIndices->push_back(vInd[0]); vIndices->push_back(vInd[1]); vIndices->push_back(vInd[2]); // normal indices nIndices->push_back(nInd[0]); nIndices->push_back(nInd[1]); nIndices->push_back(nInd[2]); // uv Indices uvIndices->push_back(uvInd[0]); uvIndices->push_back(uvInd[1]); uvIndices->push_back(uvInd[2]); } void toPositiveIndice( size_t numVertices, int (&vertices)[4], unsigned int (&positiveVertices)[4]) { for (int i = 0; i < 4; ++i) { positiveVertices[i] = vertices[i] >= 0 ? vertices[i] : numVertices + vertices[i] + 1; } // printf("NumVertices: %li\nVertices: %d %d %d %d\nPositiveVertices: %d %d %d %d\n", // numVertices, vertices[0], vertices[1], vertices[2], vertices[3], // positiveVertices[0], positiveVertices[1], positiveVertices[2], positiveVertices[3]); // exit(1); } void addFace( const vector<char>& buffer, vector<unsigned int>* vIndices, vector<unsigned int>* nIndices, vector<unsigned int>* uvIndices, const size_t numVertices, const size_t numNormals, const size_t numUVs) { // Faces can either be: // 1. vertices only // 2. vertices + texture // 3. vertices + normal + texture // Four Vertices 3. int vInd[4], nInd[4], uvInd[4]; unsigned int vpInd[4], npInd[4], uvpInd[4]; int numMatches = sscanf(buffer.data(), "%*s" " %d/%d/%d" " %d/%d/%d" " %d/%d/%d" " %d/%d/%d", &vInd[0], &uvInd[0], &nInd[0], &vInd[1], &uvInd[1], &nInd[1], &vInd[2], &uvInd[2], &nInd[2], &vInd[3], &uvInd[3], &nInd[3]); if (numMatches == 12) { // Parsed correctly a quad. toPositiveIndice(numVertices, vInd, vpInd); toPositiveIndice(numNormals, nInd, npInd); toPositiveIndice(numUVs, uvInd, uvpInd); addQuad(vpInd, npInd, uvpInd, vIndices, nIndices, uvIndices); return; } numMatches = sscanf(buffer.data(), "%*s" " %d//%d" " %d//%d" " %d//%d" " %d//%d", &vInd[0], &nInd[0], &vInd[1], &nInd[1], &vInd[2], &nInd[2], &vInd[3], &nInd[3]); uvInd[0] = 0; uvInd[1] = 0; uvInd[2] = 0; uvInd[3] = 0; if (numMatches == 8) { // Parsed correctly a quad. toPositiveIndice(numVertices, vInd, vpInd); toPositiveIndice(numNormals, nInd, npInd); toPositiveIndice(numUVs, uvInd, uvpInd); addQuad(vpInd, npInd, uvpInd, vIndices, nIndices, uvIndices); return; } numMatches = sscanf(buffer.data(), "%*s" " %d/%d" " %d/%d" " %d/%d" " %d/%d", &vInd[0], &uvInd[0], &vInd[1], &uvInd[1], &vInd[2], &uvInd[2], &vInd[3], &uvInd[3]); nInd[0] = 0; nInd[1] = 0; nInd[2] = 0; nInd[3] = 0; if (numMatches == 8) { // Parsed correctly a quad. toPositiveIndice(numVertices, vInd, vpInd); toPositiveIndice(numNormals, nInd, npInd); toPositiveIndice(numUVs, uvInd, uvpInd); addQuad(vpInd, npInd, uvpInd, vIndices, nIndices, uvIndices); return; } numMatches = sscanf(buffer.data(), "%*s" " %d" " %d" " %d" " %d", &vInd[0], &vInd[1], &vInd[2], &vInd[3]); uvInd[0] = 0; uvInd[1] = 0; uvInd[2] = 0; uvInd[3] = 0; if (numMatches == 4) { // Parsed correctly a quad. toPositiveIndice(numVertices, vInd, vpInd); toPositiveIndice(numNormals, nInd, npInd); toPositiveIndice(numUVs, uvInd, uvpInd); addQuad(vpInd, npInd, uvpInd, vIndices, nIndices, uvIndices); return; } // Triangle Vertices+Texture+Normal numMatches = sscanf(buffer.data(), "%*s" " %d/%d/%d" " %d/%d/%d" " %d/%d/%d", &vInd[0], &uvInd[0], &nInd[0], &vInd[1], &uvInd[1], &nInd[1], &vInd[2], &uvInd[2], &nInd[2]); if (numMatches == 9) { // Parsed correctly a quad. toPositiveIndice(numVertices, vInd, vpInd); toPositiveIndice(numNormals, nInd, npInd); toPositiveIndice(numUVs, uvInd, uvpInd); addTriangle(vpInd, npInd, uvpInd, vIndices, nIndices, uvIndices); return; } // Triangle Vertices+Normal numMatches = sscanf(buffer.data(), "%*s" " %d//%d" " %d//%d" " %d//%d", &vInd[0], &nInd[0], &vInd[1], &nInd[1], &vInd[2], &nInd[2]); uvInd[0] = 0; uvInd[1] = 0; uvInd[2] = 0; uvInd[3] = 0; if (numMatches == 6) { // Parsed correctly a quad. toPositiveIndice(numVertices, vInd, vpInd); toPositiveIndice(numNormals, nInd, npInd); toPositiveIndice(numUVs, uvInd, uvpInd); addTriangle(vpInd, npInd, uvpInd, vIndices, nIndices, uvIndices); return; } // Triangle Vertices+Texture numMatches = sscanf(buffer.data(), "%*s" " %d/%d" " %d/%d" " %d/%d", &vInd[0], &uvInd[0], &vInd[1], &uvInd[1], &vInd[2], &uvInd[2]); nInd[0] = 0; nInd[1] = 0; nInd[2] = 0; nInd[3] = 0; if (numMatches == 6) { // Parsed correctly a quad. toPositiveIndice(numVertices, vInd, vpInd); toPositiveIndice(numNormals, nInd, npInd); toPositiveIndice(numUVs, uvInd, uvpInd); addTriangle(vpInd, npInd, uvpInd, vIndices, nIndices, uvIndices); return; } // Triangle Vertices only numMatches = sscanf(buffer.data(), "%*s" " %d" " %d" " %d", &vInd[0], &vInd[1], &vInd[2]); uvInd[0] = 0; uvInd[1] = 0; uvInd[2] = 0; uvInd[3] = 0; if (numMatches == 3) { // Parsed correctly a quad. toPositiveIndice(numVertices, vInd, vpInd); toPositiveIndice(numNormals, nInd, npInd); toPositiveIndice(numUVs, uvInd, uvpInd); addTriangle(vpInd, npInd, uvpInd, vIndices, nIndices, uvIndices); return; } return; } void interpretLine( const vector<char>& buffer, vector<vec3>* vertices, vector<vec3>* normals, vector<vec2>* uvCoords, vector<unsigned int>* vIndices, vector<unsigned int>* nIndices, vector<unsigned int>* uvIndices) { if (strncmp(buffer.data(), "v ", 2) == 0) { // This line contains vertex data. vec3 vertex; sscanf(buffer.data(), "%*s %f %f %f", &vertex.x, &vertex.y, &vertex.z); vertices->push_back(vertex); } if (strncmp(buffer.data(), "vn ", 3) == 0) { // This line contains a normal. vec3 normal; sscanf(buffer.data(), "%*s %f %f %f", &normal.x, &normal.y, &normal.z); normals->push_back(normal); } if (strncmp(buffer.data(), "vt ", 3) == 0) { // This line contains uv coordinates. vec2 uv; sscanf(buffer.data(), "%*s %f %f", &uv.x, &uv.y); uvCoords->push_back(uv); } if (strncmp(buffer.data(), "f ", 2) == 0) { addFace(buffer, vIndices, nIndices, uvIndices, vertices->size(), normals->size(), uvCoords->size()); } } } // namespace namespace parser { // _____________________________________________________________________________ bool parseObjFile( const string& filename, vector<vec3>* vertices, vector<vec3>* normals, vector<vec2>* uvCoords) { // opengl-tutorial.org like obj parser. // Open the file. #ifdef WINDOWS FILE* file = nullptr; fopen_s(&file, filename.c_str(), "rb"); #else FILE* file = fopen(filename.c_str(), "r"); #endif // WINDOWS // Is the file ready to be read? if (!file) { fprintf(stderr, "ERROR: could not open file %s\n", filename.c_str()); return false; } // Tmp variables to store read informations. vector<unsigned int> vIndices, nIndices, uvIndices; vector<vec3> tmpVertices; vector<vec3> tmpNormals; vector<vec2> tmpUVCoords; // stores the line. vector<char> buffer; // Read the file line by line into buffer. while (readLine(file, &buffer) != EOF) { // The line is now stored in buffer. interpretLine(buffer, &tmpVertices, &tmpNormals, &tmpUVCoords, &vIndices, &nIndices, &uvIndices); } // Last line of the file is parsed here. interpretLine(buffer, &tmpVertices, &tmpNormals, &tmpUVCoords, &vIndices, &nIndices, &uvIndices); // We are done reading the file. fclose(file); // Now we remove the indeces and store every face in the output vectors. size_t numIndices = vIndices.size(); // Resize the output vectors. vertices->clear(); vertices->reserve(numIndices); normals->clear(); normals->reserve(numIndices); uvCoords->clear(); uvCoords->reserve(numIndices); for (size_t i = 0; i < numIndices; ++i) { vertices->push_back(tmpVertices[vIndices[i] - 1]); if (tmpNormals.size() > nIndices[i] - 1) normals->push_back(tmpNormals[nIndices[i] - 1]); // If file has no tex coordinates defined ignore them! if (uvIndices[i] != 0) uvCoords->push_back(tmpUVCoords[uvIndices[i] - 1]); } printf("parsed a obj file with %lu faces\n", numIndices / 3); return true; } } // namespace parser <|endoftext|>
<commit_before>#include "server.hpp" namespace po = boost::program_options; using std::cout; using std::cerr; using std::endl; using std::string; sf::UdpSocket socket; unsigned short client_port; std::map<string, Player> players; void shutdown(int s) { (void)s; // intentionally unused cout << "\nServer shutting down..."; for (const auto& pair: players) { sf::Packet sorry; sorry << sf::Uint8(2); socket.send(sorry, pair.second.get_ip(), client_port); } cout << endl; exit(0); } int main(int argc, char* argv[]) { struct sigaction action; action.sa_handler = shutdown; sigemptyset(&action.sa_mask); action.sa_flags = 0; sigaction(SIGINT, &action, nullptr); sigaction(SIGTERM, &action, nullptr); sigaction(SIGKILL, &action, nullptr); po::options_description desc("Bananagrams multiplayer dedicated server"); desc.add_options() ("help", "show options") ("dict", po::value<string>(), "dictionary file") ("port", po::value<unsigned short>()->default_value(default_server_port), "TCP/UDP listening port") ("bunch", po::value<string>()->default_value("1"), "bunch multiplier (0.5 or a positive integer)") ; // TODO usage string // TODO print help on unrecognized options po::variables_map opts; po::store(po::parse_command_line(argc, argv, desc), opts); po::notify(opts); if (opts.count("help")) { cerr << desc << endl; return 1; } // check port option unsigned short server_port {opts["port"].as<unsigned short>()}; if (server_port == 0) { cerr << "Invalid listening port: " << server_port << "!\n"; return 1; } client_port = server_port + 1; // check bunch multiplier option std::stringstream multi_s; multi_s << opts["bunch"].as<string>(); unsigned int b_num {1}; unsigned int b_den {1}; if (multi_s.str() == "0.5") b_den = 2; else multi_s >> b_num; // check dictionary option if (!opts.count("dict")) { cerr << "No dictionary file specified!\n"; return 1; } string dict = opts["dict"].as<string>(); std::map<string, string> dictionary; cout << "Loading dictionary... "; cout.flush(); std::ifstream words(dict); if (!words.is_open()) { std::cerr << "\nFailed to open " << dict << "!\n"; return 1; } // parse dictionary string line; while (std::getline(words, line)) { auto pos = line.find_first_of(' '); if (pos == string::npos) dictionary[line] = ""; else dictionary[line.substr(0, pos)] = line.substr(pos + 1, string::npos); } words.close(); cout << dictionary.size() << " words found"; cout.flush(); // LET'S GO!!! std::list<char> bunch; for (char ch = 'A'; ch <= 'Z'; ++ch) for (unsigned int i = 0; i < ((letter_count[ch - 'A'] * b_num) / b_den); ++i) random_insert(bunch, ch); // TODO catch failure socket.bind(server_port); sf::Uint8 peel_n = 0; bool playing = false; cout << "\nWaiting for players to join..."; cout.flush(); while (true) { sf::Packet packet; sf::IpAddress client_ip; unsigned short client_port; socket.receive(packet, client_ip, client_port); cout << "\nReceived packet from " << client_ip << ":" << client_port; cout.flush(); sf::Uint8 type; std::string id; // every client packet starts with a type and player id packet >> type; packet >> id; switch(type) { case 0: // player join { sf::Uint8 version; packet >> version; if (version != protocol_version) { sf::Packet sorry; sorry << sf::Uint8(1) << sf::Uint8(0); socket.send(sorry, client_ip, client_port); cout << "\nclient failed to join" "\n\tNeed protocol version " << (int)protocol_version << ", got " << (int)version; cout.flush(); break; } if (playing) { sf::Packet sorry; sorry << sf::Uint8(1) << sf::Uint8(3); socket.send(sorry, client_ip, client_port); cout << "\nclient failed to join" "\n\tGame already started"; cout.flush(); break; } if (players.count(id) == 0) { Player player(client_ip); packet >> player; players[id] = player; cout << "\n" << player.get_name() << " has joined the game"; cout.flush(); sf::Packet accept; accept << sf::Uint8(0) << sf::Uint8(players.size() - 1); socket.send(accept, player.get_ip(), client_port); playing = true; // TODO for now, start the game immediately for (const auto& pair : players) { string letters; for (unsigned int i = 0; i < 21; i++) { letters.append(1, bunch.back()); bunch.pop_back(); } sf::Packet peel; peel << sf::Uint8(4) << sf::Uint8(peel_n) << letters; socket.send(peel, pair.second.get_ip(), client_port); } } break; } case 1: // player disconnect { if (players.count(id) > 0) { cout << "\n" << players[id].get_name() << " has left the game"; cout.flush(); players.erase(id); } break; } case 6: // finished peel { if (players.count(id) > 0) { sf::Uint8 client_peel; packet >> client_peel; if (client_peel == peel_n + 1) { sf::Int16 remaining = bunch.size() - players.size(); // if there aren't enough letters left if (remaining < 0) { // send victory notification for (const auto& pair : players) { sf::Packet win; win << sf::Uint8(5) << sf::Uint8(1) << id; socket.send(win, pair.second.get_ip(), client_port); } cout << "\n" << players[id].get_name() << " has won the game!"; cout.flush(); shutdown(0); } ++peel_n; cout << "\n" << players[id].get_name() << " peeled (" << peel_n << ")"; cout.flush(); // send each player a new letter for (const auto& pair : players) { string letter {bunch.back()}; bunch.pop_back(); sf::Packet peel; peel << sf::Uint8(4) << sf::Uint8(peel_n) << remaining << letter; socket.send(peel, pair.second.get_ip(), client_port); } } } } default: cout << "\nUnrecognized packet type: " << (int)type; cout.flush(); } } return 0; } <commit_msg>Fix sending inconsistent peel packets to client<commit_after>#include "server.hpp" namespace po = boost::program_options; using std::cout; using std::cerr; using std::endl; using std::string; sf::UdpSocket socket; unsigned short client_port; std::map<string, Player> players; void shutdown(int s) { (void)s; // intentionally unused cout << "\nServer shutting down..."; for (const auto& pair: players) { sf::Packet sorry; sorry << sf::Uint8(2); socket.send(sorry, pair.second.get_ip(), client_port); } cout << endl; exit(0); } int main(int argc, char* argv[]) { struct sigaction action; action.sa_handler = shutdown; sigemptyset(&action.sa_mask); action.sa_flags = 0; sigaction(SIGINT, &action, nullptr); sigaction(SIGTERM, &action, nullptr); sigaction(SIGKILL, &action, nullptr); po::options_description desc("Bananagrams multiplayer dedicated server"); desc.add_options() ("help", "show options") ("dict", po::value<string>(), "dictionary file") ("port", po::value<unsigned short>()->default_value(default_server_port), "TCP/UDP listening port") ("bunch", po::value<string>()->default_value("1"), "bunch multiplier (0.5 or a positive integer)") ; // TODO usage string // TODO print help on unrecognized options po::variables_map opts; po::store(po::parse_command_line(argc, argv, desc), opts); po::notify(opts); if (opts.count("help")) { cerr << desc << endl; return 1; } // check port option unsigned short server_port {opts["port"].as<unsigned short>()}; if (server_port == 0) { cerr << "Invalid listening port: " << server_port << "!\n"; return 1; } client_port = server_port + 1; // check bunch multiplier option std::stringstream multi_s; multi_s << opts["bunch"].as<string>(); unsigned int b_num {1}; unsigned int b_den {1}; if (multi_s.str() == "0.5") b_den = 2; else multi_s >> b_num; // check dictionary option if (!opts.count("dict")) { cerr << "No dictionary file specified!\n"; return 1; } string dict = opts["dict"].as<string>(); std::map<string, string> dictionary; cout << "Loading dictionary... "; cout.flush(); std::ifstream words(dict); if (!words.is_open()) { std::cerr << "\nFailed to open " << dict << "!\n"; return 1; } // parse dictionary string line; while (std::getline(words, line)) { auto pos = line.find_first_of(' '); if (pos == string::npos) dictionary[line] = ""; else dictionary[line.substr(0, pos)] = line.substr(pos + 1, string::npos); } words.close(); cout << dictionary.size() << " words found"; cout.flush(); // LET'S GO!!! std::list<char> bunch; for (char ch = 'A'; ch <= 'Z'; ++ch) for (unsigned int i = 0; i < ((letter_count[ch - 'A'] * b_num) / b_den); ++i) random_insert(bunch, ch); // TODO catch failure socket.bind(server_port); sf::Uint8 peel_n = 0; bool playing = false; cout << "\nWaiting for players to join..."; cout.flush(); while (true) { sf::Packet packet; sf::IpAddress client_ip; unsigned short client_port; socket.receive(packet, client_ip, client_port); cout << "\nReceived packet from " << client_ip << ":" << client_port; cout.flush(); sf::Uint8 type; std::string id; // every client packet starts with a type and player id packet >> type; packet >> id; switch(type) { case 0: // player join { sf::Uint8 version; packet >> version; if (version != protocol_version) { sf::Packet sorry; sorry << sf::Uint8(1) << sf::Uint8(0); socket.send(sorry, client_ip, client_port); cout << "\nclient failed to join" "\n\tNeed protocol version " << (int)protocol_version << ", got " << (int)version; cout.flush(); break; } if (playing) { sf::Packet sorry; sorry << sf::Uint8(1) << sf::Uint8(3); socket.send(sorry, client_ip, client_port); cout << "\nclient failed to join" "\n\tGame already started"; cout.flush(); break; } if (players.count(id) == 0) { Player player(client_ip); packet >> player; players[id] = player; cout << "\n" << player.get_name() << " has joined the game"; cout.flush(); sf::Packet accept; accept << sf::Uint8(0) << sf::Uint8(players.size() - 1); socket.send(accept, player.get_ip(), client_port); playing = true; sf::Int16 remaining = bunch.size() - 21 * players.size(); // TODO for now, start the game immediately for (const auto& pair : players) { string letters; for (unsigned int i = 0; i < 21; i++) { letters.append(1, bunch.back()); bunch.pop_back(); } cout << "\n" << "Sending " << player.get_name() << " " << letters; cout.flush(); sf::Packet peel; peel << sf::Uint8(4) << sf::Uint8(peel_n) << remaining << pair.first << letters; socket.send(peel, pair.second.get_ip(), client_port); } } break; } case 1: // player disconnect { if (players.count(id) > 0) { cout << "\n" << players[id].get_name() << " has left the game"; cout.flush(); players.erase(id); } break; } case 6: // finished peel { if (players.count(id) > 0) { sf::Uint8 client_peel; packet >> client_peel; if (client_peel == peel_n + 1) { sf::Int16 remaining = bunch.size() - players.size(); // if there aren't enough letters left if (remaining < 0) { // send victory notification for (const auto& pair : players) { sf::Packet win; win << sf::Uint8(5) << sf::Uint8(1) << id; socket.send(win, pair.second.get_ip(), client_port); } cout << "\n" << players[id].get_name() << " has won the game!"; cout.flush(); shutdown(0); } ++peel_n; cout << "\n" << players[id].get_name() << " peeled (" << peel_n << ")"; cout.flush(); // send each player a new letter for (const auto& pair : players) { string letter {bunch.back()}; bunch.pop_back(); sf::Packet peel; peel << sf::Uint8(4) << sf::Uint8(peel_n) << remaining << id << letter; socket.send(peel, pair.second.get_ip(), client_port); } } } } default: cout << "\nUnrecognized packet type: " << (int)type; cout.flush(); } } return 0; } <|endoftext|>
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE** * * Condor Software Copyright Notice * Copyright (C) 1990-2006, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * This source code is covered by the Condor Public License, which can * be found in the accompanying LICENSE.TXT file, or online at * www.condorproject.org. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * AND THE UNIVERSITY OF WISCONSIN-MADISON "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS * FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT * HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON * MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS, * ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY * PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY * RIGHT. * ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/ #include "condor_common.h" #include "condor_debug.h" #include "condor_config.h" #include "internet.h" #include "get_full_hostname.h" #include "my_hostname.h" #include "condor_attributes.h" #include "condor_netdb.h" static char* hostname = NULL; static char* full_hostname = NULL; static unsigned int ip_addr; static struct in_addr sin_addr; static bool has_sin_addr = false; static int hostnames_initialized = 0; static int ipaddr_initialized = 0; static void init_hostnames(); extern "C" { // Return our hostname in a static data buffer. char * my_hostname() { if( ! hostnames_initialized ) { init_hostnames(); } return hostname; } // Return our full hostname (with domain) in a static data buffer. char* my_full_hostname() { if( ! hostnames_initialized ) { init_hostnames(); } return full_hostname; } // Return the host-ordered, unsigned int version of our hostname. unsigned int my_ip_addr() { if( ! ipaddr_initialized ) { init_ipaddr(0); } return ip_addr; } struct in_addr* my_sin_addr() { if( ! ipaddr_initialized ) { init_ipaddr(0); } return &sin_addr; } char* my_ip_string() { if( ! ipaddr_initialized ) { init_ipaddr(0); } // It is too risky to return whatever inet_ntoa() returns // directly, because the caller may unwittingly corrupt that // value by calling inet_ntoa() again. char const *str = inet_ntoa(sin_addr); static char buf[IP_STRING_BUF_SIZE]; if(!str) { return NULL; } ASSERT(strlen(str) < IP_STRING_BUF_SIZE); strcpy(buf,str); return buf; } void init_full_hostname() { char *tmp; // If we don't have our IP addr yet, we'll get it for free if // we want it. if( ! ipaddr_initialized ) { tmp = get_full_hostname( hostname, &sin_addr ); has_sin_addr = true; init_ipaddr(0); } else { tmp = get_full_hostname( hostname ); } if( full_hostname ) { free( full_hostname ); } if( tmp ) { // Found it, use it. full_hostname = strdup( tmp ); delete [] tmp; } else { // Couldn't find it, just use what we've already got. full_hostname = strdup( hostname ); } } void init_ipaddr( int config_done ) { char *network_interface, *tmp; char *host; if( ! hostname ) { init_hostnames(); } dprintf( D_HOSTNAME, "Trying to initialize local IP address (%s)\n", config_done ? "after reading config" : "config file not read" ); if( config_done ) { if( (network_interface = param("NETWORK_INTERFACE")) ) { if( is_ipaddr((const char*)network_interface, &sin_addr) ) { // We were given a valid IP address, which we now // have in ip_addr. Just make sure it's in host // order now: has_sin_addr = true; ip_addr = ntohl( sin_addr.s_addr ); ipaddr_initialized = TRUE; dprintf( D_HOSTNAME, "Using NETWORK_INTERFACE (%s) from " "config file for local IP addr\n", network_interface ); } else { dprintf( D_ALWAYS, "init_ipaddr: Invalid network interface string: \"%s\"\n", network_interface ); dprintf( D_ALWAYS, "init_ipaddr: Using default interface.\n" ); } free( network_interface ); } else { dprintf( D_HOSTNAME, "NETWORK_INTERFACE not in config file, " "using existing value\n" ); } } if( ! ipaddr_initialized ) { if( ! has_sin_addr ) { dprintf( D_HOSTNAME, "Have not found an IP yet, calling " "gethostbyname()\n" ); // Get our official host info to initialize sin_addr if( full_hostname ) { host = full_hostname; } else { host = hostname; } tmp = get_full_hostname( host, &sin_addr ); if( ! tmp ) { EXCEPT( "gethostbyname(%s) failed, errno = %d", host, errno ); } has_sin_addr = true; // We don't need the full hostname, we've already got // that... delete [] tmp; } else { dprintf( D_HOSTNAME, "Already found IP with gethostbyname()\n" ); } ip_addr = ntohl( sin_addr.s_addr ); ipaddr_initialized = TRUE; } } } /* extern "C" */ #ifdef WIN32 // see below comment in init_hostname() to learn why we must // include condor_io in this module. #include "condor_io.h" #endif void init_hostnames() { char *tmp, hostbuf[MAXHOSTNAMELEN]; hostbuf[0]='\0'; #ifdef WIN32 // There are a tools in Condor, like // condor_history, which do not use any CEDAR sockets but which call // some socket helper functions like gethostbyname(). These helper // functions will fail unless WINSOCK is initialized. WINSOCK // is initialized via a global constructor in CEDAR, so we must // make certain we call at least one CEDAR function so the linker // brings in the global constructor to initialize WINSOCK! // In addition, some global constructors end up calling // init_hostnames(), and thus will fail if the global constructor // in CEDAR is not called first. Instead of relying upon a // specified global constructor ordering (which we cannot), // we explicitly invoke SockInitializer::init() right here -Todd T. SockInitializer startmeup; startmeup.init(); #endif if( hostname ) { free( hostname ); } if( full_hostname ) { free( full_hostname ); full_hostname = NULL; } dprintf( D_HOSTNAME, "Finding local host information, " "calling gethostname()\n" ); // Get our local hostname, and strip off the domain if // gethostname returns it. if( condor_gethostname(hostbuf, sizeof(hostbuf)) == 0 ) { if( hostbuf[0] ) { if( (tmp = strchr(hostbuf, '.')) ) { // There's a '.' in the hostname, assume we've got // the full hostname here, save it, and trim the // domain off and save that as the hostname. full_hostname = strdup( hostbuf ); dprintf( D_HOSTNAME, "gethostname() returned fully " "qualified name \"%s\"\n", hostbuf ); *tmp = '\0'; } else { dprintf( D_HOSTNAME, "gethostname() returned a host " "with no domain \"%s\"\n", hostbuf ); } hostname = strdup( hostbuf ); } else { EXCEPT( "gethostname succeeded, but hostbuf is empty" ); } } else { EXCEPT( "gethostname failed, errno = %d", #ifndef WIN32 errno ); #else WSAGetLastError() ); #endif } if( ! full_hostname ) { init_full_hostname(); } hostnames_initialized = TRUE; } // Returns true if given attribute is used by Condor to advertise the // IP address of the sender. This is used by // ConvertMyDefaultIPToMySocketIP(). static bool is_sender_ip_attr(char const *attr_name) { if(strcmp(attr_name,ATTR_MY_ADDRESS) == 0) return true; if(strcmp(attr_name,ATTR_TRANSFER_SOCKET) == 0) return true; // We would not have to rewrite the IP in capability strings, but // some schedd/shadow code assumes that the capability contains // a valid contact address. Therefore, we rewrite the IP in the // capability, and the startd has to ignore differences in the IP // portion of the capability when comparing to capability strings // submitted by the schedd/shadow. if(strcmp(attr_name,ATTR_CAPABILITY) == 0) return true; if(strcmp(attr_name,ATTR_CLAIM_ID) == 0) return true; size_t attr_name_len = strlen(attr_name); if(attr_name_len >= 6 && stricmp(attr_name+attr_name_len-6,"IpAddr") == 0) { return true; } return false; } void ConvertDefaultIPToSocketIP(char const *attr_name,char const *old_expr_string,char **new_expr_string,Stream& s) { *new_expr_string = NULL; if(is_sender_ip_attr(attr_name)) { char const *my_default_ip = my_ip_string(); char const *my_sock_ip = s.sender_ip_str(); if(!my_default_ip || !my_sock_ip) { return; } if(strcmp(my_default_ip,my_sock_ip) == 0) { return; } if(strcmp(my_sock_ip,"127.0.0.1") == 0) { // We assume this is the loop-back interface, so we must // be talking to another daemon on the same machine as us. // We don't want to replace the default IP with this one, // since nobody outside of this machine will be able to // contact us on that IP. return; } char *ref = strstr(old_expr_string,my_default_ip); if(ref) { // Replace the default IP address with the one I am actually using. int pos = ref-old_expr_string; // position of the reference int my_default_ip_len = strlen(my_default_ip); int my_sock_ip_len = strlen(my_sock_ip); *new_expr_string = (char *)malloc(strlen(old_expr_string) + my_sock_ip_len - my_default_ip_len + 1); ASSERT(*new_expr_string); strncpy(*new_expr_string, old_expr_string,pos); strcpy(*new_expr_string+pos, my_sock_ip); strcpy(*new_expr_string+pos+my_sock_ip_len, old_expr_string+pos+my_default_ip_len); dprintf(D_NETWORK,"Replaced default IP %s with connection IP %s " "in outgoing ClassAd attribute %s.\n", my_default_ip,my_sock_ip,attr_name); } } } void ConvertDefaultIPToSocketIP(char const *attr_name,char **expr_string,Stream& s) { char *new_expr_string = NULL; ConvertDefaultIPToSocketIP(attr_name,*expr_string,&new_expr_string,s); if(new_expr_string) { //The expression was updated. Replace the old expression with //the new one. free(*expr_string); *expr_string = new_expr_string; } } <commit_msg>In ConvertDefaultIPToSocketIP(), if GCB is enabled, we need to return immediately, since we never want to re-write IP addresses with GCB.<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE** * * Condor Software Copyright Notice * Copyright (C) 1990-2006, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * This source code is covered by the Condor Public License, which can * be found in the accompanying LICENSE.TXT file, or online at * www.condorproject.org. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * AND THE UNIVERSITY OF WISCONSIN-MADISON "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS * FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT * HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON * MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS, * ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY * PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY * RIGHT. * ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/ #include "condor_common.h" #include "condor_debug.h" #include "condor_config.h" #include "internet.h" #include "get_full_hostname.h" #include "my_hostname.h" #include "condor_attributes.h" #include "condor_netdb.h" static char* hostname = NULL; static char* full_hostname = NULL; static unsigned int ip_addr; static struct in_addr sin_addr; static bool has_sin_addr = false; static int hostnames_initialized = 0; static int ipaddr_initialized = 0; static void init_hostnames(); extern "C" { // Return our hostname in a static data buffer. char * my_hostname() { if( ! hostnames_initialized ) { init_hostnames(); } return hostname; } // Return our full hostname (with domain) in a static data buffer. char* my_full_hostname() { if( ! hostnames_initialized ) { init_hostnames(); } return full_hostname; } // Return the host-ordered, unsigned int version of our hostname. unsigned int my_ip_addr() { if( ! ipaddr_initialized ) { init_ipaddr(0); } return ip_addr; } struct in_addr* my_sin_addr() { if( ! ipaddr_initialized ) { init_ipaddr(0); } return &sin_addr; } char* my_ip_string() { if( ! ipaddr_initialized ) { init_ipaddr(0); } // It is too risky to return whatever inet_ntoa() returns // directly, because the caller may unwittingly corrupt that // value by calling inet_ntoa() again. char const *str = inet_ntoa(sin_addr); static char buf[IP_STRING_BUF_SIZE]; if(!str) { return NULL; } ASSERT(strlen(str) < IP_STRING_BUF_SIZE); strcpy(buf,str); return buf; } void init_full_hostname() { char *tmp; // If we don't have our IP addr yet, we'll get it for free if // we want it. if( ! ipaddr_initialized ) { tmp = get_full_hostname( hostname, &sin_addr ); has_sin_addr = true; init_ipaddr(0); } else { tmp = get_full_hostname( hostname ); } if( full_hostname ) { free( full_hostname ); } if( tmp ) { // Found it, use it. full_hostname = strdup( tmp ); delete [] tmp; } else { // Couldn't find it, just use what we've already got. full_hostname = strdup( hostname ); } } void init_ipaddr( int config_done ) { char *network_interface, *tmp; char *host; if( ! hostname ) { init_hostnames(); } dprintf( D_HOSTNAME, "Trying to initialize local IP address (%s)\n", config_done ? "after reading config" : "config file not read" ); if( config_done ) { if( (network_interface = param("NETWORK_INTERFACE")) ) { if( is_ipaddr((const char*)network_interface, &sin_addr) ) { // We were given a valid IP address, which we now // have in ip_addr. Just make sure it's in host // order now: has_sin_addr = true; ip_addr = ntohl( sin_addr.s_addr ); ipaddr_initialized = TRUE; dprintf( D_HOSTNAME, "Using NETWORK_INTERFACE (%s) from " "config file for local IP addr\n", network_interface ); } else { dprintf( D_ALWAYS, "init_ipaddr: Invalid network interface string: \"%s\"\n", network_interface ); dprintf( D_ALWAYS, "init_ipaddr: Using default interface.\n" ); } free( network_interface ); } else { dprintf( D_HOSTNAME, "NETWORK_INTERFACE not in config file, " "using existing value\n" ); } } if( ! ipaddr_initialized ) { if( ! has_sin_addr ) { dprintf( D_HOSTNAME, "Have not found an IP yet, calling " "gethostbyname()\n" ); // Get our official host info to initialize sin_addr if( full_hostname ) { host = full_hostname; } else { host = hostname; } tmp = get_full_hostname( host, &sin_addr ); if( ! tmp ) { EXCEPT( "gethostbyname(%s) failed, errno = %d", host, errno ); } has_sin_addr = true; // We don't need the full hostname, we've already got // that... delete [] tmp; } else { dprintf( D_HOSTNAME, "Already found IP with gethostbyname()\n" ); } ip_addr = ntohl( sin_addr.s_addr ); ipaddr_initialized = TRUE; } } } /* extern "C" */ #ifdef WIN32 // see below comment in init_hostname() to learn why we must // include condor_io in this module. #include "condor_io.h" #endif void init_hostnames() { char *tmp, hostbuf[MAXHOSTNAMELEN]; hostbuf[0]='\0'; #ifdef WIN32 // There are a tools in Condor, like // condor_history, which do not use any CEDAR sockets but which call // some socket helper functions like gethostbyname(). These helper // functions will fail unless WINSOCK is initialized. WINSOCK // is initialized via a global constructor in CEDAR, so we must // make certain we call at least one CEDAR function so the linker // brings in the global constructor to initialize WINSOCK! // In addition, some global constructors end up calling // init_hostnames(), and thus will fail if the global constructor // in CEDAR is not called first. Instead of relying upon a // specified global constructor ordering (which we cannot), // we explicitly invoke SockInitializer::init() right here -Todd T. SockInitializer startmeup; startmeup.init(); #endif if( hostname ) { free( hostname ); } if( full_hostname ) { free( full_hostname ); full_hostname = NULL; } dprintf( D_HOSTNAME, "Finding local host information, " "calling gethostname()\n" ); // Get our local hostname, and strip off the domain if // gethostname returns it. if( condor_gethostname(hostbuf, sizeof(hostbuf)) == 0 ) { if( hostbuf[0] ) { if( (tmp = strchr(hostbuf, '.')) ) { // There's a '.' in the hostname, assume we've got // the full hostname here, save it, and trim the // domain off and save that as the hostname. full_hostname = strdup( hostbuf ); dprintf( D_HOSTNAME, "gethostname() returned fully " "qualified name \"%s\"\n", hostbuf ); *tmp = '\0'; } else { dprintf( D_HOSTNAME, "gethostname() returned a host " "with no domain \"%s\"\n", hostbuf ); } hostname = strdup( hostbuf ); } else { EXCEPT( "gethostname succeeded, but hostbuf is empty" ); } } else { EXCEPT( "gethostname failed, errno = %d", #ifndef WIN32 errno ); #else WSAGetLastError() ); #endif } if( ! full_hostname ) { init_full_hostname(); } hostnames_initialized = TRUE; } // Returns true if given attribute is used by Condor to advertise the // IP address of the sender. This is used by // ConvertMyDefaultIPToMySocketIP(). static bool is_sender_ip_attr(char const *attr_name) { if(strcmp(attr_name,ATTR_MY_ADDRESS) == 0) return true; if(strcmp(attr_name,ATTR_TRANSFER_SOCKET) == 0) return true; // We would not have to rewrite the IP in capability strings, but // some schedd/shadow code assumes that the capability contains // a valid contact address. Therefore, we rewrite the IP in the // capability, and the startd has to ignore differences in the IP // portion of the capability when comparing to capability strings // submitted by the schedd/shadow. if(strcmp(attr_name,ATTR_CAPABILITY) == 0) return true; if(strcmp(attr_name,ATTR_CLAIM_ID) == 0) return true; size_t attr_name_len = strlen(attr_name); if(attr_name_len >= 6 && stricmp(attr_name+attr_name_len-6,"IpAddr") == 0) { return true; } return false; } void ConvertDefaultIPToSocketIP(char const *attr_name,char const *old_expr_string,char **new_expr_string,Stream& s) { *new_expr_string = NULL; /* Woe is us. If GCB is enabled, we should *NOT* be re-writing IP addresses in the ClassAds we send out. :( We already go through a lot of trouble to make sure they're all set how they should be. This only used to work at all because of a bug in GCB + CEDAR where all outbound connections were hitting GCB_bind() and so we thought my_sock_ip below was the GCB broker's IP, and it all "worked". Once we're not longer pounding the GCB broker for all outbound connections, this bug becomes visible. Note that we use the optional 3rd argument to param_boolean() to get it to shut up, even if NET_REMAP_ENABLE isn't defined in the config file, since otherwise, this would completely FILL a log file at D_CONFIG or D_ALL, since we hit this for *every* attribute in every ClassAd that's sent. */ if (param_boolean("NET_REMAP_ENABLE", false, false)) { return; } if(is_sender_ip_attr(attr_name)) { char const *my_default_ip = my_ip_string(); char const *my_sock_ip = s.sender_ip_str(); if(!my_default_ip || !my_sock_ip) { return; } if(strcmp(my_default_ip,my_sock_ip) == 0) { return; } if(strcmp(my_sock_ip,"127.0.0.1") == 0) { // We assume this is the loop-back interface, so we must // be talking to another daemon on the same machine as us. // We don't want to replace the default IP with this one, // since nobody outside of this machine will be able to // contact us on that IP. return; } char *ref = strstr(old_expr_string,my_default_ip); if(ref) { // Replace the default IP address with the one I am actually using. int pos = ref-old_expr_string; // position of the reference int my_default_ip_len = strlen(my_default_ip); int my_sock_ip_len = strlen(my_sock_ip); *new_expr_string = (char *)malloc(strlen(old_expr_string) + my_sock_ip_len - my_default_ip_len + 1); ASSERT(*new_expr_string); strncpy(*new_expr_string, old_expr_string,pos); strcpy(*new_expr_string+pos, my_sock_ip); strcpy(*new_expr_string+pos+my_sock_ip_len, old_expr_string+pos+my_default_ip_len); dprintf(D_NETWORK,"Replaced default IP %s with connection IP %s " "in outgoing ClassAd attribute %s.\n", my_default_ip,my_sock_ip,attr_name); } } } void ConvertDefaultIPToSocketIP(char const *attr_name,char **expr_string,Stream& s) { char *new_expr_string = NULL; ConvertDefaultIPToSocketIP(attr_name,*expr_string,&new_expr_string,s); if(new_expr_string) { //The expression was updated. Replace the old expression with //the new one. free(*expr_string); *expr_string = new_expr_string; } } <|endoftext|>
<commit_before><commit_msg>Core: Linkcondition cleanup (was causing warnings in VS2017)<commit_after><|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2012-2015 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <inviwo/core/processors/processor.h> #include <inviwo/core/metadata/metadatafactory.h> #include <inviwo/core/metadata/processormetadata.h> #include <inviwo/core/interaction/interactionhandler.h> #include <inviwo/core/interaction/events/event.h> #include <inviwo/core/interaction/events/interactionevent.h> #include <inviwo/core/processors/processorwidget.h> #include <inviwo/core/util/factory.h> #include <inviwo/core/util/stdextensions.h> #include <inviwo/core/ports/imageport.h> namespace inviwo { std::set<std::string> Processor::usedIdentifiers_; ProcessorClassIdentifier(Processor, "org.inviwo.Processor"); ProcessorDisplayName(Processor, "Processor"); ProcessorTags(Processor, Tags::None); ProcessorCategory(Processor, "undefined"); ProcessorCodeState(Processor, CODE_STATE_EXPERIMENTAL); Processor::Processor() : PropertyOwner() , ProcessorObservable() , processorWidget_(nullptr) , identifier_("") , initialized_(false) , invalidationEnabled_(true) , invalidationRequestLevel_(VALID) { createMetaData<ProcessorMetaData>(ProcessorMetaData::CLASS_IDENTIFIER); } Processor::~Processor() { usedIdentifiers_.erase(identifier_); if (processorWidget_) { processorWidget_->setProcessor(nullptr); } } void Processor::addPort(Inport* port, const std::string& portDependencySet) { // TODO: check if port with same name has been added before port->setProcessor(this); inports_.push_back(port); portDependencySets_.insert(portDependencySet, port); notifyObserversProcessorPortAdded(this, port); } void Processor::addPort(Inport& port, const std::string& portDependencySet) { addPort(&port, portDependencySet); } void Processor::addPort(Outport* port, const std::string& portDependencySet) { // TODO: check if port with same name has been added before port->setProcessor(this); outports_.push_back(port); portDependencySets_.insert(portDependencySet, port); notifyObserversProcessorPortAdded(this, port); } void Processor::addPort(Outport& port, const std::string& portDependencySet) { addPort(&port, portDependencySet); } std::string Processor::setIdentifier(const std::string& identifier) { if (identifier == identifier_) // nothing changed return identifier_; if (usedIdentifiers_.find(identifier_) != usedIdentifiers_.end()) { usedIdentifiers_.erase(identifier_); // remove old identifier } std::string baseIdentifier = identifier; std::string newIdentifier = identifier; int i = 2; while (usedIdentifiers_.find(newIdentifier) != usedIdentifiers_.end()) { newIdentifier = baseIdentifier + " " + toString(i++); } usedIdentifiers_.insert(newIdentifier); identifier_ = newIdentifier; notifyObserversIdentifierChange(this); return identifier_; } std::string Processor::getIdentifier() { if (identifier_.empty()) setIdentifier(getDisplayName()); return identifier_; } void Processor::setProcessorWidget(ProcessorWidget* processorWidget) { processorWidget_ = processorWidget; } ProcessorWidget* Processor::getProcessorWidget() const { return processorWidget_; } bool Processor::hasProcessorWidget() const { return (processorWidget_ != nullptr); } Port* Processor::getPort(const std::string& identifier) const { for (auto port : inports_) if (port->getIdentifier() == identifier) return port; for (auto port : outports_) if (port->getIdentifier() == identifier) return port; return nullptr; } Inport* Processor::getInport(const std::string& identifier) const { for (auto port : inports_) if (port->getIdentifier() == identifier) return port; return nullptr; } Outport* Processor::getOutport(const std::string& identifier) const { for (auto port : outports_) if (port->getIdentifier() == identifier) return port; return nullptr; } const std::vector<Inport*>& Processor::getInports() const { return inports_; } const std::vector<Outport*>& Processor::getOutports() const { return outports_; } std::vector<Port*> Processor::getPortsByDependencySet( const std::string& portDependencySet) const { return portDependencySets_.getGroupedData(portDependencySet); } std::vector<std::string> Processor::getPortDependencySets() const { return portDependencySets_.getGroupKeys(); } std::string Processor::getPortDependencySet(Port* port) const { return portDependencySets_.getKey(port); } std::vector<Port*> Processor::getPortsInSameSet(Port* port) const { return portDependencySets_.getGroupedData(portDependencySets_.getKey(port)); } void Processor::initialize() { initialized_ = true; } void Processor::deinitialize() { initialized_ = false; } bool Processor::isInitialized() const { return initialized_; } void Processor::invalidate(InvalidationLevel invalidationLevel, Property* modifiedProperty) { if (!invalidationEnabled_) { invalidationRequestLevel_ = invalidationLevel; return; } notifyObserversInvalidationBegin(this); PropertyOwner::invalidate(invalidationLevel, modifiedProperty); if (PropertyOwner::isValid()) { notifyObserversInvalidationEnd(this); return; } for (auto& port : outports_) port->invalidate(INVALID_OUTPUT); notifyObserversInvalidationEnd(this); if (isEndProcessor()) { performEvaluateRequest(); } } bool Processor::isEndProcessor() const { return outports_.empty(); } bool Processor::isReady() const { return allInportsAreReady(); } bool Processor::allInportsAreReady() const { return util::all_of(inports_, [](Inport* p) { return p->isReady(); }); } bool Processor::allInportsConnected() const { return util::all_of(inports_, [](Inport* p) { return p->isConnected(); }); } void Processor::addInteractionHandler(InteractionHandler* interactionHandler) { util::push_back_unique(interactionHandlers_, interactionHandler); } void Processor::removeInteractionHandler(InteractionHandler* interactionHandler) { util::erase_remove(interactionHandlers_, interactionHandler); } bool Processor::hasInteractionHandler() const { return !interactionHandlers_.empty(); } const std::vector<InteractionHandler*>& Processor::getInteractionHandlers() const { return interactionHandlers_; } void Processor::invokeEvent(Event* event) { PropertyOwner::invokeEvent(event); for (auto elem : interactionHandlers_) elem->invokeEvent(event); } bool Processor::propagateResizeEvent(ResizeEvent* resizeEvent, Outport* source) { bool propagationEnded = true; for (auto port : getPortsInSameSet(source)) { if (auto imageInport = dynamic_cast<ImagePortBase*>(port)) { propagationEnded = false; imageInport->propagateResizeEvent(resizeEvent); } } return propagationEnded; } void Processor::serialize(IvwSerializer& s) const { s.serialize("type", getClassIdentifier(), true); s.serialize("identifier", identifier_, true); s.serialize("InteractonHandlers", interactionHandlers_, "InteractionHandler"); s.serialize("InPorts", inports_, "InPort"); s.serialize("OutPorts", outports_, "OutPort"); PropertyOwner::serialize(s); MetaDataOwner::serialize(s); } void Processor::deserialize(IvwDeserializer& d) { std::string identifier; d.deserialize("identifier", identifier, true); setIdentifier(identifier); // Need to use setIdentifier to make sure we get a unique id. d.deserialize("InteractonHandlers", interactionHandlers_, "InteractionHandler"); StandardIdentifier<Port> inportIdentifier; d.deserialize("InPorts", inports_, "InPort", inportIdentifier); d.deserialize("OutPorts", outports_, "OutPort", inportIdentifier); for (auto elem : inports_) { elem->setProcessor(this); } for (auto elem : outports_) { elem->setProcessor(this); } PropertyOwner::deserialize(d); MetaDataOwner::deserialize(d); } void Processor::setValid() { PropertyOwner::setValid(); for (auto inport : inports_) inport->setChanged(false); for (auto outport : outports_) outport->setValid(); } void Processor::enableInvalidation() { invalidationEnabled_ = true; if (invalidationRequestLevel_ > VALID) { invalidate(invalidationRequestLevel_); invalidationRequestLevel_ = VALID; } } void Processor::disableInvalidation() { invalidationRequestLevel_ = VALID; invalidationEnabled_ = false; } void Processor::performEvaluateRequest() { notifyObserversRequestEvaluate(this); } void Processor::propagateEvent(Event* event) { invokeEvent(event); if (event->hasBeenUsed()) return; for (auto inport : getInports()) { inport->propagateEvent(event); if (event->hasBeenUsed()) return; } } const std::string Processor::getCodeStateString(CodeState state) { switch (state) { case CODE_STATE_STABLE: return "Stable"; case CODE_STATE_BROKEN: return "Broken"; case CODE_STATE_EXPERIMENTAL: return "Experimental"; default: return "Unknown"; } } std::vector<std::string> Processor::getPath() const { std::vector<std::string> path; path.push_back(identifier_); return path; } } // namespace <commit_msg>Core: Processor minor cleanup<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2012-2015 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <inviwo/core/processors/processor.h> #include <inviwo/core/metadata/metadatafactory.h> #include <inviwo/core/metadata/processormetadata.h> #include <inviwo/core/interaction/interactionhandler.h> #include <inviwo/core/interaction/events/event.h> #include <inviwo/core/interaction/events/interactionevent.h> #include <inviwo/core/processors/processorwidget.h> #include <inviwo/core/util/factory.h> #include <inviwo/core/util/stdextensions.h> #include <inviwo/core/ports/imageport.h> namespace inviwo { std::set<std::string> Processor::usedIdentifiers_; ProcessorClassIdentifier(Processor, "org.inviwo.Processor"); ProcessorDisplayName(Processor, "Processor"); ProcessorTags(Processor, Tags::None); ProcessorCategory(Processor, "undefined"); ProcessorCodeState(Processor, CODE_STATE_EXPERIMENTAL); Processor::Processor() : PropertyOwner() , ProcessorObservable() , processorWidget_(nullptr) , identifier_("") , initialized_(false) , invalidationEnabled_(true) , invalidationRequestLevel_(VALID) { createMetaData<ProcessorMetaData>(ProcessorMetaData::CLASS_IDENTIFIER); } Processor::~Processor() { usedIdentifiers_.erase(identifier_); if (processorWidget_) { processorWidget_->setProcessor(nullptr); } } void Processor::addPort(Inport* port, const std::string& portDependencySet) { // TODO: check if port with same name has been added before port->setProcessor(this); inports_.push_back(port); portDependencySets_.insert(portDependencySet, port); notifyObserversProcessorPortAdded(this, port); } void Processor::addPort(Inport& port, const std::string& portDependencySet) { addPort(&port, portDependencySet); } void Processor::addPort(Outport* port, const std::string& portDependencySet) { // TODO: check if port with same name has been added before port->setProcessor(this); outports_.push_back(port); portDependencySets_.insert(portDependencySet, port); notifyObserversProcessorPortAdded(this, port); } void Processor::addPort(Outport& port, const std::string& portDependencySet) { addPort(&port, portDependencySet); } std::string Processor::setIdentifier(const std::string& identifier) { if (identifier == identifier_) // nothing changed return identifier_; if (usedIdentifiers_.find(identifier_) != usedIdentifiers_.end()) { usedIdentifiers_.erase(identifier_); // remove old identifier } std::string baseIdentifier = identifier; std::string newIdentifier = identifier; int i = 2; while (usedIdentifiers_.find(newIdentifier) != usedIdentifiers_.end()) { newIdentifier = baseIdentifier + " " + toString(i++); } usedIdentifiers_.insert(newIdentifier); identifier_ = newIdentifier; notifyObserversIdentifierChange(this); return identifier_; } std::string Processor::getIdentifier() { if (identifier_.empty()) setIdentifier(getDisplayName()); return identifier_; } void Processor::setProcessorWidget(ProcessorWidget* processorWidget) { processorWidget_ = processorWidget; } ProcessorWidget* Processor::getProcessorWidget() const { return processorWidget_; } bool Processor::hasProcessorWidget() const { return (processorWidget_ != nullptr); } Port* Processor::getPort(const std::string& identifier) const { for (auto port : inports_) if (port->getIdentifier() == identifier) return port; for (auto port : outports_) if (port->getIdentifier() == identifier) return port; return nullptr; } Inport* Processor::getInport(const std::string& identifier) const { for (auto port : inports_) if (port->getIdentifier() == identifier) return port; return nullptr; } Outport* Processor::getOutport(const std::string& identifier) const { for (auto port : outports_) if (port->getIdentifier() == identifier) return port; return nullptr; } const std::vector<Inport*>& Processor::getInports() const { return inports_; } const std::vector<Outport*>& Processor::getOutports() const { return outports_; } std::vector<Port*> Processor::getPortsByDependencySet( const std::string& portDependencySet) const { return portDependencySets_.getGroupedData(portDependencySet); } std::vector<std::string> Processor::getPortDependencySets() const { return portDependencySets_.getGroupKeys(); } std::string Processor::getPortDependencySet(Port* port) const { return portDependencySets_.getKey(port); } std::vector<Port*> Processor::getPortsInSameSet(Port* port) const { return portDependencySets_.getGroupedData(portDependencySets_.getKey(port)); } void Processor::initialize() { initialized_ = true; } void Processor::deinitialize() { initialized_ = false; } bool Processor::isInitialized() const { return initialized_; } void Processor::invalidate(InvalidationLevel invalidationLevel, Property* modifiedProperty) { if (!invalidationEnabled_) { invalidationRequestLevel_ = invalidationLevel; return; } notifyObserversInvalidationBegin(this); PropertyOwner::invalidate(invalidationLevel, modifiedProperty); if (!isValid()) { for (auto& port : outports_) port->invalidate(INVALID_OUTPUT); } notifyObserversInvalidationEnd(this); if (!isValid() && isEndProcessor()) { performEvaluateRequest(); } } bool Processor::isEndProcessor() const { return outports_.empty(); } bool Processor::isReady() const { return allInportsAreReady(); } bool Processor::allInportsAreReady() const { return util::all_of(inports_, [](Inport* p) { return p->isReady(); }); } bool Processor::allInportsConnected() const { return util::all_of(inports_, [](Inport* p) { return p->isConnected(); }); } void Processor::addInteractionHandler(InteractionHandler* interactionHandler) { util::push_back_unique(interactionHandlers_, interactionHandler); } void Processor::removeInteractionHandler(InteractionHandler* interactionHandler) { util::erase_remove(interactionHandlers_, interactionHandler); } bool Processor::hasInteractionHandler() const { return !interactionHandlers_.empty(); } const std::vector<InteractionHandler*>& Processor::getInteractionHandlers() const { return interactionHandlers_; } void Processor::invokeEvent(Event* event) { PropertyOwner::invokeEvent(event); for (auto elem : interactionHandlers_) elem->invokeEvent(event); } bool Processor::propagateResizeEvent(ResizeEvent* resizeEvent, Outport* source) { bool propagationEnded = true; for (auto port : getPortsInSameSet(source)) { if (auto imageInport = dynamic_cast<ImagePortBase*>(port)) { propagationEnded = false; imageInport->propagateResizeEvent(resizeEvent); } } return propagationEnded; } void Processor::serialize(IvwSerializer& s) const { s.serialize("type", getClassIdentifier(), true); s.serialize("identifier", identifier_, true); s.serialize("InteractonHandlers", interactionHandlers_, "InteractionHandler"); s.serialize("InPorts", inports_, "InPort"); s.serialize("OutPorts", outports_, "OutPort"); PropertyOwner::serialize(s); MetaDataOwner::serialize(s); } void Processor::deserialize(IvwDeserializer& d) { std::string identifier; d.deserialize("identifier", identifier, true); setIdentifier(identifier); // Need to use setIdentifier to make sure we get a unique id. d.deserialize("InteractonHandlers", interactionHandlers_, "InteractionHandler"); StandardIdentifier<Port> inportIdentifier; d.deserialize("InPorts", inports_, "InPort", inportIdentifier); d.deserialize("OutPorts", outports_, "OutPort", inportIdentifier); for (auto elem : inports_) { elem->setProcessor(this); } for (auto elem : outports_) { elem->setProcessor(this); } PropertyOwner::deserialize(d); MetaDataOwner::deserialize(d); } void Processor::setValid() { PropertyOwner::setValid(); for (auto inport : inports_) inport->setChanged(false); for (auto outport : outports_) outport->setValid(); } void Processor::enableInvalidation() { invalidationEnabled_ = true; if (invalidationRequestLevel_ > VALID) { invalidate(invalidationRequestLevel_); invalidationRequestLevel_ = VALID; } } void Processor::disableInvalidation() { invalidationRequestLevel_ = VALID; invalidationEnabled_ = false; } void Processor::performEvaluateRequest() { notifyObserversRequestEvaluate(this); } void Processor::propagateEvent(Event* event) { invokeEvent(event); if (event->hasBeenUsed()) return; for (auto inport : getInports()) { inport->propagateEvent(event); if (event->hasBeenUsed()) return; } } const std::string Processor::getCodeStateString(CodeState state) { switch (state) { case CODE_STATE_STABLE: return "Stable"; case CODE_STATE_BROKEN: return "Broken"; case CODE_STATE_EXPERIMENTAL: return "Experimental"; default: return "Unknown"; } } std::vector<std::string> Processor::getPath() const { std::vector<std::string> path; path.push_back(identifier_); return path; } } // namespace <|endoftext|>
<commit_before>/**************************************************************************** * Copyright (c) 2012-2019 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #ifndef DTK_DETAILS_KOKKOS_EXT_HPP #define DTK_DETAILS_KOKKOS_EXT_HPP #include <Kokkos_View.hpp> #include <cfloat> // DBL_MAX, DBL_EPSILON #include <cmath> // isfinite, HUGE_VAL #include <cstdint> // uint32_t #include <type_traits> #if __cplusplus < 201402L namespace std { template <bool B, class T = void> using enable_if_t = typename std::enable_if<B, T>::type; } // namespace std #endif #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace KokkosExt { template <typename View, typename = void> struct is_accessible_from_host : std::false_type { static_assert( Kokkos::is_view<View>::value, "" ); }; template <typename View> struct is_accessible_from_host< View, typename std::enable_if<Kokkos::Impl::SpaceAccessibility< Kokkos::HostSpace, typename View::memory_space>::accessible>::type> : std::true_type { }; /** Count the number of consecutive leading zero bits in 32 bit integer * @param x */ KOKKOS_INLINE_FUNCTION int clz( uint32_t x ) { #if defined( __CUDA_ARCH__ ) // Note that the __clz() CUDA intrinsic function takes a signed integer // as input parameter. This is fine but would need to be adjusted if // we were to change expandBits() and morton3D() to subdivide [0, 1]^3 // into more 1024^3 bins. return __clz( x ); #elif defined( KOKKOS_COMPILER_GNU ) || ( KOKKOS_COMPILER_CLANG >= 500 ) // According to https://en.wikipedia.org/wiki/Find_first_set // Clang 5.X supports the builtin function with the same syntax as GCC return ( x == 0 ) ? 32 : __builtin_clz( x ); #else if ( x == 0 ) return 32; // The following is taken from: // http://stackoverflow.com/questions/23856596/counting-leading-zeros-in-a-32-bit-unsigned-integer-with-best-algorithm-in-c-pro const char debruijn32[32] = {0, 31, 9, 30, 3, 8, 13, 29, 2, 5, 7, 21, 12, 24, 28, 19, 1, 10, 4, 14, 6, 22, 25, 20, 11, 15, 23, 26, 16, 27, 17, 18}; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; x++; return debruijn32[x * 0x076be629 >> 27]; #endif } //! Compute the maximum of two values. template <typename T, typename = std::enable_if_t<std::is_arithmetic<T>::value>> KOKKOS_INLINE_FUNCTION T max( T a, T b ) { return ( a > b ) ? a : b; } //! Compute the minimum of two values. template <typename T, typename = std::enable_if_t<std::is_arithmetic<T>::value>> KOKKOS_INLINE_FUNCTION T min( T a, T b ) { return ( a < b ) ? a : b; } /** * Branchless sign function. Return 1 if @param x is greater than zero, 0 if * @param x is zero, and -1 if @param x is less than zero. */ template <typename T, typename = std::enable_if_t<std::is_arithmetic<T>::value>> KOKKOS_INLINE_FUNCTION int sgn( T x ) { return ( x > 0 ) - ( x < 0 ); } /** Determine whether the given floating point argument @param x has finite * value. * * NOTE: Clang issues a warning if the std:: namespace is missing and nvcc * complains about calling a __host__ function from a __host__ __device__ * function when it is present. */ template <typename FloatingPoint> KOKKOS_INLINE_FUNCTION bool isFinite( FloatingPoint x ) { #ifdef __CUDA_ARCH__ return isfinite( x ); #else return std::isfinite( x ); #endif } namespace ArithmeticTraits { template <typename T> struct infinity { }; template <> struct infinity<double> { static constexpr double value = HUGE_VAL; }; template <typename T> struct max { }; template <> struct max<double> { static constexpr double value = DBL_MAX; }; template <typename T> struct epsilon { }; template <> struct epsilon<double> { static constexpr double value = DBL_EPSILON; }; } // namespace ArithmeticTraits } // namespace KokkosExt #endif // DOXYGEN_SHOULD_SKIP_THIS #endif <commit_msg>Remove constraints on overload set for KokkosExt::{min, max}<commit_after>/**************************************************************************** * Copyright (c) 2012-2019 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #ifndef DTK_DETAILS_KOKKOS_EXT_HPP #define DTK_DETAILS_KOKKOS_EXT_HPP #include <Kokkos_View.hpp> #include <cfloat> // DBL_MAX, DBL_EPSILON #include <cmath> // isfinite, HUGE_VAL #include <cstdint> // uint32_t #include <type_traits> #if __cplusplus < 201402L namespace std { template <bool B, class T = void> using enable_if_t = typename std::enable_if<B, T>::type; } // namespace std #endif #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace KokkosExt { template <typename View, typename = void> struct is_accessible_from_host : std::false_type { static_assert( Kokkos::is_view<View>::value, "" ); }; template <typename View> struct is_accessible_from_host< View, typename std::enable_if<Kokkos::Impl::SpaceAccessibility< Kokkos::HostSpace, typename View::memory_space>::accessible>::type> : std::true_type { }; /** Count the number of consecutive leading zero bits in 32 bit integer * @param x */ KOKKOS_INLINE_FUNCTION int clz( uint32_t x ) { #if defined( __CUDA_ARCH__ ) // Note that the __clz() CUDA intrinsic function takes a signed integer // as input parameter. This is fine but would need to be adjusted if // we were to change expandBits() and morton3D() to subdivide [0, 1]^3 // into more 1024^3 bins. return __clz( x ); #elif defined( KOKKOS_COMPILER_GNU ) || ( KOKKOS_COMPILER_CLANG >= 500 ) // According to https://en.wikipedia.org/wiki/Find_first_set // Clang 5.X supports the builtin function with the same syntax as GCC return ( x == 0 ) ? 32 : __builtin_clz( x ); #else if ( x == 0 ) return 32; // The following is taken from: // http://stackoverflow.com/questions/23856596/counting-leading-zeros-in-a-32-bit-unsigned-integer-with-best-algorithm-in-c-pro const char debruijn32[32] = {0, 31, 9, 30, 3, 8, 13, 29, 2, 5, 7, 21, 12, 24, 28, 19, 1, 10, 4, 14, 6, 22, 25, 20, 11, 15, 23, 26, 16, 27, 17, 18}; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; x++; return debruijn32[x * 0x076be629 >> 27]; #endif } //! Compute the maximum of two values. template <typename T> KOKKOS_INLINE_FUNCTION T max( T a, T b ) { return ( a > b ) ? a : b; } //! Compute the minimum of two values. template <typename T> KOKKOS_INLINE_FUNCTION T min( T a, T b ) { return ( a < b ) ? a : b; } /** * Branchless sign function. Return 1 if @param x is greater than zero, 0 if * @param x is zero, and -1 if @param x is less than zero. */ template <typename T, typename = std::enable_if_t<std::is_arithmetic<T>::value>> KOKKOS_INLINE_FUNCTION int sgn( T x ) { return ( x > 0 ) - ( x < 0 ); } /** Determine whether the given floating point argument @param x has finite * value. * * NOTE: Clang issues a warning if the std:: namespace is missing and nvcc * complains about calling a __host__ function from a __host__ __device__ * function when it is present. */ template <typename FloatingPoint> KOKKOS_INLINE_FUNCTION bool isFinite( FloatingPoint x ) { #ifdef __CUDA_ARCH__ return isfinite( x ); #else return std::isfinite( x ); #endif } namespace ArithmeticTraits { template <typename T> struct infinity { }; template <> struct infinity<double> { static constexpr double value = HUGE_VAL; }; template <typename T> struct max { }; template <> struct max<double> { static constexpr double value = DBL_MAX; }; template <typename T> struct epsilon { }; template <> struct epsilon<double> { static constexpr double value = DBL_EPSILON; }; } // namespace ArithmeticTraits } // namespace KokkosExt #endif // DOXYGEN_SHOULD_SKIP_THIS #endif <|endoftext|>
<commit_before>// This file is part of the AliceVision project. // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. #include "Stat3d.hpp" namespace aliceVision { double hypot2(double x, double y) { return sqrt(x * x + y * y); } // Symmetric Householder reductio3 to tridiago3al form. void tred2(double V0[], double V1[], double V2[], double d[], double e[]) { int i, j, k; double scale, h, f, g, hh; double V[3][3]; V[0][0] = V0[0]; V[0][1] = V0[1]; V[0][2] = V0[2]; V[1][0] = V1[0]; V[1][1] = V1[1]; V[1][2] = V1[2]; V[2][0] = V2[0]; V[2][1] = V2[1]; V[2][2] = V2[2]; for(j = 0; j < 3; j++) { d[j] = V[3 - 1][j]; } // Householder reduction to tridiagonal form. for(i = 3 - 1; i > 0; i--) { // Scale to avoid under/overflow. scale = 0.0; h = 0.0; for(k = 0; k < i; k++) { scale = scale + fabs(d[k]); } if(scale == 0.0) { e[i] = d[i - 1]; for(j = 0; j < i; j++) { d[j] = V[i - 1][j]; V[i][j] = 0.0; V[j][i] = 0.0; } } else { // Generate Householder vector. for(k = 0; k < i; k++) { d[k] /= scale; h += d[k] * d[k]; } f = d[i - 1]; g = sqrt(h); if(f > 0) { g = -g; } e[i] = scale * g; h = h - f * g; d[i - 1] = f - g; for(j = 0; j < i; j++) { e[j] = 0.0; } // Apply similarity transformation to remaining columns. for(j = 0; j < i; j++) { f = d[j]; V[j][i] = f; g = e[j] + V[j][j] * f; for(k = j + 1; k <= i - 1; k++) { g += V[k][j] * d[k]; e[k] += V[k][j] * f; } e[j] = g; } f = 0.0; for(j = 0; j < i; j++) { e[j] /= h; f += e[j] * d[j]; } hh = f / (h + h); for(j = 0; j < i; j++) { e[j] -= hh * d[j]; } for(j = 0; j < i; j++) { f = d[j]; g = e[j]; for(k = j; k <= i - 1; k++) { V[k][j] -= (f * e[k] + g * d[k]); } d[j] = V[i - 1][j]; V[i][j] = 0.0; } } d[i] = h; } // Accumulate transformations. for(i = 0; i < 3 - 1; i++) { V[3 - 1][i] = V[i][i]; V[i][i] = 1.0; h = d[i + 1]; if(h != 0.0) { for(k = 0; k <= i; k++) { d[k] = V[k][i + 1] / h; } for(j = 0; j <= i; j++) { g = 0.0; for(k = 0; k <= i; k++) { g += V[k][i + 1] * V[k][j]; } for(k = 0; k <= i; k++) { V[k][j] -= g * d[k]; } } } for(k = 0; k <= i; k++) { V[k][i + 1] = 0.0; } } for(j = 0; j < 3; j++) { d[j] = V[3 - 1][j]; V[3 - 1][j] = 0.0; } V[3 - 1][3 - 1] = 1.0; e[0] = 0.0; V0[0] = V[0][0]; V0[1] = V[0][1]; V0[2] = V[0][2]; V1[0] = V[1][0]; V1[1] = V[1][1]; V1[2] = V[1][2]; V2[0] = V[2][0]; V2[1] = V[2][1]; V2[2] = V[2][2]; } // Symmetric tridiago3al QL algorithm. void tql2(double V0[], double V1[], double V2[], double d[], double e[]) { int i, l, m, iter, k, j; double f, g, p, r, dl1, h, c, c2, c3, el1, s, s2; double tst1; double eps; double V[3][3]; V[0][0] = V0[0]; V[0][1] = V0[1]; V[0][2] = V0[2]; V[1][0] = V1[0]; V[1][1] = V1[1]; V[1][2] = V1[2]; V[2][0] = V2[0]; V[2][1] = V2[1]; V[2][2] = V2[2]; for(i = 1; i < 3; i++) { e[i - 1] = e[i]; } e[3 - 1] = 0.0; f = 0.0; tst1 = 0.0; eps = pow(2.0, -52.0); for(l = 0; l < 3; l++) { // Fi3d small subdiago3al eleme3t tst1 = std::max(tst1, fabs(d[l]) + fabs(e[l])); m = l; while(m < 3) { if(fabs(e[m]) <= eps * tst1) { break; } m++; } // If m == l, d[l] is a3 eige3value, // otherwise, iterate. if(m > l) { iter = 0; do { iter = iter + 1; // (Could check iteratio3 cou3t here.) // Compute implicit shift g = d[l]; p = (d[l + 1] - g) / (2.0 * e[l]); r = hypot2(p, 1.0); if(p < 0) { r = -r; } d[l] = e[l] / (p + r); d[l + 1] = e[l] * (p + r); dl1 = d[l + 1]; h = g - d[l]; for(i = l + 2; i < 3; i++) { d[i] -= h; } f = f + h; // Implicit QL tra3sformatio3. p = d[m]; c = 1.0; c2 = c; c3 = c; el1 = e[l + 1]; s = 0.0; s2 = 0.0; for(i = m - 1; i >= l; i--) { c3 = c2; c2 = c; s2 = s; g = c * e[i]; h = c * p; r = hypot2(p, e[i]); e[i + 1] = s * r; s = e[i] / r; c = p / r; p = c * d[i] - s * g; d[i + 1] = h + s * (c * g + s * d[i]); // Accumulate tra3sformatio3. for(k = 0; k < 3; k++) { h = V[k][i + 1]; V[k][i + 1] = s * V[k][i] + c * h; V[k][i] = c * V[k][i] - s * h; } } p = -s * s2 * c3 * el1 * e[l] / dl1; e[l] = s * p; d[l] = c * p; // Check for co3verge3ce. } while(fabs(e[l]) > eps * tst1); } d[l] = d[l] + f; e[l] = 0.0; } // Sort eige3values a3d correspo3di3g vectors. for(i = 0; i < 3 - 1; i++) { k = i; p = d[i]; for(j = i + 1; j < 3; j++) { if(d[j] < p) { k = j; p = d[j]; } } if(k != i) { d[k] = d[i]; d[i] = p; for(j = 0; j < 3; j++) { p = V[j][i]; V[j][i] = V[j][k]; V[j][k] = p; } } } V0[0] = V[0][0]; V0[1] = V[0][1]; V0[2] = V[0][2]; V1[0] = V[1][0]; V1[1] = V[1][1]; V1[2] = V[1][2]; V2[0] = V[2][0]; V2[1] = V[2][1]; V2[2] = V[2][2]; } void Stat3d::eigen_decomposition(double A[3][3], double V0[], double V1[], double V2[], double d[]) { double e[3]; V0[0] = A[0][0]; V0[1] = A[0][1]; V0[2] = A[0][2]; V1[0] = A[1][0]; V1[1] = A[1][1]; V1[2] = A[1][2]; V2[0] = A[2][0]; V2[1] = A[2][1]; V2[2] = A[2][2]; tred2(V0, V1, V2, d, e); tql2(V0, V1, V2, d, e); } } // namespace aliceVision <commit_msg>[structure] add missing include<commit_after>// This file is part of the AliceVision project. // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. #include "Stat3d.hpp" #include <algorithm> namespace aliceVision { double hypot2(double x, double y) { return sqrt(x * x + y * y); } // Symmetric Householder reductio3 to tridiago3al form. void tred2(double V0[], double V1[], double V2[], double d[], double e[]) { int i, j, k; double scale, h, f, g, hh; double V[3][3]; V[0][0] = V0[0]; V[0][1] = V0[1]; V[0][2] = V0[2]; V[1][0] = V1[0]; V[1][1] = V1[1]; V[1][2] = V1[2]; V[2][0] = V2[0]; V[2][1] = V2[1]; V[2][2] = V2[2]; for(j = 0; j < 3; j++) { d[j] = V[3 - 1][j]; } // Householder reduction to tridiagonal form. for(i = 3 - 1; i > 0; i--) { // Scale to avoid under/overflow. scale = 0.0; h = 0.0; for(k = 0; k < i; k++) { scale = scale + fabs(d[k]); } if(scale == 0.0) { e[i] = d[i - 1]; for(j = 0; j < i; j++) { d[j] = V[i - 1][j]; V[i][j] = 0.0; V[j][i] = 0.0; } } else { // Generate Householder vector. for(k = 0; k < i; k++) { d[k] /= scale; h += d[k] * d[k]; } f = d[i - 1]; g = sqrt(h); if(f > 0) { g = -g; } e[i] = scale * g; h = h - f * g; d[i - 1] = f - g; for(j = 0; j < i; j++) { e[j] = 0.0; } // Apply similarity transformation to remaining columns. for(j = 0; j < i; j++) { f = d[j]; V[j][i] = f; g = e[j] + V[j][j] * f; for(k = j + 1; k <= i - 1; k++) { g += V[k][j] * d[k]; e[k] += V[k][j] * f; } e[j] = g; } f = 0.0; for(j = 0; j < i; j++) { e[j] /= h; f += e[j] * d[j]; } hh = f / (h + h); for(j = 0; j < i; j++) { e[j] -= hh * d[j]; } for(j = 0; j < i; j++) { f = d[j]; g = e[j]; for(k = j; k <= i - 1; k++) { V[k][j] -= (f * e[k] + g * d[k]); } d[j] = V[i - 1][j]; V[i][j] = 0.0; } } d[i] = h; } // Accumulate transformations. for(i = 0; i < 3 - 1; i++) { V[3 - 1][i] = V[i][i]; V[i][i] = 1.0; h = d[i + 1]; if(h != 0.0) { for(k = 0; k <= i; k++) { d[k] = V[k][i + 1] / h; } for(j = 0; j <= i; j++) { g = 0.0; for(k = 0; k <= i; k++) { g += V[k][i + 1] * V[k][j]; } for(k = 0; k <= i; k++) { V[k][j] -= g * d[k]; } } } for(k = 0; k <= i; k++) { V[k][i + 1] = 0.0; } } for(j = 0; j < 3; j++) { d[j] = V[3 - 1][j]; V[3 - 1][j] = 0.0; } V[3 - 1][3 - 1] = 1.0; e[0] = 0.0; V0[0] = V[0][0]; V0[1] = V[0][1]; V0[2] = V[0][2]; V1[0] = V[1][0]; V1[1] = V[1][1]; V1[2] = V[1][2]; V2[0] = V[2][0]; V2[1] = V[2][1]; V2[2] = V[2][2]; } // Symmetric tridiago3al QL algorithm. void tql2(double V0[], double V1[], double V2[], double d[], double e[]) { int i, l, m, iter, k, j; double f, g, p, r, dl1, h, c, c2, c3, el1, s, s2; double tst1; double eps; double V[3][3]; V[0][0] = V0[0]; V[0][1] = V0[1]; V[0][2] = V0[2]; V[1][0] = V1[0]; V[1][1] = V1[1]; V[1][2] = V1[2]; V[2][0] = V2[0]; V[2][1] = V2[1]; V[2][2] = V2[2]; for(i = 1; i < 3; i++) { e[i - 1] = e[i]; } e[3 - 1] = 0.0; f = 0.0; tst1 = 0.0; eps = pow(2.0, -52.0); for(l = 0; l < 3; l++) { // Fi3d small subdiago3al eleme3t tst1 = std::max(tst1, fabs(d[l]) + fabs(e[l])); m = l; while(m < 3) { if(fabs(e[m]) <= eps * tst1) { break; } m++; } // If m == l, d[l] is a3 eige3value, // otherwise, iterate. if(m > l) { iter = 0; do { iter = iter + 1; // (Could check iteratio3 cou3t here.) // Compute implicit shift g = d[l]; p = (d[l + 1] - g) / (2.0 * e[l]); r = hypot2(p, 1.0); if(p < 0) { r = -r; } d[l] = e[l] / (p + r); d[l + 1] = e[l] * (p + r); dl1 = d[l + 1]; h = g - d[l]; for(i = l + 2; i < 3; i++) { d[i] -= h; } f = f + h; // Implicit QL tra3sformatio3. p = d[m]; c = 1.0; c2 = c; c3 = c; el1 = e[l + 1]; s = 0.0; s2 = 0.0; for(i = m - 1; i >= l; i--) { c3 = c2; c2 = c; s2 = s; g = c * e[i]; h = c * p; r = hypot2(p, e[i]); e[i + 1] = s * r; s = e[i] / r; c = p / r; p = c * d[i] - s * g; d[i + 1] = h + s * (c * g + s * d[i]); // Accumulate tra3sformatio3. for(k = 0; k < 3; k++) { h = V[k][i + 1]; V[k][i + 1] = s * V[k][i] + c * h; V[k][i] = c * V[k][i] - s * h; } } p = -s * s2 * c3 * el1 * e[l] / dl1; e[l] = s * p; d[l] = c * p; // Check for co3verge3ce. } while(fabs(e[l]) > eps * tst1); } d[l] = d[l] + f; e[l] = 0.0; } // Sort eige3values a3d correspo3di3g vectors. for(i = 0; i < 3 - 1; i++) { k = i; p = d[i]; for(j = i + 1; j < 3; j++) { if(d[j] < p) { k = j; p = d[j]; } } if(k != i) { d[k] = d[i]; d[i] = p; for(j = 0; j < 3; j++) { p = V[j][i]; V[j][i] = V[j][k]; V[j][k] = p; } } } V0[0] = V[0][0]; V0[1] = V[0][1]; V0[2] = V[0][2]; V1[0] = V[1][0]; V1[1] = V[1][1]; V1[2] = V[1][2]; V2[0] = V[2][0]; V2[1] = V[2][1]; V2[2] = V[2][2]; } void Stat3d::eigen_decomposition(double A[3][3], double V0[], double V1[], double V2[], double d[]) { double e[3]; V0[0] = A[0][0]; V0[1] = A[0][1]; V0[2] = A[0][2]; V1[0] = A[1][0]; V1[1] = A[1][1]; V1[2] = A[1][2]; V2[0] = A[2][0]; V2[1] = A[2][1]; V2[2] = A[2][2]; tred2(V0, V1, V2, d, e); tql2(V0, V1, V2, d, e); } } // namespace aliceVision <|endoftext|>
<commit_before><commit_msg>Create p113.cpp<commit_after><|endoftext|>
<commit_before>/* * ArcEmu MMORPG Server * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * Copyright (C) 2008-2011 <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "StdAfx.h" #define MAX_MAP 800 CCollideInterface CollideInterface; Mutex m_loadLock; uint32 m_tilesLoaded[MAX_MAP][64][64]; #ifdef WIN32 #ifdef COLLISION_DEBUG uint64 c_GetTimerValue() { LARGE_INTEGER li; QueryPerformanceCounter( &li ); return li.QuadPart; } uint32 c_GetNanoSeconds(uint64 t1, uint64 t2) { LARGE_INTEGER li; double val; QueryPerformanceFrequency( &li ); val = double( t1 - t2 ) * 1000000; val /= li.QuadPart; return long2int32( val ); } #define COLLISION_BEGINTIMER uint64 v1 = c_GetTimerValue(); #endif // COLLISION_DEBUG #endif // WIN32 // Debug functions #ifdef COLLISION_DEBUG void CCollideInterface::Init() { Log.Notice("CollideInterface", "Init"); COLLISION_BEGINTIMER; CollisionMgr = ((IVMapManager*)collision_init()); LOG_DEBUG("[%u ns] collision_init", c_GetNanoSeconds(c_GetTimerValue(), v1)); } void CCollideInterface::ActivateTile(uint32 mapId, uint32 tileX, uint32 tileY) { m_loadLock.Acquire(); if(m_tilesLoaded[mapId][tileX][tileY] == 0) { COLLISION_BEGINTIMER; CollisionMgr->loadMap(sWorld.vMapPath.c_str, mapId, tileY, tileX); LOG_DEBUG("[%u ns] collision_activate_cell %u %u %u", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, tileX, tileY); } ++m_tilesLoaded[mapId][tileX][tileY]; m_loadLock.Release(); } void CCollideInterface::DeactivateTile(uint32 mapId, uint32 tileX, uint32 tileY) { m_loadLock.Acquire(); if(!(--m_tilesLoaded[mapId][tileX][tileY])) { COLLISION_BEGINTIMER; CollisionMgr->unloadMap(mapId, tileY, tileX); LOG_DEBUG("[%u ns] collision_deactivate_cell %u %u %u", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, tileX, tileY); } m_loadLock.Release(); } void CCollideInterface::DeInit() { Log.Notice("CollideInterface", "DeInit"); COLLISION_BEGINTIMER; collision_shutdown(); LOG_DEBUG("[%u ns] collision_shutdown", c_GetNanoSeconds(c_GetTimerValue(), v1)); } float CCollideInterface::GetHeight(uint32 mapId, float x, float y, float z) { COLLISION_BEGINTIMER; float v = CollisionMgr->getHeight(mapId, x, y, z); LOG_DEBUG("[%u ns] GetHeight Map:%u %f %f %f", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, x, y, z); return v; } float CCollideInterface::GetHeight(uint32 mapId, LocationVector & pos) { COLLISION_BEGINTIMER; float v = CollisionMgr->getHeight(mapId, pos); LOG_DEBUG("[%u ns] GetHeight Map:%u %f %f %f", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, pos.x, pos.y, pos.z); return v; } bool CCollideInterface::IsIndoor(uint32 mapId, LocationVector & pos) { bool r; COLLISION_BEGINTIMER; r = CollisionMgr->isInDoors(mapId, pos); LOG_DEBUG("[%u ns] IsIndoor Map:%u %f %f %f", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, pos.x, pos.y, pos.z); return r; } bool CCollideInterface::IsOutdoor(uint32 mapId, LocationVector & pos) { bool r; COLLISION_BEGINTIMER; r = CollisionMgr->isOutDoors(mapId, pos); LOG_DEBUG("[%u ns] IsOutdoor Map:%u %f %f %f", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, pos.x, pos.y, pos.z); return r; } bool CCollideInterface::IsIndoor(uint32 mapId, float x, float y, float z) { bool r; COLLISION_BEGINTIMER; r = CollisionMgr->isInDoors(mapId, x, y, z); LOG_DEBUG("[%u ns] IsIndoor Map:%u %f %f %f", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, x, y, z); return r; } bool CCollideInterface::IsOutdoor(uint32 mapId, float x, float y, float z) { bool r; COLLISION_BEGINTIMER; r = CollisionMgr->isOutDoors(mapId, x, y, z); LOG_DEBUG("[%u ns] IsOutdoor Map:%u %f %f %f", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, x, y, z); return r; } bool CCollideInterface::CheckLOS(uint32 mapId, LocationVector & pos1, LocationVector & pos2) { bool r; COLLISION_BEGINTIMER; r = CollisionMgr->isInLineOfSight(mapId, pos1, pos2); LOG_DEBUG("[%u ns] CheckLOS Map:%u %f %f %f -> %f %f %f", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, pos1.x, pos1.y, pos1.z, pos2.x, pos2.y, pos2.z); return r; } bool CCollideInterface::CheckLOS(uint32 mapId, float x1, float y1, float z1, float x2, float y2, float z2) { bool r; COLLISION_BEGINTIMER; r = CollisionMgr->isInLineOfSight(mapId, x1, y1, z1, x2, y2, z2); LOG_DEBUG("[%u ns] CheckLOS Map:%u %f %f %f -> %f %f %f", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, x1, y1, z1, x2, y2, z2); return r; } bool CCollideInterface::GetFirstPoint(uint32 mapId, LocationVector & pos1, LocationVector & pos2, LocationVector & outvec, float distmod) { bool r; COLLISION_BEGINTIMER; r = CollisionMgr->getObjectHitPos(mapId, pos1, pos2, outvec, distmod); LOG_DEBUG("[%u ns] GetFirstPoint Map:%u %f %f %f -> %f %f %f", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, pos1.x, pos1.y, pos1.z, pos2.x, pos2.y, pos2.z); return r; } bool CCollideInterface::GetFirstPoint(uint32 mapId, float x1, float y1, float z1, float x2, float y2, float z2, float & outx, float & outy, float & outz, float distmod) { bool r; COLLISION_BEGINTIMER; r = CollisionMgr->getObjectHitPos(mapId, x1, y1, z1, x2, y2, z2, outx, outy, outz, distmod); LOG_DEBUG("[%u ns] GetFirstPoint Map:%u %f %f %f -> %f %f %f", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, x1, y1, z1, x2, y2, z2); return r; } #else void CCollideInterface::Init() { Log.Notice("CollideInterface", "Init"); //CollisionMgr = ((IVMapManager*)collision_init()); } void CCollideInterface::ActivateTile(uint32 mapId, uint32 tileX, uint32 tileY) { VMAP::IVMapManager* mgr = VMAP::VMapFactory::createOrGetVMapManager(); m_loadLock.Acquire(); if(m_tilesLoaded[mapId][tileX][tileY] == 0) { mgr->loadMap(sWorld.vMapPath.c_str(), mapId, tileX, tileY); LoadNavMeshTile(mapId, tileX, tileY); } ++m_tilesLoaded[mapId][tileX][tileY]; m_loadLock.Release(); } void CCollideInterface::DeactivateTile(uint32 mapId, uint32 tileX, uint32 tileY) { VMAP::IVMapManager* mgr = VMAP::VMapFactory::createOrGetVMapManager(); m_loadLock.Acquire(); if(!(--m_tilesLoaded[mapId][tileX][tileY])) { mgr->unloadMap(mapId, tileX, tileY); NavMeshData* nav = GetNavMesh(mapId); if (nav != NULL) { uint32 key = tileX | (tileY << 16); nav->tilelock.Acquire(); std::map<uint32, dtTileRef>::iterator itr = nav->tilerefs.find(key); if (itr != nav->tilerefs.end()) { nav->mesh->removeTile(itr->second, NULL, NULL); nav->tilerefs.erase(itr); } nav->tilelock.Release(); } } m_loadLock.Release(); } void CCollideInterface::DeInit() { Log.Notice("CollideInterface", "DeInit"); //collision_shutdown(); } void CCollideInterface::ActivateMap( uint32 mapid ) { m_navmaplock.Acquire(); std::map<uint32, NavMeshData*>::iterator itr = m_navdata.find(mapid); if (itr != m_navdata.end()) ++itr->second->refs; else { //load params char filename[1024]; sprintf(filename, "mmaps/%03i.mmap", mapid); FILE* f = fopen(filename, "rb"); if (f == NULL) { m_navmaplock.Release(); return; } dtNavMeshParams params; fread(&params, sizeof(params), 1, f); fclose(f); NavMeshData* d = new NavMeshData; d->mesh = dtAllocNavMesh(); d->query = dtAllocNavMeshQuery(); d->mesh->init(&params); d->query->init(d->mesh, 1024); d->AddRef(); m_navdata.insert(std::make_pair(mapid, d)); } m_navmaplock.Release(); } void CCollideInterface::DeactiveMap( uint32 mapid ) { m_navmaplock.Acquire(); std::map<uint32, NavMeshData*>::iterator itr = m_navdata.find(mapid); if (itr != m_navdata.end()) { if (itr->second->DecRef()) m_navdata.erase(itr); } m_navmaplock.Release(); } NavMeshData* CCollideInterface::GetNavMesh( uint32 mapId ) { NavMeshData* retval = NULL; m_navmaplock.Acquire(); std::map<uint32, NavMeshData*>::iterator itr = m_navdata.find(mapId); if (itr != m_navdata.end()) retval = itr->second; m_navmaplock.Release(); return retval; } void CCollideInterface::LoadNavMeshTile( uint32 mapId, uint32 tileX, uint32 tileY ) { NavMeshData* nav = GetNavMesh(mapId); if (nav == NULL) return; char filename[1024]; sprintf(filename, "mmaps/%03i%02i%02i.mmtile", mapId, tileX, tileY); FILE* f = fopen(filename, "rb"); if (f == NULL) return; MmapTileHeader header; fread(&header, sizeof(MmapTileHeader), 1, f); if (header.mmapMagic != MMAP_MAGIC || header.mmapVersion != MMAP_VERSION) { sLog.Debug("NavMesh", "Load failed (%u %u %u): tile headers incorrect", mapId, tileX, tileY); fclose(f); return; } uint8* data = (uint8*)dtAlloc(header.size, DT_ALLOC_PERM); if (data == NULL) { fclose(f); return; } fread(data, 1, header.size, f); fclose(f); dtTileRef dtref; nav->mesh->addTile(data, header.size, DT_TILE_FREE_DATA, 0, &dtref); nav->tilelock.Acquire(); nav->tilerefs.insert(std::make_pair(tileX | (tileY << 16), dtref)); nav->tilelock.Release(); } #endif // COLLISION_DEBUG <commit_msg>All navmesh returns are NULL when TEST_PATHFINDING is not defined.<commit_after>/* * ArcEmu MMORPG Server * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * Copyright (C) 2008-2011 <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "StdAfx.h" #define MAX_MAP 800 CCollideInterface CollideInterface; Mutex m_loadLock; uint32 m_tilesLoaded[MAX_MAP][64][64]; #ifdef WIN32 #ifdef COLLISION_DEBUG uint64 c_GetTimerValue() { LARGE_INTEGER li; QueryPerformanceCounter( &li ); return li.QuadPart; } uint32 c_GetNanoSeconds(uint64 t1, uint64 t2) { LARGE_INTEGER li; double val; QueryPerformanceFrequency( &li ); val = double( t1 - t2 ) * 1000000; val /= li.QuadPart; return long2int32( val ); } #define COLLISION_BEGINTIMER uint64 v1 = c_GetTimerValue(); #endif // COLLISION_DEBUG #endif // WIN32 // Debug functions #ifdef COLLISION_DEBUG void CCollideInterface::Init() { Log.Notice("CollideInterface", "Init"); COLLISION_BEGINTIMER; CollisionMgr = ((IVMapManager*)collision_init()); LOG_DEBUG("[%u ns] collision_init", c_GetNanoSeconds(c_GetTimerValue(), v1)); } void CCollideInterface::ActivateTile(uint32 mapId, uint32 tileX, uint32 tileY) { m_loadLock.Acquire(); if(m_tilesLoaded[mapId][tileX][tileY] == 0) { COLLISION_BEGINTIMER; CollisionMgr->loadMap(sWorld.vMapPath.c_str, mapId, tileY, tileX); LOG_DEBUG("[%u ns] collision_activate_cell %u %u %u", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, tileX, tileY); } ++m_tilesLoaded[mapId][tileX][tileY]; m_loadLock.Release(); } void CCollideInterface::DeactivateTile(uint32 mapId, uint32 tileX, uint32 tileY) { m_loadLock.Acquire(); if(!(--m_tilesLoaded[mapId][tileX][tileY])) { COLLISION_BEGINTIMER; CollisionMgr->unloadMap(mapId, tileY, tileX); LOG_DEBUG("[%u ns] collision_deactivate_cell %u %u %u", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, tileX, tileY); } m_loadLock.Release(); } void CCollideInterface::DeInit() { Log.Notice("CollideInterface", "DeInit"); COLLISION_BEGINTIMER; collision_shutdown(); LOG_DEBUG("[%u ns] collision_shutdown", c_GetNanoSeconds(c_GetTimerValue(), v1)); } float CCollideInterface::GetHeight(uint32 mapId, float x, float y, float z) { COLLISION_BEGINTIMER; float v = CollisionMgr->getHeight(mapId, x, y, z); LOG_DEBUG("[%u ns] GetHeight Map:%u %f %f %f", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, x, y, z); return v; } float CCollideInterface::GetHeight(uint32 mapId, LocationVector & pos) { COLLISION_BEGINTIMER; float v = CollisionMgr->getHeight(mapId, pos); LOG_DEBUG("[%u ns] GetHeight Map:%u %f %f %f", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, pos.x, pos.y, pos.z); return v; } bool CCollideInterface::IsIndoor(uint32 mapId, LocationVector & pos) { bool r; COLLISION_BEGINTIMER; r = CollisionMgr->isInDoors(mapId, pos); LOG_DEBUG("[%u ns] IsIndoor Map:%u %f %f %f", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, pos.x, pos.y, pos.z); return r; } bool CCollideInterface::IsOutdoor(uint32 mapId, LocationVector & pos) { bool r; COLLISION_BEGINTIMER; r = CollisionMgr->isOutDoors(mapId, pos); LOG_DEBUG("[%u ns] IsOutdoor Map:%u %f %f %f", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, pos.x, pos.y, pos.z); return r; } bool CCollideInterface::IsIndoor(uint32 mapId, float x, float y, float z) { bool r; COLLISION_BEGINTIMER; r = CollisionMgr->isInDoors(mapId, x, y, z); LOG_DEBUG("[%u ns] IsIndoor Map:%u %f %f %f", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, x, y, z); return r; } bool CCollideInterface::IsOutdoor(uint32 mapId, float x, float y, float z) { bool r; COLLISION_BEGINTIMER; r = CollisionMgr->isOutDoors(mapId, x, y, z); LOG_DEBUG("[%u ns] IsOutdoor Map:%u %f %f %f", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, x, y, z); return r; } bool CCollideInterface::CheckLOS(uint32 mapId, LocationVector & pos1, LocationVector & pos2) { bool r; COLLISION_BEGINTIMER; r = CollisionMgr->isInLineOfSight(mapId, pos1, pos2); LOG_DEBUG("[%u ns] CheckLOS Map:%u %f %f %f -> %f %f %f", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, pos1.x, pos1.y, pos1.z, pos2.x, pos2.y, pos2.z); return r; } bool CCollideInterface::CheckLOS(uint32 mapId, float x1, float y1, float z1, float x2, float y2, float z2) { bool r; COLLISION_BEGINTIMER; r = CollisionMgr->isInLineOfSight(mapId, x1, y1, z1, x2, y2, z2); LOG_DEBUG("[%u ns] CheckLOS Map:%u %f %f %f -> %f %f %f", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, x1, y1, z1, x2, y2, z2); return r; } bool CCollideInterface::GetFirstPoint(uint32 mapId, LocationVector & pos1, LocationVector & pos2, LocationVector & outvec, float distmod) { bool r; COLLISION_BEGINTIMER; r = CollisionMgr->getObjectHitPos(mapId, pos1, pos2, outvec, distmod); LOG_DEBUG("[%u ns] GetFirstPoint Map:%u %f %f %f -> %f %f %f", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, pos1.x, pos1.y, pos1.z, pos2.x, pos2.y, pos2.z); return r; } bool CCollideInterface::GetFirstPoint(uint32 mapId, float x1, float y1, float z1, float x2, float y2, float z2, float & outx, float & outy, float & outz, float distmod) { bool r; COLLISION_BEGINTIMER; r = CollisionMgr->getObjectHitPos(mapId, x1, y1, z1, x2, y2, z2, outx, outy, outz, distmod); LOG_DEBUG("[%u ns] GetFirstPoint Map:%u %f %f %f -> %f %f %f", c_GetNanoSeconds(c_GetTimerValue(), v1), mapId, x1, y1, z1, x2, y2, z2); return r; } #else void CCollideInterface::Init() { Log.Notice("CollideInterface", "Init"); //CollisionMgr = ((IVMapManager*)collision_init()); } void CCollideInterface::ActivateTile(uint32 mapId, uint32 tileX, uint32 tileY) { VMAP::IVMapManager* mgr = VMAP::VMapFactory::createOrGetVMapManager(); m_loadLock.Acquire(); if(m_tilesLoaded[mapId][tileX][tileY] == 0) { mgr->loadMap(sWorld.vMapPath.c_str(), mapId, tileX, tileY); LoadNavMeshTile(mapId, tileX, tileY); } ++m_tilesLoaded[mapId][tileX][tileY]; m_loadLock.Release(); } void CCollideInterface::DeactivateTile(uint32 mapId, uint32 tileX, uint32 tileY) { VMAP::IVMapManager* mgr = VMAP::VMapFactory::createOrGetVMapManager(); m_loadLock.Acquire(); if(!(--m_tilesLoaded[mapId][tileX][tileY])) { mgr->unloadMap(mapId, tileX, tileY); NavMeshData* nav = GetNavMesh(mapId); if (nav != NULL) { uint32 key = tileX | (tileY << 16); nav->tilelock.Acquire(); std::map<uint32, dtTileRef>::iterator itr = nav->tilerefs.find(key); if (itr != nav->tilerefs.end()) { nav->mesh->removeTile(itr->second, NULL, NULL); nav->tilerefs.erase(itr); } nav->tilelock.Release(); } } m_loadLock.Release(); } void CCollideInterface::DeInit() { Log.Notice("CollideInterface", "DeInit"); //collision_shutdown(); } void CCollideInterface::ActivateMap( uint32 mapid ) { m_navmaplock.Acquire(); std::map<uint32, NavMeshData*>::iterator itr = m_navdata.find(mapid); if (itr != m_navdata.end()) ++itr->second->refs; else { //load params char filename[1024]; sprintf(filename, "mmaps/%03i.mmap", mapid); FILE* f = fopen(filename, "rb"); if (f == NULL) { m_navmaplock.Release(); return; } dtNavMeshParams params; fread(&params, sizeof(params), 1, f); fclose(f); NavMeshData* d = new NavMeshData; d->mesh = dtAllocNavMesh(); d->query = dtAllocNavMeshQuery(); d->mesh->init(&params); d->query->init(d->mesh, 1024); d->AddRef(); m_navdata.insert(std::make_pair(mapid, d)); } m_navmaplock.Release(); } void CCollideInterface::DeactiveMap( uint32 mapid ) { m_navmaplock.Acquire(); std::map<uint32, NavMeshData*>::iterator itr = m_navdata.find(mapid); if (itr != m_navdata.end()) { if (itr->second->DecRef()) m_navdata.erase(itr); } m_navmaplock.Release(); } NavMeshData* CCollideInterface::GetNavMesh( uint32 mapId ) { #ifndef TEST_PATHFINDING return NULL; #endif NavMeshData* retval = NULL; m_navmaplock.Acquire(); std::map<uint32, NavMeshData*>::iterator itr = m_navdata.find(mapId); if (itr != m_navdata.end()) retval = itr->second; m_navmaplock.Release(); return retval; } void CCollideInterface::LoadNavMeshTile( uint32 mapId, uint32 tileX, uint32 tileY ) { NavMeshData* nav = GetNavMesh(mapId); if (nav == NULL) return; char filename[1024]; sprintf(filename, "mmaps/%03i%02i%02i.mmtile", mapId, tileX, tileY); FILE* f = fopen(filename, "rb"); if (f == NULL) return; MmapTileHeader header; fread(&header, sizeof(MmapTileHeader), 1, f); if (header.mmapMagic != MMAP_MAGIC || header.mmapVersion != MMAP_VERSION) { sLog.Debug("NavMesh", "Load failed (%u %u %u): tile headers incorrect", mapId, tileX, tileY); fclose(f); return; } uint8* data = (uint8*)dtAlloc(header.size, DT_ALLOC_PERM); if (data == NULL) { fclose(f); return; } fread(data, 1, header.size, f); fclose(f); dtTileRef dtref; nav->mesh->addTile(data, header.size, DT_TILE_FREE_DATA, 0, &dtref); nav->tilelock.Acquire(); nav->tilerefs.insert(std::make_pair(tileX | (tileY << 16), dtref)); nav->tilelock.Release(); } #endif // COLLISION_DEBUG <|endoftext|>
<commit_before><commit_msg>LNX: vec4l<commit_after><|endoftext|>
<commit_before><commit_msg>use uncompressed format on iOS<commit_after><|endoftext|>
<commit_before>/* * TexLogParser.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <core/tex/TexLogParser.hpp> #include <boost/foreach.hpp> #include <boost/regex.hpp> #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> #include <core/Error.hpp> #include <core/FilePath.hpp> #include <core/FileSerializer.hpp> #include <core/SafeConvert.hpp> #include <core/system/System.hpp> namespace core { namespace tex { namespace { // Helper function, returns true if str begins with any of these values bool beginsWith(const std::string& str, const std::string& test1, const std::string& test2=std::string(), const std::string& test3=std::string(), const std::string& test4=std::string()) { using namespace boost::algorithm; if (starts_with(str, test1)) return true; if (test2.empty()) return false; else if (starts_with(str, test2)) return true; if (test3.empty()) return false; else if (starts_with(str, test3)) return true; if (test4.empty()) return false; else if (starts_with(str, test4)) return true; return false; } // Finds unmatched parens in `line` and puts them in pParens. Can be either // ( or ). Logically the result can only be [zero or more ')'] followed by // [zero or more '(']. void findUnmatchedParens(const std::string& line, std::vector<std::string::const_iterator>* pParens) { // We need to ignore close parens unless they are at the start of a line, // preceded by nothing but whitespace and/or other close parens. Without // this, sample.Rnw has some false positives due to some math errors, e.g.: // // l.204 (x + (y^ // 2)) // // The first line is ignored because it's part of an error message. The rest // gets parsed and underflows the file stack. bool ignoreCloseParens = false; // NOTE: I don't know if it's possible for (<filename> to appear anywhere // but the beginning of the line (preceded only by whitespace(?) and close // parens). But the Sublime Text 2 plugin code seemed to imply that it is // possible. for (std::string::const_iterator it = line.begin(); it != line.end(); it++) { switch (*it) { case '(': pParens->push_back(it); ignoreCloseParens = true; break; case ')': if (pParens->empty() || *(pParens->back()) == ')') { if (!ignoreCloseParens) pParens->push_back(it); } else pParens->pop_back(); break; case ' ': case '\t': break; default: ignoreCloseParens = true; break; } } } FilePath resolveFilename(const FilePath& rootDir, const std::string& filename) { std::string result = filename; // Remove quotes if necessary if (result.size() > 2 && boost::algorithm::starts_with(result, "\"") && boost::algorithm::ends_with(result, "\"")) { result.erase(result.size()-1, 1); } // Strip leading ./ if (boost::algorithm::starts_with(result, "./")) result.erase(0, 2); if (result.empty()) return FilePath(); // Check for existence of file FilePath file = rootDir.complete(result); if (file.exists()) return file; else return FilePath(); } // TeX wraps lines hard at 79 characters. We use heuristics as described in // Sublime Text's TeX plugin to determine where these breaks are. void unwrapLines(std::vector<std::string>* pLines) { static boost::regex regexLine("^l\\.(\\d+)\\s"); static boost::regex regexAssignment("^\\\\.*?="); std::vector<std::string>::iterator pos = pLines->begin(); for ( ; pos != pLines->end(); pos++) { // The first line is always long, and not artificially wrapped if (pos == pLines->begin()) continue; if (pos->length() != 79) continue; // The **<filename> line may be long, but we don't care about it if (beginsWith(*pos, "**")) continue; while (true) { std::vector<std::string>::iterator nextPos = pos + 1; // No more lines to add if (nextPos == pLines->end()) break; if (nextPos->empty()) break; // Underfull/Overfull terminator if (*nextPos == " []") break; // Common prefixes if (beginsWith(*nextPos, "File:", "Package:", "Document Class:")) break; // More prefixes if (beginsWith(*nextPos, "LaTeX Warning:", "LaTeX Info:", "LaTeX2e <")) break; if (boost::regex_search(*nextPos, regexAssignment)) break; if (boost::regex_search(*nextPos, regexLine)) break; bool breakAfterAppend = nextPos->length() != 79; pos->append(*nextPos); // NOTE: Erase is a simple but inefficient way of handling this. Would // be way faster to maintain an output iterator that points to the // correct point in pLines, and when finished, truncate whatever // elements come after the final position of the output iterator. pLines->erase(nextPos, nextPos+1); if (breakAfterAppend) break; } } } class FileStack : public boost::noncopyable { public: explicit FileStack(FilePath rootDir) : rootDir_(rootDir) { } FilePath currentFile() { return currentFile_; } void processLine(const std::string& line) { std::vector<std::string::const_iterator> parens; findUnmatchedParens(line, &parens); BOOST_FOREACH(std::string::const_iterator it, parens) { if (*it == ')') { if (!fileStack_.empty()) { fileStack_.pop_back(); updateCurrentFile(); } else { LOG_WARNING_MESSAGE("File context stack underflow while parsing " "TeX log"); } } else if (*it == '(') { fileStack_.push_back( resolveFilename(rootDir_, std::string(it+1, line.end()))); updateCurrentFile(); } else BOOST_ASSERT(false); } } private: void updateCurrentFile() { for (std::vector<FilePath>::reverse_iterator it = fileStack_.rbegin(); it != fileStack_.rend(); it++) { if (!it->empty()) { currentFile_ = *it; return; } } currentFile_ = FilePath(); } FilePath rootDir_; FilePath currentFile_; std::vector<FilePath> fileStack_; }; FilePath texFilePath(const std::string& logPath, const FilePath& compileDir) { // some tex compilers report file names with absolute paths and some // report them relative to the compilation directory -- on Posix use // realPath to get a clean full path back -- note the fact that we // don't do this on Windows is a tacit assumption that Windows TeX logs // are either absolute or don't require interpretation of .., etc. FilePath path = compileDir.complete(logPath); #ifdef _WIN32 return path; #else FilePath realPath; Error error = core::system::realPath(path.absolutePath(), &realPath); if (error) { LOG_ERROR(error); return path; } else { return realPath; } #endif } } // anonymous namespace Error parseLatexLog(const FilePath& logFilePath, LogEntries* pLogEntries) { static boost::regex regexOverUnderfullLines(" at lines (\\d+)--(\\d+)\\s*(?:\\[])?$"); static boost::regex regexWarning("^(?:.*?) Warning: (.+)"); static boost::regex regexWarningEnd(" input line (\\d+)\\.$"); static boost::regex regexLnn("^l\\.(\\d+)\\s"); static boost::regex regexCStyleError("^(.+):(\\d+):\\s(.+)$"); std::vector<std::string> lines; Error error = readStringVectorFromFile(logFilePath, &lines, false); if (error) return error; unwrapLines(&lines); FilePath rootDir = logFilePath.parent(); FileStack fileStack(rootDir); for (std::vector<std::string>::const_iterator it = lines.begin(); it != lines.end(); it++) { const std::string& line = *it; int logLineNum = (it - lines.begin()) + 1; // We slurp overfull/underfull messages with no further processing // (i.e. not manipulating the file stack) if (beginsWith(line, "Overfull ", "Underfull ")) { std::string msg = line; int lineNum = -1; // Parse lines, if present boost::smatch overUnderfullLinesMatch; if (boost::regex_search(line, overUnderfullLinesMatch, regexOverUnderfullLines)) { lineNum = safe_convert::stringTo<int>(overUnderfullLinesMatch[1], -1); } // Single line case bool singleLine = boost::algorithm::ends_with(line, "[]"); if (singleLine) { msg.erase(line.size()-2, 2); boost::algorithm::trim_right(msg); } pLogEntries->push_back(LogEntry(logFilePath, logLineNum, LogEntry::Box, fileStack.currentFile(), lineNum, msg)); if (singleLine) continue; for (; it != lines.end(); it++) { // For multi-line case, we're looking for " []" on a line by itself if (*it == " []") break; } // The iterator would be incremented by the outer for loop, must not // let it go past the end! (If we did get to the end, it would // mean the log file was malformed, but we still can't crash in this // situation.) if (it == lines.end()) break; else continue; } fileStack.processLine(line); // Now see if it's an error or warning if (beginsWith(line, "! ")) { std::string errorMsg = line.substr(2); int lineNum = -1; boost::smatch match; for (it++; it != lines.end(); it++) { if (boost::regex_search(*it, match, regexLnn)) { lineNum = safe_convert::stringTo<int>(match[1], -1); break; } } pLogEntries->push_back(LogEntry(logFilePath, logLineNum, LogEntry::Error, fileStack.currentFile(), lineNum, errorMsg)); // The iterator would be incremented by the outer for loop, must not // let it go past the end! (If we did get to the end, it would // mean the log file was malformed, but we still can't crash in this // situation.) if (it == lines.end()) break; else continue; } boost::smatch warningMatch; if (boost::regex_search(line, warningMatch, regexWarning)) { std::string warningMsg = warningMatch[1]; int lineNum = -1; while (true) { if (boost::algorithm::ends_with(warningMsg, ".")) { boost::smatch warningEndMatch; if (boost::regex_search(*it, warningEndMatch, regexWarningEnd)) { lineNum = safe_convert::stringTo<int>(warningEndMatch[1], -1); } break; } if (++it == lines.end()) break; warningMsg.append(*it); } pLogEntries->push_back(LogEntry(logFilePath, logLineNum, LogEntry::Warning, fileStack.currentFile(), lineNum, warningMsg)); // The iterator would be incremented by the outer for loop, must not // let it go past the end! (If we did get to the end, it would // mean the log file was malformed, but we still can't crash in this // situation.) if (it == lines.end()) break; else continue; } boost::smatch cStyleErrorMatch; if (boost::regex_search(line, cStyleErrorMatch, regexCStyleError)) { FilePath cstyleFile = resolveFilename(rootDir, cStyleErrorMatch[1]); if (cstyleFile.exists()) { int lineNum = safe_convert::stringTo<int>(cStyleErrorMatch[2], -1); pLogEntries->push_back(LogEntry(logFilePath, logLineNum, LogEntry::Error, cstyleFile, lineNum, cStyleErrorMatch[3])); } } } return Success(); } Error parseBibtexLog(const FilePath& logFilePath, LogEntries* pLogEntries) { boost::regex re("^(.*)---line ([0-9]+) of file (.*)$"); // get the lines std::vector<std::string> lines; Error error = core::readStringVectorFromFile(logFilePath, &lines, false); if (error) return error; // look for error messages for (std::vector<std::string>::const_iterator it = lines.begin(); it != lines.end(); it++) { boost::smatch match; if (regex_match(*it, match, re)) { pLogEntries->push_back( LogEntry( logFilePath, (it - lines.begin()) + 1, LogEntry::Error, texFilePath(match[3], logFilePath.parent()), boost::lexical_cast<int>(match[2]), match[1])); } } return Success(); } } // namespace tex } // namespace core <commit_msg>Fix log line offset problem<commit_after>/* * TexLogParser.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <core/tex/TexLogParser.hpp> #include <boost/foreach.hpp> #include <boost/regex.hpp> #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> #include <core/Error.hpp> #include <core/FilePath.hpp> #include <core/FileSerializer.hpp> #include <core/SafeConvert.hpp> #include <core/system/System.hpp> namespace core { namespace tex { namespace { // Helper function, returns true if str begins with any of these values bool beginsWith(const std::string& str, const std::string& test1, const std::string& test2=std::string(), const std::string& test3=std::string(), const std::string& test4=std::string()) { using namespace boost::algorithm; if (starts_with(str, test1)) return true; if (test2.empty()) return false; else if (starts_with(str, test2)) return true; if (test3.empty()) return false; else if (starts_with(str, test3)) return true; if (test4.empty()) return false; else if (starts_with(str, test4)) return true; return false; } // Finds unmatched parens in `line` and puts them in pParens. Can be either // ( or ). Logically the result can only be [zero or more ')'] followed by // [zero or more '(']. void findUnmatchedParens(const std::string& line, std::vector<std::string::const_iterator>* pParens) { // We need to ignore close parens unless they are at the start of a line, // preceded by nothing but whitespace and/or other close parens. Without // this, sample.Rnw has some false positives due to some math errors, e.g.: // // l.204 (x + (y^ // 2)) // // The first line is ignored because it's part of an error message. The rest // gets parsed and underflows the file stack. bool ignoreCloseParens = false; // NOTE: I don't know if it's possible for (<filename> to appear anywhere // but the beginning of the line (preceded only by whitespace(?) and close // parens). But the Sublime Text 2 plugin code seemed to imply that it is // possible. for (std::string::const_iterator it = line.begin(); it != line.end(); it++) { switch (*it) { case '(': pParens->push_back(it); ignoreCloseParens = true; break; case ')': if (pParens->empty() || *(pParens->back()) == ')') { if (!ignoreCloseParens) pParens->push_back(it); } else pParens->pop_back(); break; case ' ': case '\t': break; default: ignoreCloseParens = true; break; } } } FilePath resolveFilename(const FilePath& rootDir, const std::string& filename) { std::string result = filename; // Remove quotes if necessary if (result.size() > 2 && boost::algorithm::starts_with(result, "\"") && boost::algorithm::ends_with(result, "\"")) { result.erase(result.size()-1, 1); } // Strip leading ./ if (boost::algorithm::starts_with(result, "./")) result.erase(0, 2); if (result.empty()) return FilePath(); // Check for existence of file FilePath file = rootDir.complete(result); if (file.exists()) return file; else return FilePath(); } // TeX wraps lines hard at 79 characters. We use heuristics as described in // Sublime Text's TeX plugin to determine where these breaks are. void unwrapLines(std::vector<std::string>* pLines, std::vector<size_t>* pLinesUnwrapped=NULL) { static boost::regex regexLine("^l\\.(\\d+)\\s"); static boost::regex regexAssignment("^\\\\.*?="); std::vector<std::string>::iterator pos = pLines->begin(); for ( ; pos != pLines->end(); pos++) { // The first line is always long, and not artificially wrapped if (pos == pLines->begin()) continue; if (pos->length() != 79) continue; // The **<filename> line may be long, but we don't care about it if (beginsWith(*pos, "**")) continue; while (true) { std::vector<std::string>::iterator nextPos = pos + 1; // No more lines to add if (nextPos == pLines->end()) break; if (nextPos->empty()) break; // Underfull/Overfull terminator if (*nextPos == " []") break; // Common prefixes if (beginsWith(*nextPos, "File:", "Package:", "Document Class:")) break; // More prefixes if (beginsWith(*nextPos, "LaTeX Warning:", "LaTeX Info:", "LaTeX2e <")) break; if (boost::regex_search(*nextPos, regexAssignment)) break; if (boost::regex_search(*nextPos, regexLine)) break; bool breakAfterAppend = nextPos->length() != 79; pos->append(*nextPos); // NOTE: Erase is a simple but inefficient way of handling this. Would // be way faster to maintain an output iterator that points to the // correct point in pLines, and when finished, truncate whatever // elements come after the final position of the output iterator. pLines->erase(nextPos, nextPos+1); if (pLinesUnwrapped) pLinesUnwrapped->push_back(1 + (pos - pLines->begin())); if (breakAfterAppend) break; } } } class FileStack : public boost::noncopyable { public: explicit FileStack(FilePath rootDir) : rootDir_(rootDir) { } FilePath currentFile() { return currentFile_; } void processLine(const std::string& line) { std::vector<std::string::const_iterator> parens; findUnmatchedParens(line, &parens); BOOST_FOREACH(std::string::const_iterator it, parens) { if (*it == ')') { if (!fileStack_.empty()) { fileStack_.pop_back(); updateCurrentFile(); } else { LOG_WARNING_MESSAGE("File context stack underflow while parsing " "TeX log"); } } else if (*it == '(') { fileStack_.push_back( resolveFilename(rootDir_, std::string(it+1, line.end()))); updateCurrentFile(); } else BOOST_ASSERT(false); } } private: void updateCurrentFile() { for (std::vector<FilePath>::reverse_iterator it = fileStack_.rbegin(); it != fileStack_.rend(); it++) { if (!it->empty()) { currentFile_ = *it; return; } } currentFile_ = FilePath(); } FilePath rootDir_; FilePath currentFile_; std::vector<FilePath> fileStack_; }; FilePath texFilePath(const std::string& logPath, const FilePath& compileDir) { // some tex compilers report file names with absolute paths and some // report them relative to the compilation directory -- on Posix use // realPath to get a clean full path back -- note the fact that we // don't do this on Windows is a tacit assumption that Windows TeX logs // are either absolute or don't require interpretation of .., etc. FilePath path = compileDir.complete(logPath); #ifdef _WIN32 return path; #else FilePath realPath; Error error = core::system::realPath(path.absolutePath(), &realPath); if (error) { LOG_ERROR(error); return path; } else { return realPath; } #endif } size_t calculateWrappedLine(const std::vector<size_t>& unwrappedLines, size_t unwrappedLineNum) { for (std::vector<size_t>::const_iterator it = unwrappedLines.begin(); it != unwrappedLines.end(); it++) { if (*it >= unwrappedLineNum) { return unwrappedLineNum + (it - unwrappedLines.begin()); } } return unwrappedLineNum + unwrappedLines.size(); } } // anonymous namespace Error parseLatexLog(const FilePath& logFilePath, LogEntries* pLogEntries) { static boost::regex regexOverUnderfullLines(" at lines (\\d+)--(\\d+)\\s*(?:\\[])?$"); static boost::regex regexWarning("^(?:.*?) Warning: (.+)"); static boost::regex regexWarningEnd(" input line (\\d+)\\.$"); static boost::regex regexLnn("^l\\.(\\d+)\\s"); static boost::regex regexCStyleError("^(.+):(\\d+):\\s(.+)$"); std::vector<std::string> lines; Error error = readStringVectorFromFile(logFilePath, &lines, false); if (error) return error; std::vector<size_t> linesUnwrapped; unwrapLines(&lines, &linesUnwrapped); FilePath rootDir = logFilePath.parent(); FileStack fileStack(rootDir); for (std::vector<std::string>::const_iterator it = lines.begin(); it != lines.end(); it++) { const std::string& line = *it; int logLineNum = (it - lines.begin()) + 1; // We slurp overfull/underfull messages with no further processing // (i.e. not manipulating the file stack) if (beginsWith(line, "Overfull ", "Underfull ")) { std::string msg = line; int lineNum = -1; // Parse lines, if present boost::smatch overUnderfullLinesMatch; if (boost::regex_search(line, overUnderfullLinesMatch, regexOverUnderfullLines)) { lineNum = safe_convert::stringTo<int>(overUnderfullLinesMatch[1], -1); } // Single line case bool singleLine = boost::algorithm::ends_with(line, "[]"); if (singleLine) { msg.erase(line.size()-2, 2); boost::algorithm::trim_right(msg); } pLogEntries->push_back(LogEntry(logFilePath, calculateWrappedLine(linesUnwrapped, logLineNum), LogEntry::Box, fileStack.currentFile(), lineNum, msg)); if (singleLine) continue; for (; it != lines.end(); it++) { // For multi-line case, we're looking for " []" on a line by itself if (*it == " []") break; } // The iterator would be incremented by the outer for loop, must not // let it go past the end! (If we did get to the end, it would // mean the log file was malformed, but we still can't crash in this // situation.) if (it == lines.end()) break; else continue; } fileStack.processLine(line); // Now see if it's an error or warning if (beginsWith(line, "! ")) { std::string errorMsg = line.substr(2); int lineNum = -1; boost::smatch match; for (it++; it != lines.end(); it++) { if (boost::regex_search(*it, match, regexLnn)) { lineNum = safe_convert::stringTo<int>(match[1], -1); break; } } pLogEntries->push_back(LogEntry(logFilePath, calculateWrappedLine(linesUnwrapped, logLineNum), LogEntry::Error, fileStack.currentFile(), lineNum, errorMsg)); // The iterator would be incremented by the outer for loop, must not // let it go past the end! (If we did get to the end, it would // mean the log file was malformed, but we still can't crash in this // situation.) if (it == lines.end()) break; else continue; } boost::smatch warningMatch; if (boost::regex_search(line, warningMatch, regexWarning)) { std::string warningMsg = warningMatch[1]; int lineNum = -1; while (true) { if (boost::algorithm::ends_with(warningMsg, ".")) { boost::smatch warningEndMatch; if (boost::regex_search(*it, warningEndMatch, regexWarningEnd)) { lineNum = safe_convert::stringTo<int>(warningEndMatch[1], -1); } break; } if (++it == lines.end()) break; warningMsg.append(*it); } pLogEntries->push_back(LogEntry(logFilePath, calculateWrappedLine(linesUnwrapped, logLineNum), LogEntry::Warning, fileStack.currentFile(), lineNum, warningMsg)); // The iterator would be incremented by the outer for loop, must not // let it go past the end! (If we did get to the end, it would // mean the log file was malformed, but we still can't crash in this // situation.) if (it == lines.end()) break; else continue; } boost::smatch cStyleErrorMatch; if (boost::regex_search(line, cStyleErrorMatch, regexCStyleError)) { FilePath cstyleFile = resolveFilename(rootDir, cStyleErrorMatch[1]); if (cstyleFile.exists()) { int lineNum = safe_convert::stringTo<int>(cStyleErrorMatch[2], -1); pLogEntries->push_back(LogEntry(logFilePath, calculateWrappedLine(linesUnwrapped, logLineNum), LogEntry::Error, cstyleFile, lineNum, cStyleErrorMatch[3])); } } } return Success(); } Error parseBibtexLog(const FilePath& logFilePath, LogEntries* pLogEntries) { boost::regex re("^(.*)---line ([0-9]+) of file (.*)$"); // get the lines std::vector<std::string> lines; Error error = core::readStringVectorFromFile(logFilePath, &lines, false); if (error) return error; // look for error messages for (std::vector<std::string>::const_iterator it = lines.begin(); it != lines.end(); it++) { boost::smatch match; if (regex_match(*it, match, re)) { pLogEntries->push_back( LogEntry( logFilePath, (it - lines.begin()) + 1, LogEntry::Error, texFilePath(match[3], logFilePath.parent()), boost::lexical_cast<int>(match[2]), match[1])); } } return Success(); } } // namespace tex } // namespace core <|endoftext|>
<commit_before>#include "Literal.h" #include <string> #include <vector> #include "../../Error/Error.h" #include "../../Linkage/Linkage.h" #include "../../Operation/Cast/Cast.h" #include "../../llvmUtils/llvmUtils.h" #include "../Utils/Utils.h" using namespace dale::ErrorInst; namespace dale { llvm::Constant *stringLiteralToConstant(Units *units, Type *type, Node *node, int *size) { Context *ctx = units->top()->ctx; if (!node->is_token) { Error *e = new Error(UnexpectedElement, node, "atom", "literal", "list"); ctx->er->addError(e); return NULL; } Token *t = node->token; if (type->base_type == BaseType::Int) { if (t->type != TokenType::Int) { Error *e = new Error(UnexpectedElement, node, "integer", "literal", t->tokenType()); ctx->er->addError(e); return NULL; } return ctx->nt->getConstantInt(ctx->nt->getNativeIntType(), t->str_value.c_str()); } int underlying_type = (!type->base_type && type->points_to) ? type->points_to->base_type : (type->is_array) ? type->array_type->base_type : 0; if (underlying_type == BaseType::Char) { if (t->type != TokenType::StringLiteral) { Error *e = new Error(UnexpectedElement, node, "string", "literal", t->tokenType()); ctx->er->addError(e); return NULL; } size_t pos = 0; std::string value = t->str_value; while ((pos = value.find("\\n", pos)) != std::string::npos) { value.replace(pos, 2, "\n"); } *size = value.size() + 1; return getStringConstantArray(value.c_str()); } std::string type_str; type->toString(&type_str); Error *e = new Error(CannotParseLiteral, node, type_str.c_str()); ctx->er->addError(e); return NULL; } void FormStringLiteralParse(Units *units, Context *ctx, llvm::BasicBlock *block, Node *node, ParseResult *pr) { Type *type_char = ctx->tr->type_char; Type *type_cchar = ctx->tr->getConstType(type_char); Type *type_pcchar = ctx->tr->getPointerType(type_cchar); TypeRegister *tr = ctx->tr; std::string var_name; units->top()->getUnusedVarName(&var_name); size_t pos = 0; std::string value = node->token->str_value; while ((pos = value.find("\\n", pos)) != std::string::npos) { value.replace(pos, 2, "\n"); } int size = value.size() + 1; Type *char_array_type = tr->getArrayType(tr->type_char, size); llvm::Type *llvm_type = ctx->toLLVMType(char_array_type, NULL, false); llvm::Module *mod = units->top()->module; assert( !mod->getGlobalVariable(llvm::StringRef(var_name.c_str()))); llvm::GlobalVariable *var = llvm::cast<llvm::GlobalVariable>( mod->getOrInsertGlobal(var_name.c_str(), llvm_type)); llvm::Constant *constr_str = getStringConstantArray(value.c_str()); var->setInitializer(constr_str); var->setConstant(true); var->setLinkage(ctx->toLLVMLinkage(Linkage::Intern)); llvm::Constant *const_pchar = createConstantGEP(llvm::cast<llvm::Constant>(var), ctx->nt->getTwoLLVMZeros()); pr->set(block, type_pcchar, llvm::dyn_cast<llvm::Value>(const_pchar)); } void FormFloatingPointLiteralParse(Context *ctx, Type *wanted_type, llvm::BasicBlock *block, Token *t, ParseResult *pr) { if (wanted_type && wanted_type->base_type == BaseType::Float) { pr->set(block, ctx->tr->type_float, llvm::ConstantFP::get( llvm::Type::getFloatTy(*getContext()), llvm::StringRef(t->str_value.c_str()))); } else if (wanted_type && wanted_type->base_type == BaseType::Double) { pr->set(block, ctx->tr->type_double, llvm::ConstantFP::get( llvm::Type::getDoubleTy(*getContext()), llvm::StringRef(t->str_value.c_str()))); } else if (wanted_type && wanted_type->base_type == BaseType::LongDouble) { pr->set(block, ctx->tr->type_longdouble, llvm::ConstantFP::get( ctx->nt->getNativeLongDoubleType(), llvm::StringRef(t->str_value.c_str()))); } else { pr->set(block, ctx->tr->type_float, llvm::ConstantFP::get( llvm::Type::getFloatTy(*getContext()), llvm::StringRef(t->str_value.c_str()))); } return; } void FormIntegerLiteralParse(Context *ctx, Type *wanted_type, llvm::BasicBlock *block, Token *t, ParseResult *pr) { if (wanted_type && wanted_type->isIntegerType()) { int int_size = ctx->nt->internalSizeToRealSize( wanted_type->getIntegerSize()); pr->set(block, ctx->tr->getBasicType(wanted_type->base_type), ctx->nt->getConstantInt( llvm::IntegerType::get(*getContext(), int_size), t->str_value.c_str())); } else { pr->set(block, ctx->tr->type_int, ctx->nt->getConstantInt(ctx->nt->getNativeIntType(), t->str_value.c_str())); } return; } void FormBoolLiteralParse(Context *ctx, llvm::BasicBlock *block, Node *node, ParseResult *pr) { Token *t = node->token; int is_true = !t->str_value.compare("true"); int is_false = !t->str_value.compare("false"); if (is_true || is_false) { pr->set(block, ctx->tr->type_bool, llvm::ConstantInt::get( llvm::Type::getInt8Ty(*getContext()), is_true)); } } void FormCharLiteralParse(Context *ctx, llvm::BasicBlock *block, Node *node, ParseResult *pr) { Token *t = node->token; if ((t->str_value.size() >= 3) && (t->str_value[0] == '#') && (t->str_value[1] == '\\')) { const char *value = t->str_value.c_str(); value += 2; char c; if (!strcmp(value, "NULL")) { c = '\0'; } else if (!strcmp(value, "TAB")) { c = '\t'; } else if (!strcmp(value, "SPACE")) { c = ' '; } else if (!strcmp(value, "NEWLINE")) { c = '\n'; } else if (!strcmp(value, "CARRIAGE")) { c = '\r'; } else if (!strcmp(value, "EOF")) { c = EOF; } else { if (strlen(value) != 1) { Error *e = new Error(InvalidChar, node, value); ctx->er->addError(e); return; } c = value[0]; } pr->set( block, ctx->tr->type_char, llvm::ConstantInt::get(ctx->nt->getNativeCharType(), c)); } } bool FormLiteralParse(Units *units, Type *type, Node *node, int *size, ParseResult *pr) { Context *ctx = units->top()->ctx; TypeRegister *tr = ctx->tr; if (type->isIntegerType() && node->is_token && (node->token->type == TokenType::Int)) { FormIntegerLiteralParse(ctx, type, pr->block, node->token, pr); return true; } else if (type->isFloatingPointType() && node->is_token && (node->token->type == TokenType::FloatingPoint)) { FormFloatingPointLiteralParse(ctx, type, pr->block, node->token, pr); return true; } else if (node->is_token && (node->token->type == TokenType::StringLiteral)) { FormStringLiteralParse(units, ctx, pr->block, node, pr); return true; } else if (type->array_type) { if (!node->is_list) { return false; } std::vector<llvm::Constant *> constants; std::vector<Node *> *lst = node->list; if (lst->size() < 2) { return false; } Node *first = lst->at(0); if (!first->is_token || first->token->str_value.compare("array")) { return false; } for (std::vector<Node *>::iterator b = (lst->begin() + 1), e = lst->end(); b != e; ++b) { int size; ParseResult element_pr; bool res = FormLiteralParse(units, type->array_type, *b, &size, &element_pr); if (!res) { return false; } llvm::Constant *constant = llvm::dyn_cast<llvm::Constant>(element_pr.getValue(ctx)); constants.push_back(constant); } llvm::Constant *const_arr = llvm::ConstantArray::get( llvm::cast<llvm::ArrayType>( ctx->toLLVMType(type, node, false, false)), constants); pr->set(pr->block, type, llvm::dyn_cast<llvm::Value>(const_arr)); return true; } else if (type->struct_name.size()) { Struct *st = ctx->getStruct(type); if (!node->is_list) { return false; } std::vector<llvm::Constant *> constants; std::vector<Node *> *lst = node->list; for (std::vector<Node *>::iterator b = lst->begin(), e = lst->end(); b != e; ++b) { Node *member_node = (*b); if (!member_node->is_list) { return false; } std::vector<Node *> *member_lst = member_node->list; if (member_lst->size() != 2) { return false; } Node *name_node = (*member_lst)[0]; Node *value_node = (*member_lst)[1]; if (!name_node->is_token) { return false; } const char *name = name_node->token->str_value.c_str(); Type *type = st->nameToType(name); if (!type) { return false; } int size; ParseResult element_pr; bool res = FormLiteralParse(units, type, value_node, &size, &element_pr); if (!res) { return false; } llvm::Constant *constant = llvm::dyn_cast<llvm::Constant>(element_pr.getValue(ctx)); constants.push_back(constant); } llvm::Type *llvm_type = ctx->toLLVMType(type, NULL, false); if (!llvm_type) { return false; } llvm::StructType *llvm_st = llvm::cast<llvm::StructType>(llvm_type); llvm::Constant *const_st = llvm::ConstantStruct::get(llvm_st, constants); pr->set(pr->block, type, llvm::dyn_cast<llvm::Value>(const_st)); return true; } else { return false; } } } <commit_msg>[master] tidying<commit_after>#include "Literal.h" #include <string> #include <vector> #include "../../Error/Error.h" #include "../../Linkage/Linkage.h" #include "../../Operation/Cast/Cast.h" #include "../../llvmUtils/llvmUtils.h" #include "../Utils/Utils.h" using namespace dale::ErrorInst; namespace dale { llvm::Constant *stringLiteralToConstant(Units *units, Type *type, Node *node, int *size) { Context *ctx = units->top()->ctx; if (!node->is_token) { Error *e = new Error(UnexpectedElement, node, "atom", "literal", "list"); ctx->er->addError(e); return NULL; } Token *t = node->token; if (type->base_type == BaseType::Int) { if (t->type != TokenType::Int) { Error *e = new Error(UnexpectedElement, node, "integer", "literal", t->tokenType()); ctx->er->addError(e); return NULL; } return ctx->nt->getConstantInt(ctx->nt->getNativeIntType(), t->str_value.c_str()); } int underlying_type = (!type->base_type && type->points_to) ? type->points_to->base_type : (type->is_array) ? type->array_type->base_type : 0; if (underlying_type == BaseType::Char) { if (t->type != TokenType::StringLiteral) { Error *e = new Error(UnexpectedElement, node, "string", "literal", t->tokenType()); ctx->er->addError(e); return NULL; } size_t pos = 0; std::string value = t->str_value; while ((pos = value.find("\\n", pos)) != std::string::npos) { value.replace(pos, 2, "\n"); } *size = value.size() + 1; return getStringConstantArray(value.c_str()); } std::string type_str; type->toString(&type_str); Error *e = new Error(CannotParseLiteral, node, type_str.c_str()); ctx->er->addError(e); return NULL; } void FormStringLiteralParse(Units *units, Context *ctx, llvm::BasicBlock *block, Node *node, ParseResult *pr) { Type *type_char = ctx->tr->type_char; Type *type_cchar = ctx->tr->getConstType(type_char); Type *type_pcchar = ctx->tr->getPointerType(type_cchar); TypeRegister *tr = ctx->tr; std::string var_name; units->top()->getUnusedVarName(&var_name); size_t pos = 0; std::string value = node->token->str_value; while ((pos = value.find("\\n", pos)) != std::string::npos) { value.replace(pos, 2, "\n"); } int size = value.size() + 1; Type *char_array_type = tr->getArrayType(tr->type_char, size); llvm::Type *llvm_type = ctx->toLLVMType(char_array_type, NULL, false); llvm::Module *mod = units->top()->module; assert( !mod->getGlobalVariable(llvm::StringRef(var_name.c_str()))); llvm::GlobalVariable *var = llvm::cast<llvm::GlobalVariable>( mod->getOrInsertGlobal(var_name.c_str(), llvm_type)); llvm::Constant *constr_str = getStringConstantArray(value.c_str()); var->setInitializer(constr_str); var->setConstant(true); var->setLinkage(ctx->toLLVMLinkage(Linkage::Intern)); llvm::Constant *const_pchar = createConstantGEP(llvm::cast<llvm::Constant>(var), ctx->nt->getTwoLLVMZeros()); pr->set(block, type_pcchar, llvm::dyn_cast<llvm::Value>(const_pchar)); } void FormFloatingPointLiteralParse(Context *ctx, Type *wanted_type, llvm::BasicBlock *block, Token *t, ParseResult *pr) { if (wanted_type && wanted_type->base_type == BaseType::Float) { pr->set(block, ctx->tr->type_float, llvm::ConstantFP::get( llvm::Type::getFloatTy(*getContext()), llvm::StringRef(t->str_value.c_str()))); } else if (wanted_type && wanted_type->base_type == BaseType::Double) { pr->set(block, ctx->tr->type_double, llvm::ConstantFP::get( llvm::Type::getDoubleTy(*getContext()), llvm::StringRef(t->str_value.c_str()))); } else if (wanted_type && wanted_type->base_type == BaseType::LongDouble) { pr->set(block, ctx->tr->type_longdouble, llvm::ConstantFP::get( ctx->nt->getNativeLongDoubleType(), llvm::StringRef(t->str_value.c_str()))); } else { pr->set(block, ctx->tr->type_float, llvm::ConstantFP::get( llvm::Type::getFloatTy(*getContext()), llvm::StringRef(t->str_value.c_str()))); } return; } void FormIntegerLiteralParse(Context *ctx, Type *wanted_type, llvm::BasicBlock *block, Token *t, ParseResult *pr) { if (wanted_type && wanted_type->isIntegerType()) { int int_size = ctx->nt->internalSizeToRealSize( wanted_type->getIntegerSize()); pr->set(block, ctx->tr->getBasicType(wanted_type->base_type), ctx->nt->getConstantInt( llvm::IntegerType::get(*getContext(), int_size), t->str_value.c_str())); } else { pr->set(block, ctx->tr->type_int, ctx->nt->getConstantInt(ctx->nt->getNativeIntType(), t->str_value.c_str())); } return; } void FormBoolLiteralParse(Context *ctx, llvm::BasicBlock *block, Node *node, ParseResult *pr) { Token *t = node->token; int is_true = !t->str_value.compare("true"); int is_false = !t->str_value.compare("false"); if (is_true || is_false) { pr->set(block, ctx->tr->type_bool, llvm::ConstantInt::get( llvm::Type::getInt8Ty(*getContext()), is_true)); } } void FormCharLiteralParse(Context *ctx, llvm::BasicBlock *block, Node *node, ParseResult *pr) { Token *t = node->token; if ((t->str_value.size() >= 3) && (t->str_value[0] == '#') && (t->str_value[1] == '\\')) { const char *value = t->str_value.c_str(); value += 2; char c; if (!strcmp(value, "NULL")) { c = '\0'; } else if (!strcmp(value, "TAB")) { c = '\t'; } else if (!strcmp(value, "SPACE")) { c = ' '; } else if (!strcmp(value, "NEWLINE")) { c = '\n'; } else if (!strcmp(value, "CARRIAGE")) { c = '\r'; } else if (!strcmp(value, "EOF")) { c = EOF; } else { if (strlen(value) != 1) { Error *e = new Error(InvalidChar, node, value); ctx->er->addError(e); return; } c = value[0]; } pr->set( block, ctx->tr->type_char, llvm::ConstantInt::get(ctx->nt->getNativeCharType(), c)); } } bool arrayLiteralParse(Units *units, Type *type, Node *node, ParseResult *pr) { Context *ctx = units->top()->ctx; if (!node->is_list) { return false; } std::vector<llvm::Constant *> constants; std::vector<Node *> *lst = node->list; if (lst->size() < 2) { return false; } Node *first = lst->at(0); if (!first->is_token || first->token->str_value.compare("array")) { return false; } for (std::vector<Node *>::iterator b = (lst->begin() + 1), e = lst->end(); b != e; ++b) { int size; ParseResult element_pr; bool res = FormLiteralParse(units, type->array_type, *b, &size, &element_pr); if (!res) { return false; } llvm::Constant *constant = llvm::dyn_cast<llvm::Constant>(element_pr.getValue(ctx)); constants.push_back(constant); } llvm::Constant *const_arr = llvm::ConstantArray::get( llvm::cast<llvm::ArrayType>( ctx->toLLVMType(type, node, false, false)), constants); pr->set(pr->block, type, llvm::dyn_cast<llvm::Value>(const_arr)); return true; } bool structLiteralParse(Units *units, Type *type, Node *node, ParseResult *pr) { Context *ctx = units->top()->ctx; Struct *st = ctx->getStruct(type); if (!node->is_list) { return false; } std::vector<llvm::Constant *> constants; std::vector<Node *> *lst = node->list; for (std::vector<Node *>::iterator b = lst->begin(), e = lst->end(); b != e; ++b) { Node *member_node = (*b); if (!member_node->is_list) { return false; } std::vector<Node *> *member_lst = member_node->list; if (member_lst->size() != 2) { return false; } Node *name_node = (*member_lst)[0]; Node *value_node = (*member_lst)[1]; if (!name_node->is_token) { return false; } const char *name = name_node->token->str_value.c_str(); Type *type = st->nameToType(name); if (!type) { return false; } int size; ParseResult element_pr; bool res = FormLiteralParse(units, type, value_node, &size, &element_pr); if (!res) { return false; } llvm::Constant *constant = llvm::dyn_cast<llvm::Constant>(element_pr.getValue(ctx)); constants.push_back(constant); } llvm::Type *llvm_type = ctx->toLLVMType(type, NULL, false); if (!llvm_type) { return false; } llvm::StructType *llvm_st = llvm::cast<llvm::StructType>(llvm_type); llvm::Constant *const_st = llvm::ConstantStruct::get(llvm_st, constants); pr->set(pr->block, type, llvm::dyn_cast<llvm::Value>(const_st)); return true; } bool FormLiteralParse(Units *units, Type *type, Node *node, int *size, ParseResult *pr) { Context *ctx = units->top()->ctx; if (type->isIntegerType() && node->is_token && (node->token->type == TokenType::Int)) { FormIntegerLiteralParse(ctx, type, pr->block, node->token, pr); return true; } else if (type->isFloatingPointType() && node->is_token && (node->token->type == TokenType::FloatingPoint)) { FormFloatingPointLiteralParse(ctx, type, pr->block, node->token, pr); return true; } else if (node->is_token && (node->token->type == TokenType::StringLiteral)) { FormStringLiteralParse(units, ctx, pr->block, node, pr); return true; } else if (type->array_type) { return arrayLiteralParse(units, type, node, pr); } else if (type->struct_name.size()) { return structLiteralParse(units, type, node, pr); } else { return false; } } } <|endoftext|>
<commit_before>/* gobby - A GTKmm driven libobby client * Copyright (C) 2005 0x539 dev group * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "common.hpp" #include "encoding.hpp" namespace { // Available encodings Gobby::Encoding encodings[] = { Gobby::Encoding("UTF-8", Gobby::Encoding::UTF_8), Gobby::Encoding("ISO_8859-1", Gobby::Encoding::ISO_8859_1), Gobby::Encoding("ISO_8859-15", Gobby::Encoding::ISO_8859_15), Gobby::Encoding("UTF-7", Gobby::Encoding::UTF_7), Gobby::Encoding("UTF-16", Gobby::Encoding::UTF_16), Gobby::Encoding("UCS-2", Gobby::Encoding::UCS_2), Gobby::Encoding("UCS-4", Gobby::Encoding::UCS_4) }; // Amount of encodings we have unsigned int encoding_count = sizeof(encodings) / sizeof(encodings[0]); }; Gobby::Encoding::Encoding(const Glib::ustring& name, Charset charset) : m_name(name), m_charset(charset) { } Gobby::Encoding::Encoding(const Encoding& other) : m_name(other.m_name), m_charset(other.m_charset) { } Gobby::Encoding::~Encoding() { } Gobby::Encoding& Gobby::Encoding::operator=(const Encoding& other) { m_name = other.m_name; m_charset = other.m_charset; } const Glib::ustring& Gobby::Encoding::get_name() const { return m_name; } Gobby::Encoding::Charset Gobby::Encoding::get_charset() const { return m_charset; } Glib::ustring Gobby::Encoding::convert_to_utf8(const std::string& str) { Glib::ustring utf8 = Glib::convert(str, "UTF-8", m_name); if(!utf8.validate() ) { throw Glib::ConvertError( Glib::ConvertError::NO_CONVERSION, "Couldn't convert to UTF_8" ); } return utf8; } Glib::ustring Gobby::convert_to_utf8(const std::string& str) { if(g_utf8_validate(str.c_str(), str.length(), NULL) == TRUE) return str; // Ignore UTF-8 encoding we currently checked for(unsigned int i = 1; i < encoding_count; ++ i) { try { return encodings[i].convert_to_utf8(str); } catch(Glib::ConvertError& e) { // Retry with next encoding } } // No suitable encoding throw Glib::ConvertError( Glib::ConvertError::NO_CONVERSION, _( "Failed to convert input into UTF-8: Either the " "encoding is unknown or it is binary input." ) ); } <commit_msg>[project @ Added missing return statement.]<commit_after>/* gobby - A GTKmm driven libobby client * Copyright (C) 2005 0x539 dev group * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "common.hpp" #include "encoding.hpp" namespace { // Available encodings Gobby::Encoding encodings[] = { Gobby::Encoding("UTF-8", Gobby::Encoding::UTF_8), Gobby::Encoding("ISO_8859-1", Gobby::Encoding::ISO_8859_1), Gobby::Encoding("ISO_8859-15", Gobby::Encoding::ISO_8859_15), Gobby::Encoding("UTF-7", Gobby::Encoding::UTF_7), Gobby::Encoding("UTF-16", Gobby::Encoding::UTF_16), Gobby::Encoding("UCS-2", Gobby::Encoding::UCS_2), Gobby::Encoding("UCS-4", Gobby::Encoding::UCS_4) }; // Amount of encodings we have unsigned int encoding_count = sizeof(encodings) / sizeof(encodings[0]); }; Gobby::Encoding::Encoding(const Glib::ustring& name, Charset charset) : m_name(name), m_charset(charset) { } Gobby::Encoding::Encoding(const Encoding& other) : m_name(other.m_name), m_charset(other.m_charset) { } Gobby::Encoding::~Encoding() { } Gobby::Encoding& Gobby::Encoding::operator=(const Encoding& other) { m_name = other.m_name; m_charset = other.m_charset; return *this; } const Glib::ustring& Gobby::Encoding::get_name() const { return m_name; } Gobby::Encoding::Charset Gobby::Encoding::get_charset() const { return m_charset; } Glib::ustring Gobby::Encoding::convert_to_utf8(const std::string& str) { Glib::ustring utf8 = Glib::convert(str, "UTF-8", m_name); if(!utf8.validate() ) { throw Glib::ConvertError( Glib::ConvertError::NO_CONVERSION, "Couldn't convert to UTF_8" ); } return utf8; } Glib::ustring Gobby::convert_to_utf8(const std::string& str) { if(g_utf8_validate(str.c_str(), str.length(), NULL) == TRUE) return str; // Ignore UTF-8 encoding we currently checked for(unsigned int i = 1; i < encoding_count; ++ i) { try { return encodings[i].convert_to_utf8(str); } catch(Glib::ConvertError& e) { // Retry with next encoding } } // No suitable encoding throw Glib::ConvertError( Glib::ConvertError::NO_CONVERSION, _( "Failed to convert input into UTF-8: Either the " "encoding is unknown or it is binary input." ) ); } <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #if defined __linux__ || (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ #include <sys/ioctl.h> #include <netinet/in.h> #include <net/if.h> #include <net/route.h> #elif defined WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #include <iphlpapi.h> #endif #include "libtorrent/enum_net.hpp" #include <asio/ip/host_name.hpp> namespace libtorrent { namespace { address sockaddr_to_address(sockaddr const* sin) { if (sin->sa_family == AF_INET) { typedef asio::ip::address_v4::bytes_type bytes_t; bytes_t b; memcpy(&b[0], &((sockaddr_in const*)sin)->sin_addr, b.size()); return address_v4(b); } else if (sin->sa_family == AF_INET6) { typedef asio::ip::address_v6::bytes_type bytes_t; bytes_t b; memcpy(&b[0], &((sockaddr_in6 const*)sin)->sin6_addr, b.size()); return address_v6(b); } return address(); } bool verify_sockaddr(sockaddr_in* sin) { return (sin->sin_len == sizeof(sockaddr_in) && sin->sin_family == AF_INET) || (sin->sin_len == sizeof(sockaddr_in6) && sin->sin_family == AF_INET6); } } bool in_subnet(address const& addr, ip_interface const& iface) { if (addr.is_v4() != iface.interface_address.is_v4()) return false; // since netmasks seems unreliable for IPv6 interfaces // (MacOS X returns AF_INET addresses as bitmasks) assume // that any IPv6 address belongs to the subnet of any // interface with an IPv6 address if (addr.is_v6()) return true; return (addr.to_v4().to_ulong() & iface.netmask.to_v4().to_ulong()) == (iface.interface_address.to_v4().to_ulong() & iface.netmask.to_v4().to_ulong()); } bool in_local_network(asio::io_service& ios, address const& addr, asio::error_code& ec) { std::vector<ip_interface> const& net = enum_net_interfaces(ios, ec); if (ec) return false; for (std::vector<ip_interface>::const_iterator i = net.begin() , end(net.end()); i != end; ++i) { if (in_subnet(addr, *i)) return true; } return false; } std::vector<ip_interface> enum_net_interfaces(asio::io_service& ios, asio::error_code& ec) { std::vector<ip_interface> ret; // covers linux, MacOS X and BSD distributions #if defined __linux__ || (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ int s = socket(AF_INET, SOCK_DGRAM, 0); if (s < 0) { ec = asio::error::fault; return ret; } ifconf ifc; char buf[1024]; ifc.ifc_len = sizeof(buf); ifc.ifc_buf = buf; if (ioctl(s, SIOCGIFCONF, &ifc) < 0) { close(s); ec = asio::error_code(errno, asio::error::system_category); return ret; } char *ifr = (char*)ifc.ifc_req; int remaining = ifc.ifc_len; while (remaining) { ifreq const& item = *reinterpret_cast<ifreq*>(ifr); if (item.ifr_addr.sa_family == AF_INET || item.ifr_addr.sa_family == AF_INET6) { ip_interface iface; iface.interface_address = sockaddr_to_address(&item.ifr_addr); ifreq netmask = item; if (ioctl(s, SIOCGIFNETMASK, &netmask) < 0) { if (iface.interface_address.is_v6()) { // this is expected to fail (at least on MacOS X) iface.netmask = address_v6::any(); } else { close(s); ec = asio::error_code(errno, asio::error::system_category); return ret; } } else { iface.netmask = sockaddr_to_address(&netmask.ifr_addr); } ret.push_back(iface); } #if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ int current_size = item.ifr_addr.sa_len + IFNAMSIZ; #elif defined __linux__ int current_size = sizeof(ifreq); #endif ifr += current_size; remaining -= current_size; } close(s); #elif defined WIN32 SOCKET s = socket(AF_INET, SOCK_DGRAM, 0); if (s == SOCKET_ERROR) { ec = asio::error_code(WSAGetLastError(), asio::error::system_category); return ret; } INTERFACE_INFO buffer[30]; DWORD size; if (WSAIoctl(s, SIO_GET_INTERFACE_LIST, 0, 0, buffer, sizeof(buffer), &size, 0, 0) != 0) { ec = asio::error_code(WSAGetLastError(), asio::error::system_category); closesocket(s); return ret; } closesocket(s); int n = size / sizeof(INTERFACE_INFO); ip_interface iface; for (int i = 0; i < n; ++i) { iface.interface_address = sockaddr_to_address(&buffer[i].iiAddress.Address); iface.netmask = sockaddr_to_address(&buffer[i].iiNetmask.Address); if (iface.interface_address == address_v4::any()) continue; ret.push_back(iface); } #else #warning THIS OS IS NOT RECOGNIZED, enum_net_interfaces WILL PROBABLY NOT WORK // make a best guess of the interface we're using and its IP udp::resolver r(ios); udp::resolver::iterator i = r.resolve(udp::resolver::query(asio::ip::host_name(ec), "0"), ec); if (ec) return ret; ip_interface iface; for (;i != udp::resolver_iterator(); ++i) { iface.interface_address = i->endpoint().address(); if (iface.interface_address.is_v4()) iface.netmask = address_v4::netmask(iface.interface_address.to_v4()); ret.push_back(iface); } #endif return ret; } address get_default_gateway(asio::io_service& ios, address const& interface, asio::error_code& ec) { #if defined __linux__ || (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ struct rt_msg { rt_msghdr m_rtm; char buf[512]; }; rt_msg m; int len = sizeof(rt_msg); bzero(&m, len); m.m_rtm.rtm_type = RTM_GET; m.m_rtm.rtm_flags = RTF_UP | RTF_GATEWAY; m.m_rtm.rtm_version = RTM_VERSION; m.m_rtm.rtm_addrs = RTA_DST | RTA_GATEWAY; m.m_rtm.rtm_seq = 0; m.m_rtm.rtm_msglen = len; int s = socket(PF_ROUTE, SOCK_RAW, AF_INET); if (s == -1) { ec = asio::error_code(errno, asio::error::system_category); return address_v4::any(); } int n = write(s, &m, len); if (n == -1) { ec = asio::error_code(errno, asio::error::system_category); close(s); return address_v4::any(); } else if (n != len) { ec = asio::error::operation_not_supported; close(s); return address_v4::any(); } bzero(&m, len); n = read(s, &m, len); if (n == -1) { ec = asio::error_code(errno, asio::error::system_category); close(s); return address_v4::any(); } close(s); TORRENT_ASSERT(m.m_rtm.rtm_seq == 0); TORRENT_ASSERT(m.m_rtm.rtm_pid == getpid()); if (m.m_rtm.rtm_errno) { ec = asio::error_code(m.m_rtm.rtm_errno, asio::error::system_category); return address_v4::any(); } if (m.m_rtm.rtm_flags & RTF_UP == 0 || m.m_rtm.rtm_flags & RTF_GATEWAY == 0) { ec = asio::error::operation_not_supported; return address_v4::any(); } if (m.m_rtm.rtm_addrs & RTA_DST == 0 || m.m_rtm.rtm_addrs & RTA_GATEWAY == 0) { ec = asio::error::operation_not_supported; return address_v4::any(); } if (m.m_rtm.rtm_msglen > len) { ec = asio::error::operation_not_supported; return address_v4::any(); } int min_len = sizeof(rt_msghdr) + 2 * sizeof(struct sockaddr_in); if (m.m_rtm.rtm_msglen < min_len) { ec = asio::error::operation_not_supported; return address_v4::any(); } // default route char* p = m.buf; sockaddr_in* sin = (sockaddr_in*)p; if (!verify_sockaddr(sin)) { ec = asio::error::operation_not_supported; return address_v4::any(); } // default gateway p += sin->sin_len; sin = (sockaddr_in*)p; if (!verify_sockaddr(sin)) { ec = asio::error::operation_not_supported; return address_v4::any(); } return sockaddr_to_address((sockaddr*)sin); #elif defined WIN32 // Load Iphlpapi library HMODULE iphlp = LoadLibraryA("Iphlpapi.dll"); if (!iphlp) { ec = asio::error::operation_not_supported; return address_v4::any(); } // Get GetAdaptersInfo() pointer typedef DWORD (WINAPI *GetAdaptersInfo_t)(PIP_ADAPTER_INFO, PULONG); GetAdaptersInfo_t GetAdaptersInfo = (GetAdaptersInfo_t)GetProcAddress(iphlp, "GetAdaptersInfo"); if (!GetAdaptersInfo) { FreeLibrary(iphlp); ec = asio::error::operation_not_supported; return address_v4::any(); } PIP_ADAPTER_INFO adapter_info = 0; ULONG out_buf_size = 0; if (GetAdaptersInfo(adapter_info, &out_buf_size) != ERROR_BUFFER_OVERFLOW) { FreeLibrary(iphlp); ec = asio::error::operation_not_supported; return address_v4::any(); } adapter_info = (IP_ADAPTER_INFO*)malloc(out_buf_size); if (!adapter_info) { FreeLibrary(iphlp); ec = asio::error::no_memory; return address_v4::any(); } address ret; if (GetAdaptersInfo(adapter_info, &out_buf_size) == NO_ERROR) { for (PIP_ADAPTER_INFO adapter = adapter_info; adapter != 0; adapter = adapter->Next) { address iface = address::from_string(adapter->IpAddressList.IpAddress.String, ec); if (ec) { ec = asio::error_code(); continue; } if (is_loopback(iface) || is_any(iface)) continue; if (interface == address() || interface == iface) { ret = address::from_string(adapter->GatewayList.IpAddress.String, ec); break; } } } // Free memory free(adapter_info); FreeLibrary(iphlp); return ret; #else address interface = guess_local_address(ios); if (!interface.is_v4()) { ec = asio::error::operation_not_supported; return address_v4::any(); } return address_v4((interface.to_v4().to_ulong() & 0xffffff00) | 1); #endif } } <commit_msg>made it build on linux. No linux implementation for getting default route yet<commit_after>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #if defined __linux__ || (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ #include <sys/ioctl.h> #include <netinet/in.h> #include <net/if.h> #include <net/route.h> #elif defined WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #include <iphlpapi.h> #endif #include "libtorrent/enum_net.hpp" #include "libtorrent/broadcast_socket.hpp" #include <asio/ip/host_name.hpp> namespace libtorrent { namespace { address sockaddr_to_address(sockaddr const* sin) { if (sin->sa_family == AF_INET) { typedef asio::ip::address_v4::bytes_type bytes_t; bytes_t b; memcpy(&b[0], &((sockaddr_in const*)sin)->sin_addr, b.size()); return address_v4(b); } else if (sin->sa_family == AF_INET6) { typedef asio::ip::address_v6::bytes_type bytes_t; bytes_t b; memcpy(&b[0], &((sockaddr_in6 const*)sin)->sin6_addr, b.size()); return address_v6(b); } return address(); } } bool in_subnet(address const& addr, ip_interface const& iface) { if (addr.is_v4() != iface.interface_address.is_v4()) return false; // since netmasks seems unreliable for IPv6 interfaces // (MacOS X returns AF_INET addresses as bitmasks) assume // that any IPv6 address belongs to the subnet of any // interface with an IPv6 address if (addr.is_v6()) return true; return (addr.to_v4().to_ulong() & iface.netmask.to_v4().to_ulong()) == (iface.interface_address.to_v4().to_ulong() & iface.netmask.to_v4().to_ulong()); } bool in_local_network(asio::io_service& ios, address const& addr, asio::error_code& ec) { std::vector<ip_interface> const& net = enum_net_interfaces(ios, ec); if (ec) return false; for (std::vector<ip_interface>::const_iterator i = net.begin() , end(net.end()); i != end; ++i) { if (in_subnet(addr, *i)) return true; } return false; } std::vector<ip_interface> enum_net_interfaces(asio::io_service& ios, asio::error_code& ec) { std::vector<ip_interface> ret; // covers linux, MacOS X and BSD distributions #if defined __linux__ || (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ int s = socket(AF_INET, SOCK_DGRAM, 0); if (s < 0) { ec = asio::error::fault; return ret; } ifconf ifc; char buf[1024]; ifc.ifc_len = sizeof(buf); ifc.ifc_buf = buf; if (ioctl(s, SIOCGIFCONF, &ifc) < 0) { close(s); ec = asio::error_code(errno, asio::error::system_category); return ret; } char *ifr = (char*)ifc.ifc_req; int remaining = ifc.ifc_len; while (remaining) { ifreq const& item = *reinterpret_cast<ifreq*>(ifr); if (item.ifr_addr.sa_family == AF_INET || item.ifr_addr.sa_family == AF_INET6) { ip_interface iface; iface.interface_address = sockaddr_to_address(&item.ifr_addr); ifreq netmask = item; if (ioctl(s, SIOCGIFNETMASK, &netmask) < 0) { if (iface.interface_address.is_v6()) { // this is expected to fail (at least on MacOS X) iface.netmask = address_v6::any(); } else { close(s); ec = asio::error_code(errno, asio::error::system_category); return ret; } } else { iface.netmask = sockaddr_to_address(&netmask.ifr_addr); } ret.push_back(iface); } #if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ int current_size = item.ifr_addr.sa_len + IFNAMSIZ; #elif defined __linux__ int current_size = sizeof(ifreq); #endif ifr += current_size; remaining -= current_size; } close(s); #elif defined WIN32 SOCKET s = socket(AF_INET, SOCK_DGRAM, 0); if (s == SOCKET_ERROR) { ec = asio::error_code(WSAGetLastError(), asio::error::system_category); return ret; } INTERFACE_INFO buffer[30]; DWORD size; if (WSAIoctl(s, SIO_GET_INTERFACE_LIST, 0, 0, buffer, sizeof(buffer), &size, 0, 0) != 0) { ec = asio::error_code(WSAGetLastError(), asio::error::system_category); closesocket(s); return ret; } closesocket(s); int n = size / sizeof(INTERFACE_INFO); ip_interface iface; for (int i = 0; i < n; ++i) { iface.interface_address = sockaddr_to_address(&buffer[i].iiAddress.Address); iface.netmask = sockaddr_to_address(&buffer[i].iiNetmask.Address); if (iface.interface_address == address_v4::any()) continue; ret.push_back(iface); } #else #warning THIS OS IS NOT RECOGNIZED, enum_net_interfaces WILL PROBABLY NOT WORK // make a best guess of the interface we're using and its IP udp::resolver r(ios); udp::resolver::iterator i = r.resolve(udp::resolver::query(asio::ip::host_name(ec), "0"), ec); if (ec) return ret; ip_interface iface; for (;i != udp::resolver_iterator(); ++i) { iface.interface_address = i->endpoint().address(); if (iface.interface_address.is_v4()) iface.netmask = address_v4::netmask(iface.interface_address.to_v4()); ret.push_back(iface); } #endif return ret; } address get_default_gateway(asio::io_service& ios, address const& interface, asio::error_code& ec) { #if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ bool verify_sockaddr(sockaddr_in* sin) { return (sin->sin_len == sizeof(sockaddr_in) && sin->sin_family == AF_INET) || (sin->sin_len == sizeof(sockaddr_in6) && sin->sin_family == AF_INET6); } struct rt_msg { rt_msghdr m_rtm; char buf[512]; }; rt_msg m; int len = sizeof(rt_msg); bzero(&m, len); m.m_rtm.rtm_type = RTM_GET; m.m_rtm.rtm_flags = RTF_UP | RTF_GATEWAY; m.m_rtm.rtm_version = RTM_VERSION; m.m_rtm.rtm_addrs = RTA_DST | RTA_GATEWAY; m.m_rtm.rtm_seq = 0; m.m_rtm.rtm_msglen = len; int s = socket(PF_ROUTE, SOCK_RAW, AF_INET); if (s == -1) { ec = asio::error_code(errno, asio::error::system_category); return address_v4::any(); } int n = write(s, &m, len); if (n == -1) { ec = asio::error_code(errno, asio::error::system_category); close(s); return address_v4::any(); } else if (n != len) { ec = asio::error::operation_not_supported; close(s); return address_v4::any(); } bzero(&m, len); n = read(s, &m, len); if (n == -1) { ec = asio::error_code(errno, asio::error::system_category); close(s); return address_v4::any(); } close(s); TORRENT_ASSERT(m.m_rtm.rtm_seq == 0); TORRENT_ASSERT(m.m_rtm.rtm_pid == getpid()); if (m.m_rtm.rtm_errno) { ec = asio::error_code(m.m_rtm.rtm_errno, asio::error::system_category); return address_v4::any(); } if (m.m_rtm.rtm_flags & RTF_UP == 0 || m.m_rtm.rtm_flags & RTF_GATEWAY == 0) { ec = asio::error::operation_not_supported; return address_v4::any(); } if (m.m_rtm.rtm_addrs & RTA_DST == 0 || m.m_rtm.rtm_addrs & RTA_GATEWAY == 0) { ec = asio::error::operation_not_supported; return address_v4::any(); } if (m.m_rtm.rtm_msglen > len) { ec = asio::error::operation_not_supported; return address_v4::any(); } int min_len = sizeof(rt_msghdr) + 2 * sizeof(struct sockaddr_in); if (m.m_rtm.rtm_msglen < min_len) { ec = asio::error::operation_not_supported; return address_v4::any(); } // default route char* p = m.buf; sockaddr_in* sin = (sockaddr_in*)p; if (!verify_sockaddr(sin)) { ec = asio::error::operation_not_supported; return address_v4::any(); } // default gateway p += sin->sin_len; sin = (sockaddr_in*)p; if (!verify_sockaddr(sin)) { ec = asio::error::operation_not_supported; return address_v4::any(); } return sockaddr_to_address((sockaddr*)sin); #elif defined WIN32 // Load Iphlpapi library HMODULE iphlp = LoadLibraryA("Iphlpapi.dll"); if (!iphlp) { ec = asio::error::operation_not_supported; return address_v4::any(); } // Get GetAdaptersInfo() pointer typedef DWORD (WINAPI *GetAdaptersInfo_t)(PIP_ADAPTER_INFO, PULONG); GetAdaptersInfo_t GetAdaptersInfo = (GetAdaptersInfo_t)GetProcAddress(iphlp, "GetAdaptersInfo"); if (!GetAdaptersInfo) { FreeLibrary(iphlp); ec = asio::error::operation_not_supported; return address_v4::any(); } PIP_ADAPTER_INFO adapter_info = 0; ULONG out_buf_size = 0; if (GetAdaptersInfo(adapter_info, &out_buf_size) != ERROR_BUFFER_OVERFLOW) { FreeLibrary(iphlp); ec = asio::error::operation_not_supported; return address_v4::any(); } adapter_info = (IP_ADAPTER_INFO*)malloc(out_buf_size); if (!adapter_info) { FreeLibrary(iphlp); ec = asio::error::no_memory; return address_v4::any(); } address ret; if (GetAdaptersInfo(adapter_info, &out_buf_size) == NO_ERROR) { for (PIP_ADAPTER_INFO adapter = adapter_info; adapter != 0; adapter = adapter->Next) { address iface = address::from_string(adapter->IpAddressList.IpAddress.String, ec); if (ec) { ec = asio::error_code(); continue; } if (is_loopback(iface) || is_any(iface)) continue; if (interface == address() || interface == iface) { ret = address::from_string(adapter->GatewayList.IpAddress.String, ec); break; } } } // Free memory free(adapter_info); FreeLibrary(iphlp); return ret; //#elif defined __linux__ // No linux implementation yet #else if (!interface.is_v4()) { ec = asio::error::operation_not_supported; return address_v4::any(); } return address_v4((interface.to_v4().to_ulong() & 0xffffff00) | 1); #endif } } <|endoftext|>
<commit_before><commit_msg>SALOME Forum bug: http://www.salome-platform.org/forum/forum_10/967838025<commit_after><|endoftext|>
<commit_before>// MultiPortOSSAudioDevice.cpp #if defined(LINUX) #include "MultiPortOSSAudioDevice.h" #include <sys/soundcard.h> #include <sys/time.h> #include <sys/ioctl.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <ctype.h> #include <errno.h> #include <string.h> // strerror() #define DEBUG 1 #if DEBUG > 1 #define PRINT0 if (1) printf #define PRINT1 if (1) printf #elif DEBUG > 0 #define PRINT0 if (1) printf #define PRINT1 if (0) printf #else #define PRINT0 if (0) printf #define PRINT1 if (0) printf #endif MultiPortOSSAudioDevice::MultiPortOSSAudioDevice(const char *devPath, int portCount) : OSSAudioDevice(devPath), _devCount(portCount), _devices(NULL) { _devices = new int[_devCount]; for (int dev = 0; dev < _devCount; ++dev) _devices[dev] = -1; } MultiPortOSSAudioDevice::~MultiPortOSSAudioDevice() { delete [] _devices; } bool MultiPortOSSAudioDevice::recognize(const char *desc) { return (desc != NULL) && strncmp(desc, "/dev/", 5) == 0 && strchr(desc + 5, '-') != NULL; } AudioDevice * MultiPortOSSAudioDevice::create(const char *inputDesc, const char *outputDesc, int mode) { const char *desc = inputDesc ? inputDesc : outputDesc; char devName[32]; int devLen = 0; // Find first digit while (!isdigit(desc[devLen])) ++devLen; const char *devnum = desc + devLen; // skip "/dev/xxx" if (strchr(devnum, '-') != NULL) { // "/dev/xxx0-7", etc. strcpy(devName, desc); devName[devLen] = '\0'; int minDev = 0, maxDev=0; sscanf(devnum, "%d-%d", &minDev, &maxDev); return new MultiPortOSSAudioDevice(devName, maxDev - minDev + 1); } return NULL; } int MultiPortOSSAudioDevice::doOpen(int mode) { char deviceName[64]; int devMode = -1; for (int dev = 0; dev < _devCount; ++dev) { switch (mode & DirectionMask) { case Playback: sprintf(deviceName, "%s%d", _outputDeviceName, dev); devMode = O_WRONLY; break; case Record: sprintf(deviceName, "%s%d", _inputDeviceName, dev); devMode = O_RDONLY; break; case RecordPlayback: sprintf(deviceName, "%s%d", _outputDeviceName, dev); devMode = O_RDWR; break; default: return error("AudioDevice: Illegal open mode."); } closing(false); PRINT0("MultiPortOSSAudioDevice::doOpen: opening %s\n", deviceName); int fd = ::open(deviceName, devMode); if (fd < 0) { return error("OSS multi-port device open failed: ", strerror(errno)); } _devices[dev] = fd; } setDevice(_devices[0]); // Sets the base class device. return 0; } int MultiPortOSSAudioDevice::doSetFormat(int sampfmt, int chans, double srate) { int sampleFormat; int deviceFormat = MUS_GET_FORMAT(sampfmt); switch (MUS_GET_FORMAT(sampfmt)) { case MUS_UBYTE: sampleFormat = AFMT_U8; _bytesPerFrame = chans; break; case MUS_BYTE: sampleFormat = AFMT_S8; _bytesPerFrame = chans; break; case MUS_LFLOAT: deviceFormat = NATIVE_SHORT_FMT; case MUS_LSHORT: _bytesPerFrame = 2 * chans; sampleFormat = AFMT_S16_LE; break; case MUS_BFLOAT: deviceFormat = NATIVE_SHORT_FMT; case MUS_BSHORT: _bytesPerFrame = 2 * chans; sampleFormat = AFMT_S16_BE; break; default: _bytesPerFrame = 0; return error("Unsupported sample format"); }; int status = 0; for (int dev = 0; dev < _devCount && status == 0; ++dev) { status = setDeviceFormat(_devices[dev], sampleFormat, chans, (int) srate); } if (status == 0) { // Store the device params to allow format conversion. setDeviceParams(deviceFormat | MUS_NON_INTERLEAVED, chans, srate); } return status; } int MultiPortOSSAudioDevice::doSetQueueSize(int *pWriteSize, int *pCount) { int reqQueueBytes = *pWriteSize * getDeviceBytesPerFrame(); int queuecode = ((int) (log(reqQueueBytes) / log(2.0))); int sizeCode = (*pCount << 16) | (queuecode & 0x0000ffff); int fragSize = 0; for (int dev = 0; dev < _devCount; ++dev) { int fd = _devices[dev]; if (::ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &sizeCode) == -1) { printf("ioctl(%d, SNDCTL_DSP_SETFRAGMENT, ...) returned -1\n", fd); } if (::ioctl(fd, SNDCTL_DSP_GETBLKSIZE, &fragSize) == -1) { return error("OSS error while retrieving fragment size: ", strerror(errno)); } } *pWriteSize = fragSize / getDeviceBytesPerFrame(); _bufferSize = *pWriteSize * *pCount; PRINT0("MultiPortOSSAudioDevice::doSetQueueSize: writesize = %d, count = %d\n", *pWriteSize, *pCount); return 0; } int MultiPortOSSAudioDevice::doGetFrames(void *frameBuffer, int frameCount) { int toRead = frameCount * _bytesPerFrame; int read = 0; void **multiChanBuffer = (void **) frameBuffer; for (int dev = 0; dev < _devCount; ++dev) { void *chanBuf = multiChanBuffer[dev]; read = ::read(_devices[dev], chanBuf, toRead); if (read <= 0) break; } if (read > 0) { int frames = read / _bytesPerFrame; incrementFrameCount(frames); return frames; } else { return error("Error reading from multi-port OSS device: ", strerror(-read)); } } int MultiPortOSSAudioDevice::doSendFrames(void *frameBuffer, int frameCount) { int toWrite = frameCount * _bytesPerFrame; void **multiChanBuffer = (void **) frameBuffer; int written = 0; for (int dev = 0; dev < _devCount; ++dev) { void *chanBuf = multiChanBuffer[dev]; written = ::write(_devices[dev], chanBuf, toWrite); if (written <= 0) break; } if (written > 0) { int frames = written / _bytesPerFrame; incrementFrameCount(frames); return frames; } else { return error("Error writing to multi-port OSS device: ", strerror(-written)); } } int MultiPortOSSAudioDevice::closeDevice() { int status = 0; for (int dev = 0; dev < _devCount; ++dev) { if (_devices[dev] > 0) status = ::close(_devices[dev]); _devices[dev] = -1; } setDevice(0); // Sets the base class device to 0. return status; } #endif // LINUX <commit_msg>Fixed some mistakes<commit_after>// MultiPortOSSAudioDevice.cpp #if defined(LINUX) #include "MultiPortOSSAudioDevice.h" #include <sys/soundcard.h> #include <sys/time.h> #include <sys/ioctl.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <ctype.h> #include <errno.h> #include <string.h> // strerror() #define DEBUG 1 #if DEBUG > 1 #define PRINT0 if (1) printf #define PRINT1 if (1) printf #elif DEBUG > 0 #define PRINT0 if (1) printf #define PRINT1 if (0) printf #else #define PRINT0 if (0) printf #define PRINT1 if (0) printf #endif MultiPortOSSAudioDevice::MultiPortOSSAudioDevice(const char *devPath, int portCount) : OSSAudioDevice(devPath), _devCount(portCount), _devices(NULL) { _devices = new int[_devCount]; for (int dev = 0; dev < _devCount; ++dev) _devices[dev] = -1; } MultiPortOSSAudioDevice::~MultiPortOSSAudioDevice() { delete [] _devices; } bool MultiPortOSSAudioDevice::recognize(const char *desc) { return (desc != NULL) && strncmp(desc, "/dev/", 5) == 0 && strchr(desc + 5, '-') != NULL; } AudioDevice * MultiPortOSSAudioDevice::create(const char *inputDesc, const char *outputDesc, int mode) { const char *desc = inputDesc ? inputDesc : outputDesc; char devName[32]; int devLen = 0; // Find first digit while (!isdigit(desc[devLen])) ++devLen; const char *devnum = desc + devLen; // skip "/dev/xxx" if (strchr(devnum, '-') != NULL) { // "/dev/xxx0-7", etc. strcpy(devName, desc); devName[devLen] = '\0'; int minDev = 0, maxDev=0; sscanf(devnum, "%d-%d", &minDev, &maxDev); return new MultiPortOSSAudioDevice(devName, maxDev - minDev + 1); } return NULL; } int MultiPortOSSAudioDevice::doOpen(int mode) { char deviceName[64]; int devMode = -1; for (int dev = 0; dev < _devCount; ++dev) { switch (mode & DirectionMask) { case Playback: sprintf(deviceName, "%s%d", _outputDeviceName, dev); devMode = O_WRONLY; break; case Record: sprintf(deviceName, "%s%d", _inputDeviceName, dev); devMode = O_RDONLY; break; case RecordPlayback: sprintf(deviceName, "%s%d", _outputDeviceName, dev); devMode = O_RDWR; break; default: return error("AudioDevice: Illegal open mode."); } closing(false); PRINT0("MultiPortOSSAudioDevice::doOpen: opening %s\n", deviceName); int fd = ::open(deviceName, devMode); if (fd < 0) { return error("OSS multi-port device open failed: ", strerror(errno)); } _devices[dev] = fd; } setDevice(_devices[0]); // Sets the base class device. return 0; } int MultiPortOSSAudioDevice::doSetFormat(int sampfmt, int chans, double srate) { int sampleFormat; int deviceFormat = MUS_GET_FORMAT(sampfmt); switch (MUS_GET_FORMAT(sampfmt)) { case MUS_UBYTE: sampleFormat = AFMT_U8; _bytesPerFrame = 1; break; case MUS_BYTE: sampleFormat = AFMT_S8; _bytesPerFrame = 1; break; case MUS_LFLOAT: deviceFormat = NATIVE_SHORT_FMT; case MUS_LSHORT: _bytesPerFrame = 2; sampleFormat = AFMT_S16_LE; break; case MUS_BFLOAT: deviceFormat = NATIVE_SHORT_FMT; case MUS_BSHORT: _bytesPerFrame = 2; sampleFormat = AFMT_S16_BE; break; default: _bytesPerFrame = 0; return error("Unsupported sample format"); }; // Eventually we will handle subsets of the open device count. if (chans != _devCount) return error("Channel count must match open device count for now"); int status = 0; // Set format on each open monaural device. for (int dev = 0; dev < _devCount && status == 0; ++dev) { status = setDeviceFormat(_devices[dev], sampleFormat, 1, (int) srate); } if (status == 0) { // Store the device params to allow format conversion. setDeviceParams(deviceFormat | MUS_NON_INTERLEAVED, chans, srate); } return status; } int MultiPortOSSAudioDevice::doSetQueueSize(int *pWriteSize, int *pCount) { int reqQueueBytes = *pWriteSize * getDeviceBytesPerFrame(); int queuecode = ((int) (log(reqQueueBytes) / log(2.0))); int sizeCode = (*pCount << 16) | (queuecode & 0x0000ffff); int fragSize = 0; for (int dev = 0; dev < _devCount; ++dev) { int fd = _devices[dev]; if (::ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &sizeCode) == -1) { printf("ioctl(%d, SNDCTL_DSP_SETFRAGMENT, ...) returned -1\n", fd); } if (::ioctl(fd, SNDCTL_DSP_GETBLKSIZE, &fragSize) == -1) { return error("OSS error while retrieving fragment size: ", strerror(errno)); } } *pWriteSize = fragSize / getDeviceBytesPerFrame(); _bufferSize = *pWriteSize * *pCount; PRINT0("MultiPortOSSAudioDevice::doSetQueueSize: writesize = %d, count = %d\n", *pWriteSize, *pCount); return 0; } int MultiPortOSSAudioDevice::doGetFrames(void *frameBuffer, int frameCount) { int toRead = frameCount * _bytesPerFrame; int read = 0; void **multiChanBuffer = (void **) frameBuffer; for (int dev = 0; dev < _devCount; ++dev) { void *chanBuf = multiChanBuffer[dev]; read = ::read(_devices[dev], chanBuf, toRead); if (read <= 0) break; } if (read > 0) { int frames = read / _bytesPerFrame; incrementFrameCount(frames); return frames; } else { return error("Error reading from multi-port OSS device: ", strerror(-read)); } } int MultiPortOSSAudioDevice::doSendFrames(void *frameBuffer, int frameCount) { int toWrite = frameCount * _bytesPerFrame; void **multiChanBuffer = (void **) frameBuffer; int written = 0; for (int dev = 0; dev < _devCount; ++dev) { void *chanBuf = multiChanBuffer[dev]; written = ::write(_devices[dev], chanBuf, toWrite); if (written <= 0) break; } if (written > 0) { int frames = written / _bytesPerFrame; incrementFrameCount(frames); return frames; } else { return error("Error writing to multi-port OSS device: ", strerror(-written)); } } int MultiPortOSSAudioDevice::closeDevice() { int status = 0; for (int dev = 0; dev < _devCount; ++dev) { if (_devices[dev] > 0) status = ::close(_devices[dev]); _devices[dev] = -1; } setDevice(0); // Sets the base class device to 0. return status; } #endif // LINUX <|endoftext|>
<commit_before>// Copyright 2015, University of Freiburg, // Chair of Algorithms and Data Structures. // Author: Björn Buchhold ([email protected]) #include <string> #include <sstream> #include <algorithm> #include "./QueryExecutionTree.h" #include "./IndexScan.h" #include "./Join.h" #include "./Sort.h" #include "./OrderBy.h" #include "./Filter.h" #include "./Distinct.h" #include "TextOperationForEntities.h" #include "TextOperationForContexts.h" #include "TextOperationWithFilter.h" #include "TextOperationWithoutFilter.h" #include "TwoColumnJoin.h" using std::string; // _____________________________________________________________________________ QueryExecutionTree::QueryExecutionTree(QueryExecutionContext *qec) : _qec(qec), _variableColumnMap(), _rootOperation(nullptr), _type(OperationType::UNDEFINED), _contextVars() { } // _____________________________________________________________________________ QueryExecutionTree::QueryExecutionTree(const QueryExecutionTree& other) : _qec(other._qec), _variableColumnMap(other._variableColumnMap), _type(other._type), _contextVars(other._contextVars) { switch (other._type) { case OperationType::SCAN: _rootOperation = new IndexScan( *static_cast<IndexScan *>(other._rootOperation)); break; case OperationType::JOIN: _rootOperation = new Join( *static_cast<Join *>(other._rootOperation)); break; case OperationType::SORT: _rootOperation = new Sort( *static_cast<Sort *>(other._rootOperation)); break; case OperationType::ORDER_BY: _rootOperation = new OrderBy( *static_cast<OrderBy *>(other._rootOperation)); break; case OperationType::FILTER: _rootOperation = new Filter( *static_cast<Filter *>(other._rootOperation)); break; case OperationType::DISTINCT: _rootOperation = new Distinct( *static_cast<Distinct *>(other._rootOperation)); break; case OperationType::TEXT_FOR_ENTITIES: _rootOperation = new TextOperationForEntities( *static_cast<TextOperationForEntities *>(other._rootOperation)); break; case OperationType::TEXT_FOR_CONTEXTS: _rootOperation = new TextOperationForContexts( *static_cast<TextOperationForContexts *>(other._rootOperation)); break; case OperationType::TEXT_WITHOUT_FILTER: _rootOperation = new TextOperationWithoutFilter( *static_cast<TextOperationWithoutFilter *>(other._rootOperation)); break; case OperationType::TEXT_WITH_FILTER: _rootOperation = new TextOperationWithFilter( *static_cast<TextOperationWithFilter *>(other._rootOperation)); break; case OperationType::TWO_COL_JOIN: _rootOperation = new TwoColumnJoin( *static_cast<TwoColumnJoin *>(other._rootOperation)); break; case UNDEFINED: default: _rootOperation = nullptr; } } // _____________________________________________________________________________ QueryExecutionTree& QueryExecutionTree::operator=( const QueryExecutionTree& other) { _qec = other._qec; _variableColumnMap = other._variableColumnMap; _contextVars = other._contextVars; if (other._type != UNDEFINED) { setOperation(other._type, other._rootOperation); } return *this; } // _____________________________________________________________________________ QueryExecutionTree::~QueryExecutionTree() { delete _rootOperation; } // _____________________________________________________________________________ string QueryExecutionTree::asString() const { if (_rootOperation) { std::ostringstream os; os << "{" << _rootOperation->asString() << " | width: " << getResultWidth() << "}"; return os.str(); } else { return "<Empty QueryExecutionTree>"; } } // _____________________________________________________________________________ void QueryExecutionTree::setOperation(QueryExecutionTree::OperationType type, Operation *op) { _type = type; switch (type) { case OperationType::SCAN: delete _rootOperation; _rootOperation = new IndexScan(*static_cast<IndexScan *>(op)); break; case OperationType::JOIN: delete _rootOperation; _rootOperation = new Join(*static_cast<Join *>(op)); break; case OperationType::SORT: delete _rootOperation; _rootOperation = new Sort(*static_cast<Sort *>(op)); break; case OperationType::ORDER_BY: delete _rootOperation; _rootOperation = new OrderBy(*static_cast<OrderBy *>(op)); break; case OperationType::FILTER: delete _rootOperation; _rootOperation = new Filter(*static_cast<Filter *>(op)); break; case OperationType::DISTINCT: delete _rootOperation; _rootOperation = new Distinct(*static_cast<Distinct *>(op)); break; case OperationType::TEXT_FOR_ENTITIES: delete _rootOperation; _rootOperation = new TextOperationForEntities( *static_cast<TextOperationForEntities *>(op)); break; case OperationType::TEXT_FOR_CONTEXTS: delete _rootOperation; _rootOperation = new TextOperationForContexts( *static_cast<TextOperationForContexts *>(op)); break; case OperationType::TEXT_WITHOUT_FILTER: delete _rootOperation; _rootOperation = new TextOperationWithoutFilter( *static_cast<TextOperationWithoutFilter *>(op)); break; case OperationType::TEXT_WITH_FILTER: delete _rootOperation; _rootOperation = new TextOperationWithFilter( *static_cast<TextOperationWithFilter *>(op)); break; case OperationType::TWO_COL_JOIN: delete _rootOperation; _rootOperation = new TwoColumnJoin( *static_cast<TwoColumnJoin *>(op)); break; default: AD_THROW(ad_semsearch::Exception::ASSERT_FAILED, "Cannot set " "an operation with undefined type."); } } // _____________________________________________________________________________ void QueryExecutionTree::setVariableColumn(const string& variable, size_t column) { _variableColumnMap[variable] = column; } // _____________________________________________________________________________ size_t QueryExecutionTree::getVariableColumn(const string& variable) const { if (_variableColumnMap.count(variable) == 0) { AD_THROW(ad_semsearch::Exception::CHECK_FAILED, "Variable could not be mapped to result column. Var: " + variable); } return _variableColumnMap.find(variable)->second; } // _____________________________________________________________________________ void QueryExecutionTree::setVariableColumns( unordered_map<string, size_t> const& map) { _variableColumnMap = map; } // _____________________________________________________________________________ void QueryExecutionTree::writeResultToStream(std::ostream& out, const vector<string>& selectVars, size_t limit, size_t offset) const { // They may trigger computation (but does not have to). const ResultTable& res = getResult(); LOG(DEBUG) << "Resolving strings for finished binary result...\n"; vector<pair<size_t, OutputType>> validIndices; for (auto var : selectVars) { OutputType outputType = OutputType::KB; if (ad_utility::startsWith(var, "SCORE(") || isContextvar(var)) { outputType = OutputType::VERBATIM; } if (ad_utility::startsWith(var, "TEXT(")) { outputType = OutputType::TEXT; var = var.substr(5, var.rfind(')') - 5); } if (getVariableColumnMap().find(var) != getVariableColumnMap().end()) { validIndices.push_back( pair<size_t, OutputType>(getVariableColumnMap().find(var)->second, outputType)); } } if (validIndices.size() == 0) { return; } if (res._nofColumns == 1) { auto data = static_cast<vector<array<Id, 1>> *>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeTsvTable(*data, offset, upperBound, validIndices, out); } else if (res._nofColumns == 2) { auto data = static_cast<vector<array<Id, 2>> *>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeTsvTable(*data, offset, upperBound, validIndices, out); } else if (res._nofColumns == 3) { auto data = static_cast<vector<array<Id, 3>> *>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeTsvTable(*data, offset, upperBound, validIndices, out); } else if (res._nofColumns == 4) { auto data = static_cast<vector<array<Id, 4>> *>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeTsvTable(*data, offset, upperBound, validIndices, out); } else if (res._nofColumns == 5) { auto data = static_cast<vector<array<Id, 5>> *>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeTsvTable(*data, offset, upperBound, validIndices, out); } else { size_t upperBound = std::min<size_t>(offset + limit, res._varSizeData.size()); writeTsvTable(res._varSizeData, offset, upperBound, validIndices, out); } LOG(DEBUG) << "Done creating readable result.\n"; } // _____________________________________________________________________________ void QueryExecutionTree::writeResultToStreamAsJson( std::ostream& out, const vector<string>& selectVars, size_t limit, size_t offset) const { out << "[\r\n"; // They may trigger computation (but does not have to). const ResultTable& res = getResult(); LOG(DEBUG) << "Resolving strings for finished binary result...\n"; vector<pair<size_t, OutputType>> validIndices; for (auto var : selectVars) { OutputType outputType = OutputType::KB; if (ad_utility::startsWith(var, "SCORE(") || isContextvar(var)) { outputType = OutputType::VERBATIM; } if (ad_utility::startsWith(var, "TEXT(")) { outputType = OutputType::TEXT; var = var.substr(5, var.rfind(')') - 5); } if (getVariableColumnMap().find(var) != getVariableColumnMap().end()) { validIndices.push_back( pair<size_t, OutputType>(getVariableColumnMap().find(var)->second, outputType)); } } if (validIndices.size() == 0) { return; } if (res._nofColumns == 1) { auto data = static_cast<vector<array<Id, 1>> *>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeJsonTable(*data, offset, upperBound, validIndices, out); } else if (res._nofColumns == 2) { auto data = static_cast<vector<array<Id, 2>> *>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeJsonTable(*data, offset, upperBound, validIndices, out); } else if (res._nofColumns == 3) { auto data = static_cast<vector<array<Id, 3>> *>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeJsonTable(*data, offset, upperBound, validIndices, out); } else if (res._nofColumns == 4) { auto data = static_cast<vector<array<Id, 4>> *>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeJsonTable(*data, offset, upperBound, validIndices, out); } else if (res._nofColumns == 5) { auto data = static_cast<vector<array<Id, 5>> *>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeJsonTable(*data, offset, upperBound, validIndices, out); } else { size_t upperBound = std::min<size_t>(offset + limit, res._varSizeData.size()); writeJsonTable(res._varSizeData, offset, upperBound, validIndices, out); } out << "]"; LOG(DEBUG) << "Done creating readable result.\n"; } // _____________________________________________________________________________ size_t QueryExecutionTree::getCostEstimate() const { return _rootOperation->getCostEstimate(); } // _____________________________________________________________________________ size_t QueryExecutionTree::getSizeEstimate() const { return _rootOperation->getSizeEstimate(); } // _____________________________________________________________________________ bool QueryExecutionTree::varCovered(string var) const { return _variableColumnMap.count(var) > 0; } <commit_msg>added size estimates to asString of QueryExecutionTrees<commit_after>// Copyright 2015, University of Freiburg, // Chair of Algorithms and Data Structures. // Author: Björn Buchhold ([email protected]) #include <string> #include <sstream> #include <algorithm> #include "./QueryExecutionTree.h" #include "./IndexScan.h" #include "./Join.h" #include "./Sort.h" #include "./OrderBy.h" #include "./Filter.h" #include "./Distinct.h" #include "TextOperationForEntities.h" #include "TextOperationForContexts.h" #include "TextOperationWithFilter.h" #include "TextOperationWithoutFilter.h" #include "TwoColumnJoin.h" using std::string; // _____________________________________________________________________________ QueryExecutionTree::QueryExecutionTree(QueryExecutionContext* qec) : _qec(qec), _variableColumnMap(), _rootOperation(nullptr), _type(OperationType::UNDEFINED), _contextVars() { } // _____________________________________________________________________________ QueryExecutionTree::QueryExecutionTree(const QueryExecutionTree& other) : _qec(other._qec), _variableColumnMap(other._variableColumnMap), _type(other._type), _contextVars(other._contextVars) { switch (other._type) { case OperationType::SCAN: _rootOperation = new IndexScan( *static_cast<IndexScan*>(other._rootOperation)); break; case OperationType::JOIN: _rootOperation = new Join( *static_cast<Join*>(other._rootOperation)); break; case OperationType::SORT: _rootOperation = new Sort( *static_cast<Sort*>(other._rootOperation)); break; case OperationType::ORDER_BY: _rootOperation = new OrderBy( *static_cast<OrderBy*>(other._rootOperation)); break; case OperationType::FILTER: _rootOperation = new Filter( *static_cast<Filter*>(other._rootOperation)); break; case OperationType::DISTINCT: _rootOperation = new Distinct( *static_cast<Distinct*>(other._rootOperation)); break; case OperationType::TEXT_FOR_ENTITIES: _rootOperation = new TextOperationForEntities( *static_cast<TextOperationForEntities*>(other._rootOperation)); break; case OperationType::TEXT_FOR_CONTEXTS: _rootOperation = new TextOperationForContexts( *static_cast<TextOperationForContexts*>(other._rootOperation)); break; case OperationType::TEXT_WITHOUT_FILTER: _rootOperation = new TextOperationWithoutFilter( *static_cast<TextOperationWithoutFilter*>(other._rootOperation)); break; case OperationType::TEXT_WITH_FILTER: _rootOperation = new TextOperationWithFilter( *static_cast<TextOperationWithFilter*>(other._rootOperation)); break; case OperationType::TWO_COL_JOIN: _rootOperation = new TwoColumnJoin( *static_cast<TwoColumnJoin*>(other._rootOperation)); break; case UNDEFINED: default: _rootOperation = nullptr; } } // _____________________________________________________________________________ QueryExecutionTree& QueryExecutionTree::operator=( const QueryExecutionTree& other) { _qec = other._qec; _variableColumnMap = other._variableColumnMap; _contextVars = other._contextVars; if (other._type != UNDEFINED) { setOperation(other._type, other._rootOperation); } return *this; } // _____________________________________________________________________________ QueryExecutionTree::~QueryExecutionTree() { delete _rootOperation; } // _____________________________________________________________________________ string QueryExecutionTree::asString() const { if (_rootOperation) { std::ostringstream os; os << "{" << _rootOperation->asString() << " | width: " << getResultWidth() << "}"; if (_qec) { os << " [estimated size: " << getSizeEstimate() << "]"; } return os.str(); } else { return "<Empty QueryExecutionTree>"; } } // _____________________________________________________________________________ void QueryExecutionTree::setOperation(QueryExecutionTree::OperationType type, Operation* op) { _type = type; switch (type) { case OperationType::SCAN: delete _rootOperation; _rootOperation = new IndexScan(*static_cast<IndexScan*>(op)); break; case OperationType::JOIN: delete _rootOperation; _rootOperation = new Join(*static_cast<Join*>(op)); break; case OperationType::SORT: delete _rootOperation; _rootOperation = new Sort(*static_cast<Sort*>(op)); break; case OperationType::ORDER_BY: delete _rootOperation; _rootOperation = new OrderBy(*static_cast<OrderBy*>(op)); break; case OperationType::FILTER: delete _rootOperation; _rootOperation = new Filter(*static_cast<Filter*>(op)); break; case OperationType::DISTINCT: delete _rootOperation; _rootOperation = new Distinct(*static_cast<Distinct*>(op)); break; case OperationType::TEXT_FOR_ENTITIES: delete _rootOperation; _rootOperation = new TextOperationForEntities( *static_cast<TextOperationForEntities*>(op)); break; case OperationType::TEXT_FOR_CONTEXTS: delete _rootOperation; _rootOperation = new TextOperationForContexts( *static_cast<TextOperationForContexts*>(op)); break; case OperationType::TEXT_WITHOUT_FILTER: delete _rootOperation; _rootOperation = new TextOperationWithoutFilter( *static_cast<TextOperationWithoutFilter*>(op)); break; case OperationType::TEXT_WITH_FILTER: delete _rootOperation; _rootOperation = new TextOperationWithFilter( *static_cast<TextOperationWithFilter*>(op)); break; case OperationType::TWO_COL_JOIN: delete _rootOperation; _rootOperation = new TwoColumnJoin( *static_cast<TwoColumnJoin*>(op)); break; default: AD_THROW(ad_semsearch::Exception::ASSERT_FAILED, "Cannot set " "an operation with undefined type."); } } // _____________________________________________________________________________ void QueryExecutionTree::setVariableColumn(const string& variable, size_t column) { _variableColumnMap[variable] = column; } // _____________________________________________________________________________ size_t QueryExecutionTree::getVariableColumn(const string& variable) const { if (_variableColumnMap.count(variable) == 0) { AD_THROW(ad_semsearch::Exception::CHECK_FAILED, "Variable could not be mapped to result column. Var: " + variable); } return _variableColumnMap.find(variable)->second; } // _____________________________________________________________________________ void QueryExecutionTree::setVariableColumns( unordered_map<string, size_t> const& map) { _variableColumnMap = map; } // _____________________________________________________________________________ void QueryExecutionTree::writeResultToStream(std::ostream& out, const vector<string>& selectVars, size_t limit, size_t offset) const { // They may trigger computation (but does not have to). const ResultTable& res = getResult(); LOG(DEBUG) << "Resolving strings for finished binary result...\n"; vector<pair<size_t, OutputType>> validIndices; for (auto var : selectVars) { OutputType outputType = OutputType::KB; if (ad_utility::startsWith(var, "SCORE(") || isContextvar(var)) { outputType = OutputType::VERBATIM; } if (ad_utility::startsWith(var, "TEXT(")) { outputType = OutputType::TEXT; var = var.substr(5, var.rfind(')') - 5); } if (getVariableColumnMap().find(var) != getVariableColumnMap().end()) { validIndices.push_back( pair<size_t, OutputType>(getVariableColumnMap().find(var)->second, outputType)); } } if (validIndices.size() == 0) { return; } if (res._nofColumns == 1) { auto data = static_cast<vector<array<Id, 1>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeTsvTable(*data, offset, upperBound, validIndices, out); } else if (res._nofColumns == 2) { auto data = static_cast<vector<array<Id, 2>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeTsvTable(*data, offset, upperBound, validIndices, out); } else if (res._nofColumns == 3) { auto data = static_cast<vector<array<Id, 3>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeTsvTable(*data, offset, upperBound, validIndices, out); } else if (res._nofColumns == 4) { auto data = static_cast<vector<array<Id, 4>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeTsvTable(*data, offset, upperBound, validIndices, out); } else if (res._nofColumns == 5) { auto data = static_cast<vector<array<Id, 5>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeTsvTable(*data, offset, upperBound, validIndices, out); } else { size_t upperBound = std::min<size_t>(offset + limit, res._varSizeData.size()); writeTsvTable(res._varSizeData, offset, upperBound, validIndices, out); } LOG(DEBUG) << "Done creating readable result.\n"; } // _____________________________________________________________________________ void QueryExecutionTree::writeResultToStreamAsJson( std::ostream& out, const vector<string>& selectVars, size_t limit, size_t offset) const { out << "[\r\n"; // They may trigger computation (but does not have to). const ResultTable& res = getResult(); LOG(DEBUG) << "Resolving strings for finished binary result...\n"; vector<pair<size_t, OutputType>> validIndices; for (auto var : selectVars) { OutputType outputType = OutputType::KB; if (ad_utility::startsWith(var, "SCORE(") || isContextvar(var)) { outputType = OutputType::VERBATIM; } if (ad_utility::startsWith(var, "TEXT(")) { outputType = OutputType::TEXT; var = var.substr(5, var.rfind(')') - 5); } if (getVariableColumnMap().find(var) != getVariableColumnMap().end()) { validIndices.push_back( pair<size_t, OutputType>(getVariableColumnMap().find(var)->second, outputType)); } } if (validIndices.size() == 0) { return; } if (res._nofColumns == 1) { auto data = static_cast<vector<array<Id, 1>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeJsonTable(*data, offset, upperBound, validIndices, out); } else if (res._nofColumns == 2) { auto data = static_cast<vector<array<Id, 2>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeJsonTable(*data, offset, upperBound, validIndices, out); } else if (res._nofColumns == 3) { auto data = static_cast<vector<array<Id, 3>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeJsonTable(*data, offset, upperBound, validIndices, out); } else if (res._nofColumns == 4) { auto data = static_cast<vector<array<Id, 4>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeJsonTable(*data, offset, upperBound, validIndices, out); } else if (res._nofColumns == 5) { auto data = static_cast<vector<array<Id, 5>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeJsonTable(*data, offset, upperBound, validIndices, out); } else { size_t upperBound = std::min<size_t>(offset + limit, res._varSizeData.size()); writeJsonTable(res._varSizeData, offset, upperBound, validIndices, out); } out << "]"; LOG(DEBUG) << "Done creating readable result.\n"; } // _____________________________________________________________________________ size_t QueryExecutionTree::getCostEstimate() const { return _rootOperation->getCostEstimate(); } // _____________________________________________________________________________ size_t QueryExecutionTree::getSizeEstimate() const { return _rootOperation->getSizeEstimate(); } // _____________________________________________________________________________ bool QueryExecutionTree::varCovered(string var) const { return _variableColumnMap.count(var) > 0; } <|endoftext|>