text
stringlengths
54
60.6k
<commit_before>// // main.cpp // thermaleraser // // Created by Mark Larus on 9/8/12. // Copyright (c) 2012 Kenyon College. All rights reserved. // #include <iostream> #include <algorithm> #include <math.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_sf.h> #include <boost/program_options.hpp> #ifdef HAS_BOOST_TIMER #include <boost/timer/timer.hpp> /*! Fix a namespace issue with boost library. This lets us use both cpu_timer and progress */ #define timer timer_class #include <boost/progress.hpp> #undef timer #endif #include "clangomp.h" #include "Stochastic.h" #include "Ising.h" #include "System.h" #include "Utilities.h" #include "ReservoirFactory.h" #define print(x) std::cout<<#x <<": " <<x<<std::endl; namespace opt = boost::program_options; enum OutputType { CommaSeparated, PrettyPrint, Mathematica, NoOutput }; enum ReservoirType { Ising, Stoch }; void simulate_and_print(Constants constants, int iterations, OutputType type, ReservoirFactory *factory, bool verbose = false); int main(int argc, char * argv[]) { /*! Initialize options list. */ bool verbose = false; const int default_iterations = 1<<16; opt::options_description desc("Allowed options"); desc.add_options() ("iterations,n",opt::value<int>(), "Number of iterations.") ("help","Show help message") ("verbose,v", "Show extensive debugging info") #ifdef HAS_BOOST_TIMER ("benchmark", "Test evaluation speed") #endif ("ising", "Use Ising reservoir. Requires -d. Overrides --stoch") ("stoch", "Use Stochastic reservoir. This is set by default, and overridden" " by --ising.") ("dimension,d", opt::value<int>()->default_value(100), "Set the dimension of the Ising reservoir") ("tau,t", opt::value<double>()->default_value(5)) ; opt::variables_map vmap; opt::store(opt::parse_command_line(argc,argv,desc),vmap); opt::notify(vmap); if (vmap.count("help")) { std::cout << desc << "\n"; return 1; } verbose = vmap.count("verbose"); int iterations = vmap.count("iterations") ? vmap["iterations"].as<int>() : default_iterations; if (verbose) { print(iterations); #pragma omp parallel #pragma omp single print(omp_get_num_threads()); } OutputType output_style = vmap.count("output") ? (OutputType)vmap["output"].as<int>() : CommaSeparated; /*! This call sets up our state machine for the wheel. Each state (i.e. "A0", "C1") is represented by an object with pointers to the next states and the bit-flip states. */ setupStates(); Constants constants; #ifdef HAS_BOOST_TIMER if(vmap.count("benchmark")) { std::cout<<"Benchmarking speed.\n"; int benchmark_size = 1000; boost::timer::cpu_timer timer; boost::progress_display display(benchmark_size); timer.start(); #pragma omp parallel for private(constants) for (int k=0; k<benchmark_size; k++) { simulate_and_print(constants,iterations,NoOutput,false); ++display; } timer.stop(); double time_elapsed = timer.elapsed().wall; print(benchmark_size); print(timer.format(3,"%ws")); print(benchmark_size/time_elapsed); exit(0); } #endif ReservoirFactory *rFactory = NULL; if ( vmap.count("ising") ) { if (!vmap.count("dimension")) { std::clog << "Option --ising requires -d\n"; exit(1); } int dim = vmap["dimension"].as<int>(); rFactory = new IsingReservoir::IsingFactory(dim); } else { //Assume stochastic rFactory = new DefaultArgsReservoirFactory<StochasticReservoir>; } assert(rFactory); int dimension = 50; const double tau = vmap["tau"].as<double>(); if ( output_style == CommaSeparated ) { printf("delta,epsilon,avg,max_surprise\n"); } #pragma omp parallel for private(constants) for (int k=dimension*dimension; k>=0; k--) { constants.epsilon = (k % dimension)/(double)(dimension); constants.delta = .5 + .5*(k / dimension)/(double)(dimension); constants.tau = tau; simulate_and_print(constants, iterations, output_style, rFactory, verbose); } delete rFactory; } void simulate_and_print(Constants constants, int iterations, OutputType type, \ ReservoirFactory *factory, bool verbose) { if (constants.tau<.1) { std::clog<<"Warning: small tau.\n"; } /*! Use this to change the length of the tape. */ const int BIT_STREAM_LENGTH = 8; int first_pass_iterations = iterations; int *histogram = new int[1<<BIT_STREAM_LENGTH]; std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0); long double *p = new long double[1<<BIT_STREAM_LENGTH]; long double *p_prime = new long double[1<<BIT_STREAM_LENGTH]; long double sum = 0; const long double beta = log((1+constants.epsilon)/(1-constants.epsilon)); long double max_surprise = 0; long double min_surprise = LONG_MAX; gsl_rng *localRNG = GSLRandomNumberGenerator(); Reservoir *reservoir = factory->create(localRNG,constants); for (int k=0; k<first_pass_iterations; ++k) { System *currentSystem = new System(localRNG, constants,BIT_STREAM_LENGTH); Reservoir *reservoir = factory->create(localRNG, constants); currentSystem->evolveWithReservoir(reservoir); histogram[currentSystem->endingBitString]++; delete currentSystem; reservoir->reset(); } for(int k=0; k<1<<BIT_STREAM_LENGTH; k++) { int setBits = bitCount(k,BIT_STREAM_LENGTH); p[k] = gsl_ran_binomial_pdf(setBits, constants.delta, BIT_STREAM_LENGTH)/gsl_sf_choose(BIT_STREAM_LENGTH,setBits); p_prime[k]=static_cast<long double>(histogram[k])/(first_pass_iterations); } delete [] histogram; for(int k=0; k<iterations; k++) { System *currentSystem = new System(localRNG, constants, BIT_STREAM_LENGTH); currentSystem->evolveWithReservoir(reservoir); long double surprise = exp(beta*currentSystem->mass)*p_prime[currentSystem->endingBitString]/p[currentSystem->startingBitString]; max_surprise = surprise > max_surprise ? surprise : max_surprise; min_surprise = surprise && surprise < min_surprise ? surprise : min_surprise; sum = sum + surprise; delete currentSystem; reservoir->reset(); } delete [] p_prime; delete [] p; // #pragma omp critical { if(type==CommaSeparated) { printf("%lf,%lf,%Lf,%Lf\n",constants.delta,constants.epsilon,sum/iterations,max_surprise); } if(type==PrettyPrint) { #pragma omp critical { print(beta); print(constants.delta); print(constants.epsilon); print(sum/iterations); print(max_surprise); print(sum); std::cout<<std::endl; } } if (type==Mathematica) { exit(1); } } delete reservoir; gsl_rng_free(localRNG); } <commit_msg>Fix a memory ascension and change OpenMP scheduling to guided. Performance improvements.<commit_after>// // main.cpp // thermaleraser // // Created by Mark Larus on 9/8/12. // Copyright (c) 2012 Kenyon College. All rights reserved. // #include <iostream> #include <algorithm> #include <math.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_sf.h> #include <boost/program_options.hpp> #ifdef HAS_BOOST_TIMER #include <boost/timer/timer.hpp> /*! Fix a namespace issue with boost library. This lets us use both cpu_timer and progress */ #define timer timer_class #include <boost/progress.hpp> #undef timer #endif #include "clangomp.h" #include "Stochastic.h" #include "Ising.h" #include "System.h" #include "Utilities.h" #include "ReservoirFactory.h" #define print(x) std::cout<<#x <<": " <<x<<std::endl; namespace opt = boost::program_options; enum OutputType { CommaSeparated, PrettyPrint, Mathematica, NoOutput }; enum ReservoirType { Ising, Stoch }; void simulate_and_print(Constants constants, int iterations, OutputType type, ReservoirFactory *factory, bool verbose = false); int main(int argc, char * argv[]) { /*! Initialize options list. */ bool verbose = false; const int default_iterations = 1<<16; opt::options_description desc("Allowed options"); desc.add_options() ("iterations,n",opt::value<int>(), "Number of iterations.") ("help","Show help message") ("verbose,v", "Show extensive debugging info") #ifdef HAS_BOOST_TIMER ("benchmark", "Test evaluation speed") #endif ("ising", "Use Ising reservoir. Requires -d. Overrides --stoch") ("stoch", "Use Stochastic reservoir. This is set by default, and overridden" " by --ising.") ("dimension,d", opt::value<int>()->default_value(100), "Set the dimension of the Ising reservoir") ("tau,t", opt::value<double>()->default_value(5)) ; opt::variables_map vmap; opt::store(opt::parse_command_line(argc,argv,desc),vmap); opt::notify(vmap); if (vmap.count("help")) { std::cout << desc << "\n"; return 1; } verbose = vmap.count("verbose"); int iterations = vmap.count("iterations") ? vmap["iterations"].as<int>() : default_iterations; if (verbose) { print(iterations); #pragma omp parallel #pragma omp single print(omp_get_num_threads()); } OutputType output_style = vmap.count("output") ? (OutputType)vmap["output"].as<int>() : CommaSeparated; /*! This call sets up our state machine for the wheel. Each state (i.e. "A0", "C1") is represented by an object with pointers to the next states and the bit-flip states. */ setupStates(); Constants constants; #ifdef HAS_BOOST_TIMER if(vmap.count("benchmark")) { std::cout<<"Benchmarking speed.\n"; int benchmark_size = 1000; boost::timer::cpu_timer timer; boost::progress_display display(benchmark_size); timer.start(); #pragma omp parallel for private(constants) for (int k=0; k<benchmark_size; k++) { simulate_and_print(constants,iterations,NoOutput,false); ++display; } timer.stop(); double time_elapsed = timer.elapsed().wall; print(benchmark_size); print(timer.format(3,"%ws")); print(benchmark_size/time_elapsed); exit(0); } #endif ReservoirFactory *rFactory = NULL; if ( vmap.count("ising") ) { if (!vmap.count("dimension")) { std::clog << "Option --ising requires -d\n"; exit(1); } int dim = vmap["dimension"].as<int>(); rFactory = new IsingReservoir::IsingFactory(dim); } else { //Assume stochastic rFactory = new DefaultArgsReservoirFactory<StochasticReservoir>; } assert(rFactory); int dimension = 50; const double tau = vmap["tau"].as<double>(); if ( output_style == CommaSeparated ) { printf("delta,epsilon,avg,max_surprise\n"); } #pragma omp parallel for private(constants) schedule(guided) for (int k=dimension*dimension; k>=0; k--) { constants.epsilon = (k % dimension)/(double)(dimension); constants.delta = .5 + .5*(k / dimension)/(double)(dimension); constants.tau = tau; simulate_and_print(constants, iterations, output_style, rFactory, verbose); } delete rFactory; } void simulate_and_print(Constants constants, int iterations, OutputType type, \ ReservoirFactory *factory, bool verbose) { if (constants.tau<.1) { std::clog<<"Warning: small tau.\n"; } /*! Use this to change the length of the tape. */ const int BIT_STREAM_LENGTH = 8; int first_pass_iterations = iterations; int *histogram = new int[1<<BIT_STREAM_LENGTH]; std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0); long double *p = new long double[1<<BIT_STREAM_LENGTH]; long double *p_prime = new long double[1<<BIT_STREAM_LENGTH]; long double sum = 0; const long double beta = log((1+constants.epsilon)/(1-constants.epsilon)); long double max_surprise = 0; long double min_surprise = LONG_MAX; gsl_rng *localRNG = GSLRandomNumberGenerator(); Reservoir *reservoir = factory->create(localRNG,constants); for (int k=0; k<first_pass_iterations; ++k) { System *currentSystem = new System(localRNG, constants,BIT_STREAM_LENGTH); currentSystem->evolveWithReservoir(reservoir); histogram[currentSystem->endingBitString]++; delete currentSystem; reservoir->reset(); } for(int k=0; k<1<<BIT_STREAM_LENGTH; k++) { int setBits = bitCount(k,BIT_STREAM_LENGTH); p[k] = gsl_ran_binomial_pdf(setBits, constants.delta, BIT_STREAM_LENGTH)/gsl_sf_choose(BIT_STREAM_LENGTH,setBits); p_prime[k]=static_cast<long double>(histogram[k])/(first_pass_iterations); } delete [] histogram; for(int k=0; k<iterations; k++) { System *currentSystem = new System(localRNG, constants, BIT_STREAM_LENGTH); currentSystem->evolveWithReservoir(reservoir); long double surprise = exp(beta*currentSystem->mass)*p_prime[currentSystem->endingBitString]/p[currentSystem->startingBitString]; max_surprise = surprise > max_surprise ? surprise : max_surprise; min_surprise = surprise && surprise < min_surprise ? surprise : min_surprise; sum = sum + surprise; delete currentSystem; reservoir->reset(); } delete [] p_prime; delete [] p; // #pragma omp critical { if(type==CommaSeparated) { printf("%lf,%lf,%Lf,%Lf\n",constants.delta,constants.epsilon,sum/iterations,max_surprise); } if(type==PrettyPrint) { #pragma omp critical { print(beta); print(constants.delta); print(constants.epsilon); print(sum/iterations); print(max_surprise); print(sum); std::cout<<std::endl; } } if (type==Mathematica) { exit(1); } } delete reservoir; gsl_rng_free(localRNG); } <|endoftext|>
<commit_before>/*! * @file FgAircraft.cpp * * @brief Aircraft abstraction of FlightGear's aircrafts * * @author Andrey Shelest * @author Oleksii Aliakin ([email protected]) * @date Created Jan 04, 2015 * @date Modified Jul 30, 2015 */ #include "FgAircraftsModel.h" #include "log.h" #include <QtQml> #include <QTextCodec> #include <QApplication> #include <iostream> void logMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message) { Q_UNUSED(context); QString txt; switch (type) { case QtDebugMsg: txt = QString("Debug: %1").arg(message); break; case QtWarningMsg: txt = QString("Warning: %1").arg(message); break; case QtCriticalMsg: txt = QString("Critical: %1").arg(message); break; case QtFatalMsg: txt = QString("Fatal: %1").arg(message); abort(); default: // for Qt 5.5 it will be 'case QtInfoMsg:' txt = QString("Info: %1").arg(message); break; } /*FIXME to determine right location of this file!!!*/ // QFile outFile("log"); // outFile.open(QIODevice::WriteOnly | QIODevice::Append); // QTextStream ts(&outFile); // ts << txt << endl; std::cout << txt.toStdString() << std::endl; } int main(int argc, char *argv[]) { QApplication app(argc, argv); qInstallMessageHandler(logMessageHandler); qmlRegisterType<FgAircraftsModel>("fgap", 1, 0, "FgAircraftsModel"); QQmlApplicationEngine engine; #ifdef CONFIG_PATH QString qmlFilesPath = QString("%1/%2").arg( QCoreApplication::applicationDirPath(), FGAP_QML_MODULES_PATH); engine.addImportPath(qmlFilesPath); #endif engine.load(QUrl(QStringLiteral("qrc:qml/MainView.qml"))); return app.exec(); } <commit_msg>Fixed build.<commit_after>/*! * @file FgAircraft.cpp * * @brief Aircraft abstraction of FlightGear's aircrafts * * @author Andrey Shelest * @author Oleksii Aliakin ([email protected]) * @date Created Jan 04, 2015 * @date Modified Jul 30, 2015 */ #include "FgAircraftsModel.h" #include "log.h" #include <QtQml> #include <QTextCodec> #include <QApplication> #include <iostream> void logMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message) { Q_UNUSED(context); QString txt; switch (type) { case QtDebugMsg: txt = QString("Debug: %1").arg(message); break; case QtWarningMsg: txt = QString("Warning: %1").arg(message); break; case QtCriticalMsg: txt = QString("Critical: %1").arg(message); break; case QtFatalMsg: txt = QString("Fatal: %1").arg(message); abort(); default: // for Qt 5.5 it will be 'case QtInfoMsg:' txt = QString("Info: %1").arg(message); break; } /*FIXME to determine right location of this file!!!*/ // QFile outFile("log"); // outFile.open(QIODevice::WriteOnly | QIODevice::Append); // QTextStream ts(&outFile); // ts << txt << endl; std::cout << txt.toStdString() << std::endl; } int main(int argc, char *argv[]) { QApplication app(argc, argv); qInstallMessageHandler(logMessageHandler); qmlRegisterType<FgAircraftsModel>("fgap", 1, 0, "FgAircraftsModel"); QQmlApplicationEngine engine; #ifdef FGAP_QML_MODULES_PATH QString qmlFilesPath = QString("%1/%2").arg( QCoreApplication::applicationDirPath(), FGAP_QML_MODULES_PATH); engine.addImportPath(qmlFilesPath); #endif engine.load(QUrl(QStringLiteral("qrc:qml/MainView.qml"))); return app.exec(); } <|endoftext|>
<commit_before>/* Copyright (c) 2014, Patricio Gonzalez Vivo All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/shm.h> #include <sys/stat.h> #include <unistd.h> #include <signal.h> #include <map> #include "app.h" #include "utils.h" #include "gl/shader.h" #include "gl/vbo.h" #include "gl/texture.h" #include "3d/camera.h" #include "types/shapes.h" #include "ui/cursor.h" // GLOBAL VARIABLES //============================================================================ // static bool bPlay = true; // List of FILES to watch and the variable to communicate that between process struct WatchFile { std::string type; std::string path; int lastChange; }; std::vector<WatchFile> files; int* iHasChanged; // SHADER Shader shader; int iFrag = -1; std::string fragSource = ""; int iVert = -1; std::string vertSource = ""; // CAMERA Camera cam; float lat = 180.0; float lon = 0.0; // ASSETS Vbo* vbo; int iGeom = -1; glm::mat4 model_matrix = glm::mat4(1.); std::map<std::string,Texture*> textures; std::string outputFile = ""; // CURSOR Cursor cursor; bool bCursor = false; // Time limit float timeLimit = 0.0f; //================================================================= Functions void watchThread(); void onFileChange(); void renderThread(int argc, char **argv); void setup(); void draw(); void onExit(); // Main program //============================================================================ int main(int argc, char **argv){ // Load files to watch struct stat st; for (uint i = 1; i < argc ; i++){ std::string argument = std::string(argv[i]); if ( iFrag == -1 && ( haveExt(argument,"frag") || haveExt(argument,"fs") ) ) { int ierr = stat(argument.c_str(), &st); if (ierr != 0) { std::cerr << "Error watching file " << argv[i] << std::endl; } else { WatchFile file; file.type = "fragment"; file.path = argument; file.lastChange = st.st_mtime; files.push_back(file); iFrag = files.size()-1; } } else if ( iVert == -1 && ( haveExt(argument,"vert") || haveExt(argument,"vs") ) ) { int ierr = stat(argument.c_str(), &st); if (ierr != 0) { std::cerr << "Error watching file " << argument << std::endl; } else { WatchFile file; file.type = "vertex"; file.path = argument; file.lastChange = st.st_mtime; files.push_back(file); iVert = files.size()-1; } } else if ( iGeom == -1 && ( haveExt(argument,"ply") || haveExt(argument,"PLY") || haveExt(argument,"obj") || haveExt(argument,"OBJ") ) ) { int ierr = stat(argument.c_str(), &st); if (ierr != 0) { std::cerr << "Error watching file " << argument << std::endl; } else { WatchFile file; file.type = "geometry"; file.path = argument; file.lastChange = st.st_mtime; files.push_back(file); iGeom = files.size()-1; } } else if ( haveExt(argument,"png") || haveExt(argument,"PNG") || haveExt(argument,"jpg") || haveExt(argument,"JPG") || haveExt(argument,"jpeg") || haveExt(argument,"JPEG") ){ int ierr = stat(argument.c_str(), &st); if (ierr != 0) { // std::cerr << "Error watching file " << argument << std::endl; } else { WatchFile file; file.type = "image"; file.path = argument; file.lastChange = st.st_mtime; files.push_back(file); } } } // If no shader if( iFrag == -1 && iVert == -1 && iGeom == -1) { std::cerr << "Usage: " << argv[0] << " shader.frag [shader.vert] [mesh.(obj/.ply)] [texture.(png/jpg)] [-textureNameA texture.(png/jpg)] [-u] [-x x] [-y y] [-w width] [-h height] [-l/--livecoding] [--square] [-s seconds] [-o screenshot.png]\n"; return EXIT_FAILURE; } // Fork process with a shared variable // int shmId = shmget(IPC_PRIVATE, sizeof(bool), 0666); pid_t pid = fork(); iHasChanged = (int *) shmat(shmId, NULL, 0); switch(pid) { case -1: //error break; case 0: // child { *iHasChanged = -1; watchThread(); } break; default: { // Initialize openGL context initGL(argc,argv); // OpenGL Render Loop renderThread(argc,argv); // Kill the iNotify watcher once you finish kill(pid, SIGKILL); onExit(); } break; } shmctl(shmId, IPC_RMID, NULL); return 0; } // Watching Thread //============================================================================ void watchThread() { struct stat st; while(1){ for(uint i = 0; i < files.size(); i++){ if( *iHasChanged == -1 ){ stat(files[i].path.c_str(), &st); int date = st.st_mtime; if (date != files[i].lastChange ){ *iHasChanged = i; files[i].lastChange = date; } usleep(500000); } } } } void renderThread(int argc, char **argv) { // Prepare viewport glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT ); // Setup setup(); // Turn on Alpha blending glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); // Clear the background glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); int textureCounter = 0; //Load the the resources (textures) for (uint i = 1; i < argc ; i++){ std::string argument = std::string(argv[i]); if (argument == "-x" || argument == "-y" || argument == "-w" || argument == "--width" || argument == "-h" || argument == "--height" ) { i++; } else if ( argument == "--square" || argument == "-l" || argument == "--life-coding" ) { } else if ( argument == "-m" ) { bCursor = true; cursor.init(); } else if ( argument == "-s" || argument == "--sec") { i++; argument = std::string(argv[i]); timeLimit = getFloat(argument); std::cout << "Will exit in " << timeLimit << " seconds." << std::endl; } else if ( argument == "-o" ){ i++; argument = std::string(argv[i]); if( haveExt(argument,"png") ){ outputFile = argument; std::cout << "Will save screenshot to " << outputFile << " on exit." << std::endl; } else { std::cout << "At the moment screenshots only support PNG formats" << std::endl; } } else if (argument.find("-") == 0) { std::string parameterPair = argument.substr(argument.find_last_of('-')+1); i++; argument = std::string(argv[i]); Texture* tex = new Texture(); if( tex->load(argument) ){ textures[parameterPair] = tex; std::cout << "Loading " << argument << " as the following uniform: " << std::endl; std::cout << " uniform sampler2D " << parameterPair << "; // loaded"<< std::endl; std::cout << " uniform vec2 " << parameterPair << "Resolution;"<< std::endl; } } else if ( haveExt(argument,"png") || haveExt(argument,"PNG") || haveExt(argument,"jpg") || haveExt(argument,"JPG") || haveExt(argument,"jpeg") || haveExt(argument,"JPEG") ) { Texture* tex = new Texture(); if( tex->load(argument) ){ std::string name = "u_tex"+getString(textureCounter); textures[name] = tex; std::cout << "Loading " << argument << " as the following uniform: " << std::endl; std::cout << " uniform sampler2D " << name << "; // loaded"<< std::endl; std::cout << " uniform vec2 " << name << "Resolution;"<< std::endl; textureCounter++; } } } // Render Loop while (isGL() && bPlay) { // Update updateGL(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw draw(); // Swap the buffers renderGL(); if ( timeLimit > 0.0 && getTime() > timeLimit ) { onKeyPress('s'); bPlay = false; } } } void setup() { glEnable(GL_DEPTH_TEST); glFrontFace(GL_CCW); // Load Geometry // if ( iGeom == -1 ){ vbo = rect(0.0,0.0,1.0,1.0).getVbo(); } else { Mesh model; model.load(files[iGeom].path); vbo = model.getVbo(); glm::vec3 toCentroid = getCentroid(model.getVertices()); // model_matrix = glm::scale(glm::vec3(0.001)); model_matrix = glm::translate(-toCentroid); } // Build shader; // if ( iFrag != -1 ) { fragSource = ""; if(!loadFromPath(files[iFrag].path, &fragSource)) { return; } } else { fragSource = vbo->getVertexLayout()->getDefaultFragShader(); } if ( iVert != -1 ) { vertSource = ""; loadFromPath(files[iVert].path, &vertSource); } else { vertSource = vbo->getVertexLayout()->getDefaultVertShader(); } shader.load(fragSource,vertSource); cam.setViewport(getWindowWidth(),getWindowHeight()); cam.setPosition(glm::vec3(0.0,0.0,-3.)); } void draw(){ // Something change?? if(*iHasChanged != -1) { onFileChange(); *iHasChanged = -1; } shader.use(); shader.setUniform("u_time", getTime()); shader.setUniform("u_mouse", getMouseX(), getMouseY()); shader.setUniform("u_resolution",getWindowWidth(), getWindowHeight()); glm::mat4 mvp = glm::mat4(1.); if (iGeom != -1) { shader.setUniform("u_eye", -cam.getPosition()); shader.setUniform("u_normalMatrix", cam.getNormalMatrix()); shader.setUniform("u_modelMatrix", model_matrix); shader.setUniform("u_viewMatrix", cam.getViewMatrix()); shader.setUniform("u_projectionMatrix", cam.getProjectionMatrix()); mvp = cam.getProjectionViewMatrix() * model_matrix; } shader.setUniform("u_modelViewProjectionMatrix", mvp); unsigned int index = 0; for (std::map<std::string,Texture*>::iterator it = textures.begin(); it!=textures.end(); ++it) { shader.setUniform(it->first,it->second,index); shader.setUniform(it->first+"Resolution",it->second->getWidth(),it->second->getHeight()); index++; } vbo->draw(&shader); if(bCursor){ cursor.draw(); } } // Rendering Thread //============================================================================ void onFileChange(){ std::string type = files[*iHasChanged].type; std::string path = files[*iHasChanged].path; if ( type == "fragment" ){ fragSource = ""; if(loadFromPath(path, &fragSource)){ shader.detach(GL_FRAGMENT_SHADER | GL_VERTEX_SHADER); shader.load(fragSource,vertSource); } } else if ( type == "vertex" ){ vertSource = ""; if(loadFromPath(path, &vertSource)){ shader.detach(GL_FRAGMENT_SHADER | GL_VERTEX_SHADER); shader.load(fragSource,vertSource); } } else if ( type == "geometry" ){ // TODO } else if ( type == "image" ){ for (std::map<std::string,Texture*>::iterator it = textures.begin(); it!=textures.end(); ++it) { if ( path == it->second->getFilePath() ){ it->second->load(path); break; } } } } void onKeyPress(int _key) { if( _key == 'q' || _key == 'Q' || _key == 's' || _key == 'S' ){ if (outputFile != "") { unsigned char* pixels = new unsigned char[getWindowWidth()*getWindowHeight()*4]; glReadPixels(0, 0, getWindowWidth(), getWindowHeight(), GL_RGBA, GL_UNSIGNED_BYTE, pixels); Texture::savePixels(outputFile, pixels, getWindowWidth(), getWindowHeight()); } } if ( _key == 'q' || _key == 'Q'){ bPlay = false; } } void onMouseMove(float _x, float _y) { } void onMouseClick(float _x, float _y, int _button) { } void onMouseDrag(float _x, float _y, int _button) { if (_button == 1){ float dist = glm::length(cam.getPosition()); lat -= getMouseVelX(); lon -= getMouseVelY()*0.5; cam.orbit(lat,lon,dist); cam.lookAt(glm::vec3(0.0)); } else { float dist = glm::length(cam.getPosition()); dist += (-.008f * getMouseVelY()); if(dist > 0.0f){ cam.setPosition( -dist * cam.getZAxis() ); cam.lookAt(glm::vec3(0.0)); } } } void onViewportResize(int _newWidth, int _newHeight) { cam.setViewport(_newWidth,_newHeight); } void onExit() { // clear screen glClear( GL_COLOR_BUFFER_BIT ); // close openGL instance closeGL(); // DELETE RESOURCES for (std::map<std::string,Texture*>::iterator i = textures.begin(); i != textures.end(); ++i) { delete i->second; i->second = NULL; } textures.clear(); delete vbo; }<commit_msg>add default swap interval to prevent wasted CPU cycles<commit_after>/* Copyright (c) 2014, Patricio Gonzalez Vivo All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/shm.h> #include <sys/stat.h> #include <unistd.h> #include <signal.h> #include <map> #include "app.h" #include "utils.h" #include "gl/shader.h" #include "gl/vbo.h" #include "gl/texture.h" #include "3d/camera.h" #include "types/shapes.h" #include "ui/cursor.h" // GLOBAL VARIABLES //============================================================================ // static bool bPlay = true; // List of FILES to watch and the variable to communicate that between process struct WatchFile { std::string type; std::string path; int lastChange; }; std::vector<WatchFile> files; int* iHasChanged; // SHADER Shader shader; int iFrag = -1; std::string fragSource = ""; int iVert = -1; std::string vertSource = ""; // CAMERA Camera cam; float lat = 180.0; float lon = 0.0; // ASSETS Vbo* vbo; int iGeom = -1; glm::mat4 model_matrix = glm::mat4(1.); std::map<std::string,Texture*> textures; std::string outputFile = ""; // CURSOR Cursor cursor; bool bCursor = false; // Time limit float timeLimit = 0.0f; //================================================================= Functions void watchThread(); void onFileChange(); void renderThread(int argc, char **argv); void setup(); void draw(); void onExit(); // Main program //============================================================================ int main(int argc, char **argv){ // Load files to watch struct stat st; for (uint i = 1; i < argc ; i++){ std::string argument = std::string(argv[i]); if ( iFrag == -1 && ( haveExt(argument,"frag") || haveExt(argument,"fs") ) ) { int ierr = stat(argument.c_str(), &st); if (ierr != 0) { std::cerr << "Error watching file " << argv[i] << std::endl; } else { WatchFile file; file.type = "fragment"; file.path = argument; file.lastChange = st.st_mtime; files.push_back(file); iFrag = files.size()-1; } } else if ( iVert == -1 && ( haveExt(argument,"vert") || haveExt(argument,"vs") ) ) { int ierr = stat(argument.c_str(), &st); if (ierr != 0) { std::cerr << "Error watching file " << argument << std::endl; } else { WatchFile file; file.type = "vertex"; file.path = argument; file.lastChange = st.st_mtime; files.push_back(file); iVert = files.size()-1; } } else if ( iGeom == -1 && ( haveExt(argument,"ply") || haveExt(argument,"PLY") || haveExt(argument,"obj") || haveExt(argument,"OBJ") ) ) { int ierr = stat(argument.c_str(), &st); if (ierr != 0) { std::cerr << "Error watching file " << argument << std::endl; } else { WatchFile file; file.type = "geometry"; file.path = argument; file.lastChange = st.st_mtime; files.push_back(file); iGeom = files.size()-1; } } else if ( haveExt(argument,"png") || haveExt(argument,"PNG") || haveExt(argument,"jpg") || haveExt(argument,"JPG") || haveExt(argument,"jpeg") || haveExt(argument,"JPEG") ){ int ierr = stat(argument.c_str(), &st); if (ierr != 0) { // std::cerr << "Error watching file " << argument << std::endl; } else { WatchFile file; file.type = "image"; file.path = argument; file.lastChange = st.st_mtime; files.push_back(file); } } } // If no shader if( iFrag == -1 && iVert == -1 && iGeom == -1) { std::cerr << "Usage: " << argv[0] << " shader.frag [shader.vert] [mesh.(obj/.ply)] [texture.(png/jpg)] [-textureNameA texture.(png/jpg)] [-u] [-x x] [-y y] [-w width] [-h height] [-l/--livecoding] [--square] [-s seconds] [-o screenshot.png]\n"; return EXIT_FAILURE; } // Fork process with a shared variable // int shmId = shmget(IPC_PRIVATE, sizeof(bool), 0666); pid_t pid = fork(); iHasChanged = (int *) shmat(shmId, NULL, 0); switch(pid) { case -1: //error break; case 0: // child { *iHasChanged = -1; watchThread(); } break; default: { // Initialize openGL context initGL(argc,argv); // OpenGL Render Loop renderThread(argc,argv); // Kill the iNotify watcher once you finish kill(pid, SIGKILL); onExit(); } break; } shmctl(shmId, IPC_RMID, NULL); return 0; } // Watching Thread //============================================================================ void watchThread() { struct stat st; while(1){ for(uint i = 0; i < files.size(); i++){ if( *iHasChanged == -1 ){ stat(files[i].path.c_str(), &st); int date = st.st_mtime; if (date != files[i].lastChange ){ *iHasChanged = i; files[i].lastChange = date; } usleep(500000); } } } } void renderThread(int argc, char **argv) { // Prepare viewport glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT ); // Setup setup(); // Turn on Alpha blending glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); // Clear the background glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); int textureCounter = 0; //Load the the resources (textures) for (uint i = 1; i < argc ; i++){ std::string argument = std::string(argv[i]); if (argument == "-x" || argument == "-y" || argument == "-w" || argument == "--width" || argument == "-h" || argument == "--height" ) { i++; } else if ( argument == "--square" || argument == "-l" || argument == "--life-coding" ) { } else if ( argument == "-m" ) { bCursor = true; cursor.init(); } else if ( argument == "-s" || argument == "--sec") { i++; argument = std::string(argv[i]); timeLimit = getFloat(argument); std::cout << "Will exit in " << timeLimit << " seconds." << std::endl; } else if ( argument == "-o" ){ i++; argument = std::string(argv[i]); if( haveExt(argument,"png") ){ outputFile = argument; std::cout << "Will save screenshot to " << outputFile << " on exit." << std::endl; } else { std::cout << "At the moment screenshots only support PNG formats" << std::endl; } } else if (argument.find("-") == 0) { std::string parameterPair = argument.substr(argument.find_last_of('-')+1); i++; argument = std::string(argv[i]); Texture* tex = new Texture(); if( tex->load(argument) ){ textures[parameterPair] = tex; std::cout << "Loading " << argument << " as the following uniform: " << std::endl; std::cout << " uniform sampler2D " << parameterPair << "; // loaded"<< std::endl; std::cout << " uniform vec2 " << parameterPair << "Resolution;"<< std::endl; } } else if ( haveExt(argument,"png") || haveExt(argument,"PNG") || haveExt(argument,"jpg") || haveExt(argument,"JPG") || haveExt(argument,"jpeg") || haveExt(argument,"JPEG") ) { Texture* tex = new Texture(); if( tex->load(argument) ){ std::string name = "u_tex"+getString(textureCounter); textures[name] = tex; std::cout << "Loading " << argument << " as the following uniform: " << std::endl; std::cout << " uniform sampler2D " << name << "; // loaded"<< std::endl; std::cout << " uniform vec2 " << name << "Resolution;"<< std::endl; textureCounter++; } } } // Render Loop while (isGL() && bPlay) { // Update updateGL(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw draw(); // Swap the buffers renderGL(); if ( timeLimit > 0.0 && getTime() > timeLimit ) { onKeyPress('s'); bPlay = false; } } } void setup() { glfwSwapInterval(1); glEnable(GL_DEPTH_TEST); glFrontFace(GL_CCW); // Load Geometry // if ( iGeom == -1 ){ vbo = rect(0.0,0.0,1.0,1.0).getVbo(); } else { Mesh model; model.load(files[iGeom].path); vbo = model.getVbo(); glm::vec3 toCentroid = getCentroid(model.getVertices()); // model_matrix = glm::scale(glm::vec3(0.001)); model_matrix = glm::translate(-toCentroid); } // Build shader; // if ( iFrag != -1 ) { fragSource = ""; if(!loadFromPath(files[iFrag].path, &fragSource)) { return; } } else { fragSource = vbo->getVertexLayout()->getDefaultFragShader(); } if ( iVert != -1 ) { vertSource = ""; loadFromPath(files[iVert].path, &vertSource); } else { vertSource = vbo->getVertexLayout()->getDefaultVertShader(); } shader.load(fragSource,vertSource); cam.setViewport(getWindowWidth(),getWindowHeight()); cam.setPosition(glm::vec3(0.0,0.0,-3.)); } void draw(){ // Something change?? if(*iHasChanged != -1) { onFileChange(); *iHasChanged = -1; } shader.use(); shader.setUniform("u_time", getTime()); shader.setUniform("u_mouse", getMouseX(), getMouseY()); shader.setUniform("u_resolution",getWindowWidth(), getWindowHeight()); glm::mat4 mvp = glm::mat4(1.); if (iGeom != -1) { shader.setUniform("u_eye", -cam.getPosition()); shader.setUniform("u_normalMatrix", cam.getNormalMatrix()); shader.setUniform("u_modelMatrix", model_matrix); shader.setUniform("u_viewMatrix", cam.getViewMatrix()); shader.setUniform("u_projectionMatrix", cam.getProjectionMatrix()); mvp = cam.getProjectionViewMatrix() * model_matrix; } shader.setUniform("u_modelViewProjectionMatrix", mvp); unsigned int index = 0; for (std::map<std::string,Texture*>::iterator it = textures.begin(); it!=textures.end(); ++it) { shader.setUniform(it->first,it->second,index); shader.setUniform(it->first+"Resolution",it->second->getWidth(),it->second->getHeight()); index++; } vbo->draw(&shader); if(bCursor){ cursor.draw(); } } // Rendering Thread //============================================================================ void onFileChange(){ std::string type = files[*iHasChanged].type; std::string path = files[*iHasChanged].path; if ( type == "fragment" ){ fragSource = ""; if(loadFromPath(path, &fragSource)){ shader.detach(GL_FRAGMENT_SHADER | GL_VERTEX_SHADER); shader.load(fragSource,vertSource); } } else if ( type == "vertex" ){ vertSource = ""; if(loadFromPath(path, &vertSource)){ shader.detach(GL_FRAGMENT_SHADER | GL_VERTEX_SHADER); shader.load(fragSource,vertSource); } } else if ( type == "geometry" ){ // TODO } else if ( type == "image" ){ for (std::map<std::string,Texture*>::iterator it = textures.begin(); it!=textures.end(); ++it) { if ( path == it->second->getFilePath() ){ it->second->load(path); break; } } } } void onKeyPress(int _key) { if( _key == 'q' || _key == 'Q' || _key == 's' || _key == 'S' ){ if (outputFile != "") { unsigned char* pixels = new unsigned char[getWindowWidth()*getWindowHeight()*4]; glReadPixels(0, 0, getWindowWidth(), getWindowHeight(), GL_RGBA, GL_UNSIGNED_BYTE, pixels); Texture::savePixels(outputFile, pixels, getWindowWidth(), getWindowHeight()); } } if ( _key == 'q' || _key == 'Q'){ bPlay = false; } } void onMouseMove(float _x, float _y) { } void onMouseClick(float _x, float _y, int _button) { } void onMouseDrag(float _x, float _y, int _button) { if (_button == 1){ float dist = glm::length(cam.getPosition()); lat -= getMouseVelX(); lon -= getMouseVelY()*0.5; cam.orbit(lat,lon,dist); cam.lookAt(glm::vec3(0.0)); } else { float dist = glm::length(cam.getPosition()); dist += (-.008f * getMouseVelY()); if(dist > 0.0f){ cam.setPosition( -dist * cam.getZAxis() ); cam.lookAt(glm::vec3(0.0)); } } } void onViewportResize(int _newWidth, int _newHeight) { cam.setViewport(_newWidth,_newHeight); } void onExit() { // clear screen glClear( GL_COLOR_BUFFER_BIT ); // close openGL instance closeGL(); // DELETE RESOURCES for (std::map<std::string,Texture*>::iterator i = textures.begin(); i != textures.end(); ++i) { delete i->second; i->second = NULL; } textures.clear(); delete vbo; } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 OpenALPR Technology, Inc. * Open source Automated License Plate Recognition [http://www.openalpr.com] * * This file is part of OpenALPR. * * OpenALPR is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3 as published by the Free Software Foundation * * 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 <cstdio> #include <sstream> #include <iostream> #include <iterator> #include <algorithm> #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "tclap/CmdLine.h" #include "support/filesystem.h" #include "support/timing.h" #include "support/platform.h" #include "video/videobuffer.h" #include "motiondetector.h" #include "alpr.h" using namespace alpr; const std::string MAIN_WINDOW_NAME = "ALPR main window"; const bool SAVE_LAST_VIDEO_STILL = false; const std::string LAST_VIDEO_STILL_LOCATION = "/tmp/laststill.jpg"; MotionDetector motiondetector; bool do_motiondetection = true; /** Function Headers */ bool detectandshow(Alpr* alpr, cv::Mat frame, std::string region, bool writeJson); bool is_supported_image(std::string image_file); bool measureProcessingTime = false; std::string templatePattern; // This boolean is set to false when the user hits terminates (e.g., CTRL+C ) // so we can end infinite loops for things like video processing. bool program_active = true; int main( int argc, const char** argv ) { std::vector<std::string> filenames; std::string configFile = ""; bool outputJson = false; int seektoms = 0; bool detectRegion = false; std::string country; int topn; bool debug_mode = false; TCLAP::CmdLine cmd("OpenAlpr Command Line Utility", ' ', Alpr::getVersion()); TCLAP::UnlabeledMultiArg<std::string> fileArg( "image_file", "Image containing license plates", true, "", "image_file_path" ); TCLAP::ValueArg<std::string> countryCodeArg("c","country","Country code to identify (either us for USA or eu for Europe). Default=us",false, "us" ,"country_code"); TCLAP::ValueArg<int> seekToMsArg("","seek","Seek to the specified millisecond in a video file. Default=0",false, 0 ,"integer_ms"); TCLAP::ValueArg<std::string> configFileArg("","config","Path to the openalpr.conf file",false, "" ,"config_file"); TCLAP::ValueArg<std::string> templatePatternArg("p","pattern","Attempt to match the plate number against a plate pattern (e.g., md for Maryland, ca for California)",false, "" ,"pattern code"); TCLAP::ValueArg<int> topNArg("n","topn","Max number of possible plate numbers to return. Default=10",false, 10 ,"topN"); TCLAP::SwitchArg jsonSwitch("j","json","Output recognition results in JSON format. Default=off", cmd, false); TCLAP::SwitchArg debugSwitch("","debug","Enable debug output. Default=off", cmd, false); TCLAP::SwitchArg detectRegionSwitch("d","detect_region","Attempt to detect the region of the plate image. [Experimental] Default=off", cmd, false); TCLAP::SwitchArg clockSwitch("","clock","Measure/print the total time to process image and all plates. Default=off", cmd, false); TCLAP::SwitchArg motiondetect("", "motion", "Use motion detection on video file or stream. Default=off", cmd, false); try { cmd.add( templatePatternArg ); cmd.add( seekToMsArg ); cmd.add( topNArg ); cmd.add( configFileArg ); cmd.add( fileArg ); cmd.add( countryCodeArg ); if (cmd.parse( argc, argv ) == false) { // Error occurred while parsing. Exit now. return 1; } filenames = fileArg.getValue(); country = countryCodeArg.getValue(); seektoms = seekToMsArg.getValue(); outputJson = jsonSwitch.getValue(); debug_mode = debugSwitch.getValue(); configFile = configFileArg.getValue(); detectRegion = detectRegionSwitch.getValue(); templatePattern = templatePatternArg.getValue(); topn = topNArg.getValue(); measureProcessingTime = clockSwitch.getValue(); do_motiondetection = motiondetect.getValue(); } catch (TCLAP::ArgException &e) // catch any exceptions { std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; return 1; } cv::Mat frame; Alpr alpr(country, configFile); alpr.setTopN(topn); if (debug_mode) { alpr.getConfig()->setDebug(true); } if (detectRegion) alpr.setDetectRegion(detectRegion); if (templatePattern.empty() == false) alpr.setDefaultRegion(templatePattern); if (alpr.isLoaded() == false) { std::cerr << "Error loading OpenALPR" << std::endl; return 1; } for (unsigned int i = 0; i < filenames.size(); i++) { std::string filename = filenames[i]; if (filename == "stdin") { std::string filename; while (std::getline(std::cin, filename)) { if (fileExists(filename.c_str())) { frame = cv::imread(filename); detectandshow(&alpr, frame, "", outputJson); } else { std::cerr << "Image file not found: " << filename << std::endl; } } } else if (filename == "webcam") { int framenum = 0; cv::VideoCapture cap(0); if (!cap.isOpened()) { std::cout << "Error opening webcam" << std::endl; return 1; } while (cap.read(frame)) { if (framenum == 0) motiondetector.ResetMotionDetection(&frame); detectandshow(&alpr, frame, "", outputJson); sleep_ms(10); framenum++; } } else if (startsWith(filename, "http://") || startsWith(filename, "https://")) { int framenum = 0; VideoBuffer videoBuffer; videoBuffer.connect(filename, 5); cv::Mat latestFrame; while (program_active) { std::vector<cv::Rect> regionsOfInterest; int response = videoBuffer.getLatestFrame(&latestFrame, regionsOfInterest); if (response != -1) { if (framenum == 0) motiondetector.ResetMotionDetection(&latestFrame); detectandshow(&alpr, latestFrame, "", outputJson); } // Sleep 10ms sleep_ms(10); framenum++; } videoBuffer.disconnect(); std::cout << "Video processing ended" << std::endl; } else if (hasEndingInsensitive(filename, ".avi") || hasEndingInsensitive(filename, ".mp4") || hasEndingInsensitive(filename, ".webm") || hasEndingInsensitive(filename, ".flv") || hasEndingInsensitive(filename, ".mjpg") || hasEndingInsensitive(filename, ".mjpeg") || hasEndingInsensitive(filename, ".mkv") ) { if (fileExists(filename.c_str())) { int framenum = 0; cv::VideoCapture cap = cv::VideoCapture(); cap.open(filename); cap.set(CV_CAP_PROP_POS_MSEC, seektoms); while (cap.read(frame)) { if (SAVE_LAST_VIDEO_STILL) { cv::imwrite(LAST_VIDEO_STILL_LOCATION, frame); } if (!outputJson) std::cout << "Frame: " << framenum << std::endl; if (framenum == 0) motiondetector.ResetMotionDetection(&frame); detectandshow(&alpr, frame, "", outputJson); //create a 1ms delay sleep_ms(1); framenum++; } } else { std::cerr << "Video file not found: " << filename << std::endl; } } else if (is_supported_image(filename)) { if (fileExists(filename.c_str())) { frame = cv::imread(filename); bool plate_found = detectandshow(&alpr, frame, "", outputJson); if (!plate_found && !outputJson) std::cout << "No license plates found." << std::endl; } else { std::cerr << "Image file not found: " << filename << std::endl; } } else if (DirectoryExists(filename.c_str())) { std::vector<std::string> files = getFilesInDir(filename.c_str()); std::sort(files.begin(), files.end(), stringCompare); for (int i = 0; i < files.size(); i++) { if (is_supported_image(files[i])) { std::string fullpath = filename + "/" + files[i]; std::cout << fullpath << std::endl; frame = cv::imread(fullpath.c_str()); if (detectandshow(&alpr, frame, "", outputJson)) { //while ((char) cv::waitKey(50) != 'c') { } } else { //cv::waitKey(50); } } } } else { std::cerr << "Unknown file type" << std::endl; return 1; } } return 0; } bool is_supported_image(std::string image_file) { return (hasEndingInsensitive(image_file, ".png") || hasEndingInsensitive(image_file, ".jpg") || hasEndingInsensitive(image_file, ".tif") || hasEndingInsensitive(image_file, ".bmp") || hasEndingInsensitive(image_file, ".jpeg") || hasEndingInsensitive(image_file, ".gif")); } bool detectandshow( Alpr* alpr, cv::Mat frame, std::string region, bool writeJson) { timespec startTime; getTimeMonotonic(&startTime); std::vector<AlprRegionOfInterest> regionsOfInterest; if (do_motiondetection) { cv::Rect rectan = motiondetector.MotionDetect(&frame); if (rectan.width>0) regionsOfInterest.push_back(AlprRegionOfInterest(rectan.x, rectan.y, rectan.width, rectan.height)); } else regionsOfInterest.push_back(AlprRegionOfInterest(0, 0, frame.cols, frame.rows)); AlprResults results; if (regionsOfInterest.size()>0) results = alpr->recognize(frame.data, frame.elemSize(), frame.cols, frame.rows, regionsOfInterest); timespec endTime; getTimeMonotonic(&endTime); double totalProcessingTime = diffclock(startTime, endTime); if (measureProcessingTime) std::cout << "Total Time to process image: " << totalProcessingTime << "ms." << std::endl; if (writeJson) { std::cout << alpr->toJson( results ) << std::endl; } else { for (int i = 0; i < results.plates.size(); i++) { std::cout << "plate" << i << ": " << results.plates[i].topNPlates.size() << " results"; if (measureProcessingTime) std::cout << " -- Processing Time = " << results.plates[i].processing_time_ms << "ms."; std::cout << std::endl; if (results.plates[i].regionConfidence > 0) std::cout << "State ID: " << results.plates[i].region << " (" << results.plates[i].regionConfidence << "% confidence)" << std::endl; for (int k = 0; k < results.plates[i].topNPlates.size(); k++) { // Replace the multiline newline character with a dash std::string no_newline = results.plates[i].topNPlates[k].characters; std::replace(no_newline.begin(), no_newline.end(), '\n','-'); std::cout << " - " << no_newline << "\t confidence: " << results.plates[i].topNPlates[k].overall_confidence; if (templatePattern.size() > 0 || results.plates[i].regionConfidence > 0) std::cout << "\t pattern_match: " << results.plates[i].topNPlates[k].matches_template; std::cout << std::endl; } } } return results.plates.size() > 0; } <commit_msg>Fix for alprd to allow input as /dev/video* where * is a number that corolate to the webcam on the system. Tested on OSX and Debian system (Ubuntu and RPI).<commit_after>/* * Copyright (c) 2015 OpenALPR Technology, Inc. * Open source Automated License Plate Recognition [http://www.openalpr.com] * * This file is part of OpenALPR. * * OpenALPR is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3 as published by the Free Software Foundation * * 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 <cstdio> #include <sstream> #include <iostream> #include <iterator> #include <algorithm> #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "tclap/CmdLine.h" #include "support/filesystem.h" #include "support/timing.h" #include "support/platform.h" #include "video/videobuffer.h" #include "motiondetector.h" #include "alpr.h" using namespace alpr; const std::string MAIN_WINDOW_NAME = "ALPR main window"; const bool SAVE_LAST_VIDEO_STILL = false; const std::string LAST_VIDEO_STILL_LOCATION = "/tmp/laststill.jpg"; MotionDetector motiondetector; bool do_motiondetection = true; /** Function Headers */ bool detectandshow(Alpr* alpr, cv::Mat frame, std::string region, bool writeJson); bool is_supported_image(std::string image_file); bool measureProcessingTime = false; std::string templatePattern; // This boolean is set to false when the user hits terminates (e.g., CTRL+C ) // so we can end infinite loops for things like video processing. bool program_active = true; int main( int argc, const char** argv ) { std::vector<std::string> filenames; std::string configFile = ""; bool outputJson = false; int seektoms = 0; bool detectRegion = false; std::string country; int topn; bool debug_mode = false; TCLAP::CmdLine cmd("OpenAlpr Command Line Utility", ' ', Alpr::getVersion()); TCLAP::UnlabeledMultiArg<std::string> fileArg( "image_file", "Image containing license plates", true, "", "image_file_path" ); TCLAP::ValueArg<std::string> countryCodeArg("c","country","Country code to identify (either us for USA or eu for Europe). Default=us",false, "us" ,"country_code"); TCLAP::ValueArg<int> seekToMsArg("","seek","Seek to the specified millisecond in a video file. Default=0",false, 0 ,"integer_ms"); TCLAP::ValueArg<std::string> configFileArg("","config","Path to the openalpr.conf file",false, "" ,"config_file"); TCLAP::ValueArg<std::string> templatePatternArg("p","pattern","Attempt to match the plate number against a plate pattern (e.g., md for Maryland, ca for California)",false, "" ,"pattern code"); TCLAP::ValueArg<int> topNArg("n","topn","Max number of possible plate numbers to return. Default=10",false, 10 ,"topN"); TCLAP::SwitchArg jsonSwitch("j","json","Output recognition results in JSON format. Default=off", cmd, false); TCLAP::SwitchArg debugSwitch("","debug","Enable debug output. Default=off", cmd, false); TCLAP::SwitchArg detectRegionSwitch("d","detect_region","Attempt to detect the region of the plate image. [Experimental] Default=off", cmd, false); TCLAP::SwitchArg clockSwitch("","clock","Measure/print the total time to process image and all plates. Default=off", cmd, false); TCLAP::SwitchArg motiondetect("", "motion", "Use motion detection on video file or stream. Default=off", cmd, false); try { cmd.add( templatePatternArg ); cmd.add( seekToMsArg ); cmd.add( topNArg ); cmd.add( configFileArg ); cmd.add( fileArg ); cmd.add( countryCodeArg ); if (cmd.parse( argc, argv ) == false) { // Error occurred while parsing. Exit now. return 1; } filenames = fileArg.getValue(); country = countryCodeArg.getValue(); seektoms = seekToMsArg.getValue(); outputJson = jsonSwitch.getValue(); debug_mode = debugSwitch.getValue(); configFile = configFileArg.getValue(); detectRegion = detectRegionSwitch.getValue(); templatePattern = templatePatternArg.getValue(); topn = topNArg.getValue(); measureProcessingTime = clockSwitch.getValue(); do_motiondetection = motiondetect.getValue(); } catch (TCLAP::ArgException &e) // catch any exceptions { std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; return 1; } cv::Mat frame; Alpr alpr(country, configFile); alpr.setTopN(topn); if (debug_mode) { alpr.getConfig()->setDebug(true); } if (detectRegion) alpr.setDetectRegion(detectRegion); if (templatePattern.empty() == false) alpr.setDefaultRegion(templatePattern); if (alpr.isLoaded() == false) { std::cerr << "Error loading OpenALPR" << std::endl; return 1; } for (unsigned int i = 0; i < filenames.size(); i++) { std::string filename = filenames[i]; if (filename == "stdin") { std::string filename; while (std::getline(std::cin, filename)) { if (fileExists(filename.c_str())) { frame = cv::imread(filename); detectandshow(&alpr, frame, "", outputJson); } else { std::cerr << "Image file not found: " << filename << std::endl; } } } else if (startsWith(filename, "/dev/video")) { int webcamnumber = 0; if(filename.length() > 10) { std::string webcam_str_num; for(int a = 11; a <= filename.length(); a=a+1) { webcam_str_num.append(filename,a,1); } int webcamnumber = atoi(webcam_str_num.c_str()); } else { std::cout << "Incorrect Webcam Address" << std::endl; return 1; } int framenum = 0; cv::VideoCapture cap(webcamnumber); if (!cap.isOpened()) { std::cout << "Error opening webcam" << std::endl; return 1; } } else if (filename == "webcam") { int framenum = 0; cv::VideoCapture cap(0); if (!cap.isOpened()) { std::cout << "Error opening webcam" << std::endl; return 1; } while (cap.read(frame)) { if (framenum == 0) motiondetector.ResetMotionDetection(&frame); detectandshow(&alpr, frame, "", outputJson); sleep_ms(10); framenum++; } } else if (startsWith(filename, "http://") || startsWith(filename, "https://")) { int framenum = 0; VideoBuffer videoBuffer; videoBuffer.connect(filename, 5); cv::Mat latestFrame; while (program_active) { std::vector<cv::Rect> regionsOfInterest; int response = videoBuffer.getLatestFrame(&latestFrame, regionsOfInterest); if (response != -1) { if (framenum == 0) motiondetector.ResetMotionDetection(&latestFrame); detectandshow(&alpr, latestFrame, "", outputJson); } // Sleep 10ms sleep_ms(10); framenum++; } videoBuffer.disconnect(); std::cout << "Video processing ended" << std::endl; } else if (hasEndingInsensitive(filename, ".avi") || hasEndingInsensitive(filename, ".mp4") || hasEndingInsensitive(filename, ".webm") || hasEndingInsensitive(filename, ".flv") || hasEndingInsensitive(filename, ".mjpg") || hasEndingInsensitive(filename, ".mjpeg") || hasEndingInsensitive(filename, ".mkv") ) { if (fileExists(filename.c_str())) { int framenum = 0; cv::VideoCapture cap = cv::VideoCapture(); cap.open(filename); cap.set(CV_CAP_PROP_POS_MSEC, seektoms); while (cap.read(frame)) { if (SAVE_LAST_VIDEO_STILL) { cv::imwrite(LAST_VIDEO_STILL_LOCATION, frame); } if (!outputJson) std::cout << "Frame: " << framenum << std::endl; if (framenum == 0) motiondetector.ResetMotionDetection(&frame); detectandshow(&alpr, frame, "", outputJson); //create a 1ms delay sleep_ms(1); framenum++; } } else { std::cerr << "Video file not found: " << filename << std::endl; } } else if (is_supported_image(filename)) { if (fileExists(filename.c_str())) { frame = cv::imread(filename); bool plate_found = detectandshow(&alpr, frame, "", outputJson); if (!plate_found && !outputJson) std::cout << "No license plates found." << std::endl; } else { std::cerr << "Image file not found: " << filename << std::endl; } } else if (DirectoryExists(filename.c_str())) { std::vector<std::string> files = getFilesInDir(filename.c_str()); std::sort(files.begin(), files.end(), stringCompare); for (int i = 0; i < files.size(); i++) { if (is_supported_image(files[i])) { std::string fullpath = filename + "/" + files[i]; std::cout << fullpath << std::endl; frame = cv::imread(fullpath.c_str()); if (detectandshow(&alpr, frame, "", outputJson)) { //while ((char) cv::waitKey(50) != 'c') { } } else { //cv::waitKey(50); } } } } else { std::cerr << "Unknown file type" << std::endl; return 1; } } return 0; } bool is_supported_image(std::string image_file) { return (hasEndingInsensitive(image_file, ".png") || hasEndingInsensitive(image_file, ".jpg") || hasEndingInsensitive(image_file, ".tif") || hasEndingInsensitive(image_file, ".bmp") || hasEndingInsensitive(image_file, ".jpeg") || hasEndingInsensitive(image_file, ".gif")); } bool detectandshow( Alpr* alpr, cv::Mat frame, std::string region, bool writeJson) { timespec startTime; getTimeMonotonic(&startTime); std::vector<AlprRegionOfInterest> regionsOfInterest; if (do_motiondetection) { cv::Rect rectan = motiondetector.MotionDetect(&frame); if (rectan.width>0) regionsOfInterest.push_back(AlprRegionOfInterest(rectan.x, rectan.y, rectan.width, rectan.height)); } else regionsOfInterest.push_back(AlprRegionOfInterest(0, 0, frame.cols, frame.rows)); AlprResults results; if (regionsOfInterest.size()>0) results = alpr->recognize(frame.data, frame.elemSize(), frame.cols, frame.rows, regionsOfInterest); timespec endTime; getTimeMonotonic(&endTime); double totalProcessingTime = diffclock(startTime, endTime); if (measureProcessingTime) std::cout << "Total Time to process image: " << totalProcessingTime << "ms." << std::endl; if (writeJson) { std::cout << alpr->toJson( results ) << std::endl; } else { for (int i = 0; i < results.plates.size(); i++) { std::cout << "plate" << i << ": " << results.plates[i].topNPlates.size() << " results"; if (measureProcessingTime) std::cout << " -- Processing Time = " << results.plates[i].processing_time_ms << "ms."; std::cout << std::endl; if (results.plates[i].regionConfidence > 0) std::cout << "State ID: " << results.plates[i].region << " (" << results.plates[i].regionConfidence << "% confidence)" << std::endl; for (int k = 0; k < results.plates[i].topNPlates.size(); k++) { // Replace the multiline newline character with a dash std::string no_newline = results.plates[i].topNPlates[k].characters; std::replace(no_newline.begin(), no_newline.end(), '\n','-'); std::cout << " - " << no_newline << "\t confidence: " << results.plates[i].topNPlates[k].overall_confidence; if (templatePattern.size() > 0 || results.plates[i].regionConfidence > 0) std::cout << "\t pattern_match: " << results.plates[i].topNPlates[k].matches_template; std::cout << std::endl; } } } return results.plates.size() > 0; } <|endoftext|>
<commit_before>//=====================================================================// /*! @file @brief ソケット、データ受け取りサンプル @n Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 ([email protected]) */ //=====================================================================// #include <iostream> #include <string> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> namespace { } int main(int argc, char* argv[]); int main(int argc, char* argv[]) { // サーバーソケット作成 int sock = socket(AF_INET, SOCK_STREAM, 0); if(sock == -1) { perror("socket"); return 1; } // struct sockaddr_in 作成 struct sockaddr_in sa = {0}; sa.sin_family = AF_INET; // 接続ポート3000 sa.sin_port = htons(3000); // 接続先は、任意とする。 sa.sin_addr.s_addr = htonl(INADDR_ANY); // バインド if(bind(sock, (struct sockaddr*) &sa, sizeof(struct sockaddr_in)) == -1) { perror("bind"); close(sock); return 1; } // リッスン if(listen(sock, 128) == -1) { perror("listen"); close(sock); return 1; } // クライアントの接続を待つ int fd = accept(sock, NULL, NULL); if(fd == -1) { perror("accept"); close(sock); return 1; } std::string line; bool term = false; while(!term) { // 受信 char buffer[4096]; int recv_size = read(fd, buffer, sizeof(buffer) - 1); if(recv_size == -1) { perror("read"); close(fd); close(sock); return 1; } // 内容を解析して表示 for(int i = 0; i < recv_size; ++i) { char ch = buffer[i]; if(ch == '\r') continue; if(ch == '\n') { std::cout << line << std::endl; if(line == "end") term = true; line.clear(); } else { line += ch; } } } // 接続のクローズ if(close(fd) == -1) { perror("close"); close(sock); return 1; } close(sock); } <commit_msg>update status message<commit_after>//=====================================================================// /*! @file @brief ソケット、サーバー、データ受け取りサンプル @n Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 ([email protected]) */ //=====================================================================// #include <iostream> #include <string> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> namespace { } int main(int argc, char* argv[]); int main(int argc, char* argv[]) { // サーバーソケット作成 int sock = socket(AF_INET, SOCK_STREAM, 0); if(sock == -1) { perror("socket"); return 1; } std::cout << "socket: " << sock << std::endl; // struct sockaddr_in 作成 struct sockaddr_in sa = {0}; sa.sin_family = AF_INET; // 接続ポート3000 sa.sin_port = htons(3000); // 接続先は、任意とする。 sa.sin_addr.s_addr = htonl(INADDR_ANY); // バインド if(bind(sock, (struct sockaddr*) &sa, sizeof(struct sockaddr_in)) == -1) { perror("bind"); close(sock); return 1; } std::cout << "bind: " << sock << std::endl; // リッスン if(listen(sock, 1) == -1) { perror("listen"); close(sock); return 1; } std::cout << "listen: " << sock << std::endl; // クライアントの接続を待つ int fd = accept(sock, NULL, NULL); close(sock); if(fd == -1) { perror("accept"); return 1; } std::cout << "accept: " << fd << std::endl; std::string line; bool term = false; while(!term) { // 受信 char buffer[4096]; int recv_size = read(fd, buffer, sizeof(buffer) - 1); if(recv_size == -1) { perror("read"); close(fd); return 1; } // 内容を解析して表示 for(int i = 0; i < recv_size; ++i) { char ch = buffer[i]; if(ch == '\r') continue; if(ch == '\n') { std::cout << line << std::endl; if(line == "end") term = true; line.clear(); } else { line += ch; } } } // 接続のクローズ if(close(fd) == -1) { perror("close"); return 1; } } <|endoftext|>
<commit_before>/* Original code from tekkies/CVdrone (get actual address from github) Modified by Elliot Greenlee, Caleb Mennen, Jacob Pollack COSC 402 Senior Design Min Kao Drone Tour See readme at (get actual address from github) */ #include "ardrone/ardrone.h" #include "control.h" #include "structures.h" #include <iostream> #include <vector> #include <string> using namespace std; int main(int argc, char *argv[]) { Control *control; int wait = 33; try { //Initialize main control variables and flight modes control = new Control(); } catch (const char *msg) { cout << msg << endl; return -1; } // Setting up for constant time double time_counter = 0; clock_t this_time = clock(); clock_t last_time = this_time; // Main loop while (1) { //Time stuff this_time = clock(); time_counter += (double) (this_time - last_time); last_time = this_time; if (time_counter < (double) (1 * CLOCKS_PER_SEC)) { //AKA not enough time has passed continue; } time_counter -= (double) (1 * CLOCKS_PER_SEC); //Detect user key input and end loop if ESC is pressed if (!control->getKey(wait)) break; control->detectFlyingMode(); //b, n, m to change mode control->changeSpeed(); //0-9 to change speed control->detectTakeoff(); //spacebar to take off //Get the image from the camera control->getImage(); //Run drone control control->fly(); //Display image overlay values control->overlayControl(); //Send move command to the drone control->move(); } //Close flying modes and drone connection control->close(); return 0; } <commit_msg>restrict main to execute only 25 times a second<commit_after>/* Original code from tekkies/CVdrone (get actual address from github) Modified by Elliot Greenlee, Caleb Mennen, Jacob Pollack COSC 402 Senior Design Min Kao Drone Tour See readme at (get actual address from github) */ #include "ardrone/ardrone.h" #include "control.h" #include "structures.h" #include <iostream> #include <vector> #include <string> using namespace std; int main(int argc, char *argv[]) { Control *control; int wait = 33; try { //Initialize main control variables and flight modes control = new Control(); } catch (const char *msg) { cout << msg << endl; return -1; } // Setting up for constant time double time_counter = 0; clock_t this_time = clock(); clock_t last_time = this_time; long long executions = 0; // Main loop while (1) { //Time stuff this_time = clock(); time_counter += (double) (this_time - last_time); last_time = this_time; executions++; double time_delay = 1.0 / 25; if (time_counter < (time_delay * CLOCKS_PER_SEC)) { //AKA not enough time has passed continue; } time_counter -= time_delay * CLOCKS_PER_SEC; printf("I hit %lli times\n", executions); executions = 0; // exit(0); //Detect user key input and end loop if ESC is pressed if (!control->getKey(wait)) break; control->detectFlyingMode(); //b, n, m to change mode control->changeSpeed(); //0-9 to change speed control->detectTakeoff(); //spacebar to take off //Get the image from the camera control->getImage(); //Run drone control control->fly(); //Display image overlay values control->overlayControl(); //Send move command to the drone control->move(); } //Close flying modes and drone connection control->close(); return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <cstdlib> #include <vector> #include <string> #include <queue> #include <sys/stat.h> //getlogin() and gethostname(). #include <unistd.h> //perror. #include <stdio.h> //fork,wait and execvp. #include <sys/types.h> #include <sys/wait.h> //boost! #include "boost/algorithm/string.hpp" #include "boost/tokenizer.hpp" #include "boost/foreach.hpp" //that one class. #include "Command.h" using namespace std; using namespace boost; //execute command. void execute(const vector<string> & s); //replaces char in string. void replace_char(string &s, char o, char r); //takes a string and returns vector of parsed string. void parseInput(string s, vector<string> &v); //display vector. template<typename unit> void display_vector(vector<unit> v); //helper function that finds amount of character. int find_char_amount(const string s,char c); //removes comment from input. void remove_comment(string &s); //removes char in string. string remove_char(const string &s, char c); //checks if string passed in contains a flag bool isFlag(string f); //creates command types from vector of strings. Command create_commands(const vector<string> &v); int main() { //grab the login. char* login = getlogin(); //start a flag. bool login_check = true; if((!login) != 0) { //check flag. login_check = false; //output error. perror("Error: could not retrieve login name"); } //hold c-string for host name. char host[150]; //start another flag. bool host_check = true; //gets hostname while checking if it actually grabbed it. if(gethostname(host,sizeof(host)) != 0) { //check flag. host_check = false; //output error. perror("Error: could not rerieve host name."); } //warn user of upcoming trouble. if(login_check == false || host_check == false) cout << "Unable to display login and/or host information." << endl; //string to hold user input. string input; //vector to hold parssed string. vector<string> parseIn; //hold all the Commands. vector<Command> comVector; while(true) { //output login@hostname. if(login_check && host_check) cout << login << '@' << host << ' '; //bash money. cout << "$ "; //placeholder to tell its the program. cout << " (program) "; //geting input as a string. getline(cin,input); //remove extra white space. trim(input); //remove comments. remove_comment(input); //trim again just in case. trim(input); //testing parse. //cout << "Testing parse" << endl; //parse parseInput(input,parseIn); //display_vector(parseIn); //temp variable. Command xcom; //make commands and push that into command vector. for(unsigned int i = 0; i < parseIn.size(); ++i) { //string to compare. string m = parseIn.at(i); if(m == ";" || m == "&" || m == "|") { if(m == ";") { //ends with a semi colon. xcom.set_op(1); } else if(m == "&") { if(i+1 < parseIn.size() && parseIn.at(i+1) == "&") xcom.set_op(2); ++i; } else if(m == "|") { if(i+1 < parseIn.size() && parseIn.at(i+1) == "|") xcom.set_op(3); ++i; } //add it. comVector.push_back(xcom); xcom.clear(); } else xcom.push_back(parseIn.at(i)); } //push into command vector if the command has something in it. if(xcom.empty() == false) comVector.push_back(xcom); for(unsigned int i = 0; i < comVector.size(); ++i) { comVector.at(i).display(); cout << endl; } //execute command. execute(parseIn); //clear vectors. parseIn.clear(); comVector.clear(); //just in case. cin.clear(); input.clear(); } cout << "End of program" << endl; return 0; } void execute(const vector<string> &s) { //check to see if user wants to quit and its the only command. if(s.size() == 1) for(unsigned int i = 0; i < s.size(); ++i) if(s.at(i) == "exit") exit(0); //c-string to hold command. char* args[128]; int count = 0; //cout << endl; //place, remove comments and convert commands. for(unsigned int i = 0; i < s.size(); ++i) { // string temp = remove_char(s.at(i),'\"'); //cout << "(char*)temp.c_str(): " << (char*)temp.c_str() << endl; //cout << "s.at(i): " << s.at(i) << endl; args[i] = (char*)s.at(i).c_str(); //args[i] = (char*)temp.c_str(); count++; //cout << "temp after: " << temp << endl; //cout << "args at " << i << ": " << args[i] << endl << endl; } /* cout << "array before: " << endl; for(int i = 0; i < count; ++i) cout << args[i] << endl; cout << endl; */ args[s.size()] = '\0'; /* cout << "array after: " << endl; for(int i = 0; i < count; ++i) cout << args[i] << endl; cout << endl; */ //creates fork process. pid_t pid = fork(); if(pid == -1) { //fork didn't work. perror("fork"); } if(pid ==0) { if(execvp(args[0], args) == -1) { //execute didn't work. perror("execvp"); //break out of shadow realm. exit(1); } } if(pid > 0) { //wait for child to die. if(wait(0) == -1) { //didnt wait. perror("wait"); } } return; } void parseInput(string s, vector<string> &v) { //replace spaces. replace_char(s,' ','*'); //create boost magic function. char_separator<char> sep(" ;||&&(){}", ";||&&()[]",keep_empty_tokens); //create boost magic holder thingy. tokenizer< char_separator<char> > cm(s,sep); //for each loop to grab each peice and push it into a vector. for(tokenizer< char_separator<char> >::iterator it = cm.begin(); it != cm.end(); ++it) if(*it != "") { //fix string. string temp_string = *it; replace_char(temp_string,'*',' '); v.push_back(temp_string); } //return. return; } void replace_char(string &s, char o, char r) { //different use for the function. if(o == '\"') { //nothing to replace. if(s.find(o) == string::npos) return; //replace. for(unsigned int i = 0; i < s.size(); ++i) if(s.at(i) == o) s.at(i) = r; return; } //no quotes. if(s.find("\"") == string::npos) return; else if(s.find(o) == string::npos) return; //vector to hold quote positions. vector<int> pos; //place positions of char into vector. for(unsigned int i = 0; i < s.size(); ++i) if(s.at(i) == '\"') pos.push_back(i); //count position. unsigned int count = 0; //replace. while(count < pos.size()) { for(int i = pos.at(count); i < pos.at(count+1); ++i) if(s.at(i) == o) s.at(i) = r; count++; count++; } return; } template<typename unit> void display_vector(vector<unit> v) { for(unsigned int i = 0; i < v.size(); ++i) cout << i+1 << ": " << v.at(i) << endl; return; } void remove_comment(string &s) { //just add a " to the end to avoid errors. if(find_char_amount(s,'\"') % 2 != 0) s += '\"'; //delete everything! if(s.find("#") == 0) { s = ""; return; } //return if no comments. if(s.find("#") == string::npos) { return; } //if no comments then deletes everything from hash forward. if(s.find("\"") == string::npos && s.find("#") != string::npos) { s = s.substr(0,s.find("#")); return; } //if comment before quote then delete. if(s.find("\"") > s.find("#")) { s = s.substr(0,s.find("#")); return; } //advanced situations. //get a vector to hold positions of quotes and hash. vector<int> quotePos; vector<int> hashPos; //grab pos. for(unsigned int i = 0; i < s.size(); ++i) { if(s.at(i) == '\"') quotePos.push_back(i); else if(s.at(i) == '#') hashPos.push_back(i); } //no comments or hash for some reason. if(hashPos.size() == 0 || quotePos.size() == 0) return; //just in case. if(quotePos.size() % 2 != 0) quotePos.push_back(0); //overall check; vector<bool> check; //start it up. for(unsigned int i = 0; i < hashPos.size(); ++i) check.push_back(true); //check if hash is in quotes. for(unsigned int i = 0; i < hashPos.size(); ++i ) for(unsigned int j = 0; j < quotePos.size(); j+=2 ) { if(hashPos.at(i) > quotePos.at(j) && hashPos.at(i) < quotePos.at(j+1)) { check.at(i) = true; break; } else check.at(i) = false; } //check bool vector to delete string. for(unsigned int i = 0; i < check.size(); ++i) if(!check.at(i)) { s = s.substr(0,hashPos.at(i)); return; } //if comment at end then kill it. if(hashPos.at(hashPos.size()-1) > quotePos.at(quotePos.size()-1)) s = s.substr(0,hashPos.at(hashPos.size()-1)); return; } int find_char_amount(const string s, char c) { //nothing there. if(s.find(c) == string::npos) return 0; //start counting. int count = 0; for(unsigned int i = 0; i < s.size(); ++i) if(s.at(i) == c) count++; return count; } string remove_char(const string &s, char c) { //if not there then just return. if(s.find(c) == string::npos) return s; //start empty. string t = ""; //add everything thats not what we dont want. for(unsigned int i = 0; i < s.size(); ++i) if(s.at(i) != c) t += s.at(i); return t; } int is_connector(string s) { if(s == ";") return 1; if(s == "&&") return 2; if(s == "||") return 3; return -1; } bool isFlag(string f) { //default list of possible flags string flags = "-e -d -f"; //see if string is one of the flags if (flags.find(f) != string::npos) return true; return false; } /* bool test(vector<string> &commands, vector<char*> &command_v) { //defaults to "-e" string flag = "-e"; struct stat s_thing; //put everything into a queue for ease of use queue<string> coms; for (unsigned int i = 0; i < commands.size(); i++) { coms.push_back(commands.at(i)); } //was a bracket used for the test command? bool bracketUsed = false; //set if a bracket was used if(coms.front() == "["; bracketUsed = true; //remove the first part of the command regardless of whether it's "test" or "[" coms.pop(); if (isTestFlag(coms.front())) { flag = coms.front(); //now we have the flag for the test coms.pop() } //if there's another flag attempt then it's broken if (coms.front().at(0) == "-") { cout << "ERROR: incorrect flags" << endl; //keep deleting from queue till the next command while (!is_connector(coms.front())) { coms.pop(); } return true; } // if the first part of the path is a "/" remove it (that way it can't mess up) if(coms.front().at(0) == "/") commands.front().substr(1, commands.front().size() - 1); //make a new c_string to hold the file path char *filePath = new char[coms.front.size()]; //copy it on over from the command vector strcpy(filePath, coms.front().c_str()); command_v.push_back(filePath); //moving along coms.pop(); //Did we use a bracket instead of "test"? If so get rid of the last bracket if(bracketUsed) { coms.pop(); } //valuse for using the stat thingy int current_stat; //get the status of the command current_stat = stat(command_v.front(), &s_thing); //Did it fail? if(current_stat < 0) { //Yup it did perror("ERROR: Coudn't get the stat"); return true; } //No it didn't so lets try out with "-e" if (flag == "-e") { return false; } //Try it out with "-f" if(flag == "-f") { if(S_ISREG(s_thing.st_mode)) { return false } else { return true } } //Try it out with "-d" if (flag == "-d") { if (S_ISDIR(s_thing.st_mode)) { return false; } else { return true } } //Obviously something went wrong if you got here return true }*/ Command create_commands(const vector<string> &v) { Command temp = Command(v); return temp; } <commit_msg>created a function to create command vector<commit_after>#include <iostream> #include <cstdlib> #include <vector> #include <string> #include <queue> #include <sys/stat.h> //getlogin() and gethostname(). #include <unistd.h> //perror. #include <stdio.h> //fork,wait and execvp. #include <sys/types.h> #include <sys/wait.h> //boost! #include "boost/algorithm/string.hpp" #include "boost/tokenizer.hpp" #include "boost/foreach.hpp" //that one class. #include "Command.h" using namespace std; using namespace boost; //execute command. void execute(const vector<string> & s); //replaces char in string. void replace_char(string &s, char o, char r); //takes a string and returns vector of parsed string. void parseInput(string s, vector<string> &v); //display vector. template<typename unit> void display_vector(vector<unit> v); //helper function that finds amount of character. int find_char_amount(const string s,char c); //removes comment from input. void remove_comment(string &s); //removes char in string. string remove_char(const string &s, char c); //checks if string passed in contains a flag bool isFlag(string f); //pass in vector of string and vector of Commands and populates the second vector. void create_commands(const vector<string> &s, vector<Command> &c); int main() { //grab the login. char* login = getlogin(); //start a flag. bool login_check = true; if((!login) != 0) { //check flag. login_check = false; //output error. perror("Error: could not retrieve login name"); } //hold c-string for host name. char host[150]; //start another flag. bool host_check = true; //gets hostname while checking if it actually grabbed it. if(gethostname(host,sizeof(host)) != 0) { //check flag. host_check = false; //output error. perror("Error: could not rerieve host name."); } //warn user of upcoming trouble. if(login_check == false || host_check == false) cout << "Unable to display login and/or host information." << endl; //string to hold user input. string input; //vector to hold parssed string. vector<string> parseIn; //hold all the Commands. vector<Command> comVector; while(true) { //output login@hostname. if(login_check && host_check) cout << login << '@' << host << ' '; //bash money. cout << "$ "; //placeholder to tell its the program. cout << " (program) "; //geting input as a string. getline(cin,input); //remove extra white space. trim(input); //remove comments. remove_comment(input); //trim again just in case. trim(input); //testing parse. //cout << "Testing parse" << endl; //parse parseInput(input,parseIn); //display_vector(parseIn); //create them commands. create_commands(parseIn,comVector); //display. for(unsigned int i = 0; i < comVector.size(); ++i) { comVector.at(i).display(); cout << endl; } //execute command. execute(parseIn); //clear vectors. parseIn.clear(); comVector.clear(); //just in case. cin.clear(); input.clear(); } cout << "End of program" << endl; return 0; } void execute(const vector<string> &s) { //check to see if user wants to quit and its the only command. if(s.size() == 1) for(unsigned int i = 0; i < s.size(); ++i) if(s.at(i) == "exit") exit(0); //c-string to hold command. char* args[128]; //cout << endl; //place, remove comments and convert commands. for(unsigned int i = 0; i < s.size(); ++i) { //string temp = remove_char(s.at(i),'\"'); //does not remove comments but works. args[i] = (char*)s.at(i).c_str(); //removes comments but does not work. //args[i] = (char*)temp.c_str(); } args[s.size()] = '\0'; //creates fork process. pid_t pid = fork(); if(pid == -1) { //fork didn't work. perror("fork"); } if(pid ==0) { if(execvp(args[0], args) == -1) { //execute didn't work. perror("execvp"); //break out of shadow realm. exit(1); } } if(pid > 0) { //wait for child to die. if(wait(0) == -1) { //didnt wait. perror("wait"); } } return; } void parseInput(string s, vector<string> &v) { //replace spaces. replace_char(s,' ','*'); //create boost magic function. char_separator<char> sep(" ;||&&(){}", ";||&&()[]",keep_empty_tokens); //create boost magic holder thingy. tokenizer< char_separator<char> > cm(s,sep); //for each loop to grab each peice and push it into a vector. for(tokenizer< char_separator<char> >::iterator it = cm.begin(); it != cm.end(); ++it) if(*it != "") { //fix string. string temp_string = *it; replace_char(temp_string,'*',' '); v.push_back(temp_string); } //return. return; } void replace_char(string &s, char o, char r) { //different use for the function. if(o == '\"') { //nothing to replace. if(s.find(o) == string::npos) return; //replace. for(unsigned int i = 0; i < s.size(); ++i) if(s.at(i) == o) s.at(i) = r; return; } //no quotes. if(s.find("\"") == string::npos) return; else if(s.find(o) == string::npos) return; //vector to hold quote positions. vector<int> pos; //place positions of char into vector. for(unsigned int i = 0; i < s.size(); ++i) if(s.at(i) == '\"') pos.push_back(i); //count position. unsigned int count = 0; //replace. while(count < pos.size()) { for(int i = pos.at(count); i < pos.at(count+1); ++i) if(s.at(i) == o) s.at(i) = r; count++; count++; } return; } template<typename unit> void display_vector(vector<unit> v) { for(unsigned int i = 0; i < v.size(); ++i) cout << i+1 << ": " << v.at(i) << endl; return; } void remove_comment(string &s) { //just add a " to the end to avoid errors. if(find_char_amount(s,'\"') % 2 != 0) s += '\"'; //delete everything! if(s.find("#") == 0) { s = ""; return; } //return if no comments. if(s.find("#") == string::npos) { return; } //if no comments then deletes everything from hash forward. if(s.find("\"") == string::npos && s.find("#") != string::npos) { s = s.substr(0,s.find("#")); return; } //if comment before quote then delete. if(s.find("\"") > s.find("#")) { s = s.substr(0,s.find("#")); return; } //advanced situations. //get a vector to hold positions of quotes and hash. vector<int> quotePos; vector<int> hashPos; //grab pos. for(unsigned int i = 0; i < s.size(); ++i) { if(s.at(i) == '\"') quotePos.push_back(i); else if(s.at(i) == '#') hashPos.push_back(i); } //no comments or hash for some reason. if(hashPos.size() == 0 || quotePos.size() == 0) return; //just in case. if(quotePos.size() % 2 != 0) quotePos.push_back(0); //overall check; vector<bool> check; //start it up. for(unsigned int i = 0; i < hashPos.size(); ++i) check.push_back(true); //check if hash is in quotes. for(unsigned int i = 0; i < hashPos.size(); ++i ) for(unsigned int j = 0; j < quotePos.size(); j+=2 ) { if(hashPos.at(i) > quotePos.at(j) && hashPos.at(i) < quotePos.at(j+1)) { check.at(i) = true; break; } else check.at(i) = false; } //check bool vector to delete string. for(unsigned int i = 0; i < check.size(); ++i) if(!check.at(i)) { s = s.substr(0,hashPos.at(i)); return; } //if comment at end then kill it. if(hashPos.at(hashPos.size()-1) > quotePos.at(quotePos.size()-1)) s = s.substr(0,hashPos.at(hashPos.size()-1)); return; } int find_char_amount(const string s, char c) { //nothing there. if(s.find(c) == string::npos) return 0; //start counting. int count = 0; for(unsigned int i = 0; i < s.size(); ++i) if(s.at(i) == c) count++; return count; } string remove_char(const string &s, char c) { //if not there then just return. if(s.find(c) == string::npos) return s; //start empty. string t = ""; //add everything thats not what we dont want. for(unsigned int i = 0; i < s.size(); ++i) if(s.at(i) != c) t += s.at(i); return t; } //uselss. int is_connector(string s) { if(s == ";") return 1; if(s == "&&") return 2; if(s == "||") return 3; return -1; } bool isFlag(string f) { //default list of possible flags string flags = "-e -d -f"; //see if string is one of the flags if (flags.find(f) != string::npos) return true; return false; } /* bool test(vector<string> &commands, vector<char*> &command_v) { //defaults to "-e" string flag = "-e"; struct stat s_thing; //put everything into a queue for ease of use queue<string> coms; for (unsigned int i = 0; i < commands.size(); i++) { coms.push_back(commands.at(i)); } //was a bracket used for the test command? bool bracketUsed = false; //set if a bracket was used if(coms.front() == "["; bracketUsed = true; //remove the first part of the command regardless of whether it's "test" or "[" coms.pop(); if (isTestFlag(coms.front())) { flag = coms.front(); //now we have the flag for the test coms.pop() } //if there's another flag attempt then it's broken if (coms.front().at(0) == "-") { cout << "ERROR: incorrect flags" << endl; //keep deleting from queue till the next command while (!is_connector(coms.front())) { coms.pop(); } return true; } // if the first part of the path is a "/" remove it (that way it can't mess up) if(coms.front().at(0) == "/") commands.front().substr(1, commands.front().size() - 1); //make a new c_string to hold the file path char *filePath = new char[coms.front.size()]; //copy it on over from the command vector strcpy(filePath, coms.front().c_str()); command_v.push_back(filePath); //moving along coms.pop(); //Did we use a bracket instead of "test"? If so get rid of the last bracket if(bracketUsed) { coms.pop(); } //valuse for using the stat thingy int current_stat; //get the status of the command current_stat = stat(command_v.front(), &s_thing); //Did it fail? if(current_stat < 0) { //Yup it did perror("ERROR: Coudn't get the stat"); return true; } //No it didn't so lets try out with "-e" if (flag == "-e") { return false; } //Try it out with "-f" if(flag == "-f") { if(S_ISREG(s_thing.st_mode)) { return false } else { return true } } //Try it out with "-d" if (flag == "-d") { if (S_ISDIR(s_thing.st_mode)) { return false; } else { return true } } //Obviously something went wrong if you got here return true }*/ void create_commands(const vector<string> &s, vector<Command> &c) { //temp variable. Command xcom; //make commands and push that into command vector. for(unsigned int i = 0; i < s.size(); ++i) { //string to compare. string m = s.at(i); if(m == ";" || m == "&" || m == "|") { if(m == ";") { //ends with a semi colon. xcom.set_op(1); } else if(m == "&") { if(i+1 < s.size() && s.at(i+1) == "&") xcom.set_op(2); ++i; } else if(m == "|") { if(i+1 < s.size() && s.at(i+1) == "|") xcom.set_op(3); ++i; } //add it. c.push_back(xcom); xcom.clear(); } else xcom.push_back(s.at(i)); } //push into command vector if the command has something in it. if(xcom.empty() == false) c.push_back(xcom); return; } <|endoftext|>
<commit_before>#include <iostream> #include <stdio.h> #include <string> #include <string.h> #include <unistd.h> #include "cmdAnd.h" #include "cmdOr.h" #include "cmdBase.h" #include "cmdSemi.h" #include "cmdExecutable.h" #include <vector> #include <stack> #include <list> #include <iterator> using namespace std; void printPrompt(); char* getInput(); cmdBase* parse(char* input); vector<char*> infixToPostfix(vector<char*> vInfix); int main() { while(true) { printPrompt(); char* userInput = getInput(); cmdBase* head = parse(userInput); //head->execute( ); //delete head; } } // prints the prompt for the user // displays the user name and host name void printPrompt() { char *User; char host[30]; User = getlogin( ); gethostname( host, 30 ); cout << User << "@" << host << "$ "; } //takes in user input and returns the char* char* getInput() { //takes in user input as string w/ getline string temp; getline(cin, temp); //if user entered nothing //print the prompt and wait for user input //checks for syntax error when the connectors //are the first inputs while ( temp.empty( ) || temp[0] == '&' || temp[0] == '|' || temp[0] == ';') { if (temp[0] == '&' || temp[0] == '|' || temp[0] == ';') { cout << "syntax error near unexpected token '" << temp[0]; if ( temp[0] != ';' ) cout << temp[1] << "'" << endl; else cout << "'" << endl; } printPrompt(); getline( cin, temp ); } if ( temp.find("&& ||") != std::string::npos ) { cout << "syntax error near unexpected token ||" << endl; printPrompt( ); getline( cin, temp ); } else if ( temp.find( "|| &&" ) != std::string::npos ) { cout << "syntax error near unexpected token &&" << endl; printPrompt( ); getline( cin, temp ); } //creates char array and sets it equal to string char* input = new char[temp.size()]; for (int i = 0, n = temp.size(); i < n; i++) { input[i] = temp.at(i); } input[temp.size()] = '\0'; //adds NULL to end of char array return input; } //creates tree of command connectors by parsing the entered line cmdBase* parse(char* input) { list<char*> vInfix; char* cmdPtr; cmdPtr = strtok(input, ";"); while (cmdPtr != NULL) { vInfix.push_back(cmdPtr); char* temp = new char[1]; *temp = ';'; vInfix.push_back(temp); cmdPtr = strtok(NULL, ";"); } if (*vInfix.back() == ';') { vInfix.pop_back(); } for (list<char*>::iterator it = vInfix.begin(); it != vInfix.end(); it++) { cmdPtr = strtok(*it, "&"); char* cmdPtr2 = strtok(NULL, "&"); while (cmdPtr2 != NULL) { *it = cmdPtr; char* temp = new char[2]; temp[0] = '&'; temp[1] = '&'; it++; if(it == vInfix.end()) { it--; vInfix.push_back(temp); vInfix.push_back(cmdPtr2); it++; } else { vInfix.insert(it++, temp); vInfix.insert(it, cmdPtr2); } cmdPtr = strtok(cmdPtr2, "&"); cmdPtr2 = strtok(NULL, "&"); } } for (list<char*>::iterator it = vInfix.begin(); it != vInfix.end(); it++) { cmdPtr = strtok(*it, "|"); char* cmdPtr2 = strtok(NULL, "|"); while (cmdPtr2 != NULL) { *it = cmdPtr; char* temp = new char[2]; temp[0] = '|'; temp[1] = '|'; vInfix.insert(it++, temp); vInfix.insert(it++, cmdPtr2); cmdPtr = strtok(cmdPtr2, "&"); cmdPtr2 = strtok(NULL, "&"); } } for (list<char*>::iterator it = vInfix.begin(); it != vInfix.end(); it++) { cout << *it << endl; } /*fills v with every word wordPointer = strtok(input, " "); while(wordPointer != '\0') { vInfix.push_back(wordPointer); wordPointer = strtok(NULL, " "); } if (vInfix.back() == ";") { vInfix.pop_back(); }*/ //vector<char*> vPostfix = infixToPostfix(vInfix); cmdExecutable* t = new cmdExecutable(NULL); return t; } vector<char*> infixToPostfix(vector<char*> vInfix) { stack<char*> cntrStack; vector<char*> vPostfix; char* wrdPtr; for (int i = 0, n = vInfix.size(); i < n; i++) { //TODO: FINISH PARSE wrdPtr = vInfix.at(i); if (wrdPtr == "&&" || wrdPtr == "||" || wrdPtr == ";") { if (wrdPtr == "(") { } else if (wrdPtr == ";") { while (!cntrStack.empty()) { vPostfix.push_back(cntrStack.top()); cntrStack.pop(); } } else { while (!cntrStack.empty()) { vPostfix.push_back(cntrStack.top()); cntrStack.pop(); } } } } } <commit_msg>Remade parse, added parentheses function<commit_after>#include <iostream> #include <stdio.h> #include <string> #include <string.h> #include <unistd.h> #include "cmdAnd.h" #include "cmdOr.h" #include "cmdBase.h" #include "cmdSemi.h" #include "cmdExecutable.h" #include <vector> #include <stack> #include <list> #include <iterator> using namespace std; void printPrompt(); char* getInput(); cmdBase* parse(char* input); vector<char*> infixToPostfix(list<char*> vInfix); int priority(char*); int main() { while(true) { printPrompt(); char* userInput = getInput(); cmdBase* head = parse(userInput); head->execute( ); //delete head; } } // prints the prompt for the user // displays the user name and host name void printPrompt() { char *User; char host[30]; User = getlogin( ); gethostname( host, 30 ); cout << User << "@" << host << "$ "; } //takes in user input and returns the char* char* getInput() { //takes in user input as string w/ getline string temp; getline(cin, temp); //if user entered nothing //print the prompt and wait for user input //checks for syntax error when the connectors //are the first inputs while ( temp.empty( ) || temp[0] == '&' || temp[0] == '|' || temp[0] == ';') { if (temp[0] == '&' || temp[0] == '|' || temp[0] == ';') { cout << "syntax error near unexpected token '" << temp[0]; if ( temp[0] != ';' ) cout << temp[1] << "'" << endl; else cout << "'" << endl; } printPrompt(); getline( cin, temp ); } if ( temp.find("&& ||") != std::string::npos ) { cout << "syntax error near unexpected token ||" << endl; printPrompt( ); getline( cin, temp ); } else if ( temp.find( "|| &&" ) != std::string::npos ) { cout << "syntax error near unexpected token &&" << endl; printPrompt( ); getline( cin, temp ); } //creates char array and sets it equal to string char* input = new char[temp.size()]; for (int i = 0, n = temp.size(); i < n; i++) { input[i] = temp.at(i); } input[temp.size()] = '\0'; //adds NULL to end of char array return input; } //creates tree of command connectors by parsing the entered line cmdBase* parse(char* input) { list<char*> vInfix; char* cmdPtr; cmdPtr = strtok(input, ";"); while (cmdPtr != NULL) { vInfix.push_back(cmdPtr); char* temp = new char[2]; temp[0] = ';'; temp[1] = '\0'; vInfix.push_back(temp); cmdPtr = strtok(NULL, ";"); } if (*vInfix.back() == ';') { vInfix.pop_back(); } for (list<char*>::iterator it = vInfix.begin(); it != vInfix.end(); it++) { cmdPtr = strtok(*it, "&"); char* cmdPtr2 = strtok(NULL, ""); if (cmdPtr2 != NULL) { cmdPtr2 += 1; *it = cmdPtr; char* temp = new char[3]; temp[0] = '&'; temp[1] = '&'; temp[2] = '\0'; it++; if(it == vInfix.end()) { it--; vInfix.push_back(temp); vInfix.push_back(cmdPtr2); it++; } else { vInfix.insert(it, temp); vInfix.insert(it, cmdPtr2); } } } for (list<char*>::iterator it = vInfix.begin(); it != vInfix.end(); it++) { cmdPtr = strtok(*it, "|"); char* cmdPtr2 = strtok(NULL, ""); if (cmdPtr2 != NULL) { cmdPtr2 += 1; *it = cmdPtr; char* temp = new char[3]; temp[0] = '|'; temp[1] = '|'; temp[2] = '\0'; it++; if(it == vInfix.end()) { it--; vInfix.push_back(temp); vInfix.push_back(cmdPtr2); it++; } else { vInfix.insert(it, temp); vInfix.insert(it, cmdPtr2); } } } for (list<char*>::iterator it = vInfix.begin(); it != vInfix.end(); it++) { char* c = *it; int i = 0; while (c[i] == ' ') { i++; } if (c[i] == '(') { char* temp = new char[2]; temp[0] = '('; temp[1] = '\0'; vInfix.insert(it, temp); c[i] = '\0'; c += i + 1; *it = c; it--; } } for (list<char*>::iterator it = vInfix.begin(); it != vInfix.end(); it++) { char* c = strpbrk(*it, ")"); if (c != NULL) { c[0] = '\0'; int i = 1; while (c[i] == ' ') { i++; } if (c[i] != '\0') { c += i; it++; if (it == vInfix.end()) { it--; vInfix.push_back(c); it++; } else { vInfix.insert(it, c); } it--; } char* temp = new char[2]; temp[0] = ')'; temp[1] = '\0'; it++; if (it == vInfix.end()) { it--; vInfix.push_back(temp); it++; } else { vInfix.insert(it, temp); } } } vector<char*> vPostfix = infixToPostfix(vInfix); stack<cmdBase*> cmdStack; for (int i = 0, n = vPostfix.size(); i < n; i++) { cmdBase* temp; if (strcmp(vPostfix.at(i), "&&") == 0) { cmdBase* right = cmdStack.top(); cmdStack.pop(); cmdBase* left = cmdStack.top(); cmdStack.pop(); temp = new cmdAnd(left, right); } else if (strcmp(vPostfix.at(i), "||") == 0) { cmdBase* right = cmdStack.top(); cmdStack.pop(); cmdBase* left = cmdStack.top(); cmdStack.pop(); temp = new cmdOr(left, right); } else if (strcmp(vPostfix.at(i), ";") == 0) { cmdBase* right = cmdStack.top(); cmdStack.pop(); cmdBase* left = cmdStack.top(); cmdStack.pop(); temp = new cmdSemi(left, right); } else { temp = new cmdExecutable(vPostfix.at(i)); } cmdStack.push(temp); } return cmdStack.top(); } vector<char*> infixToPostfix(list<char*> vInfix) { stack<char*> cntrStack; vector<char*> vPostfix; char* wrdPtr; for (list<char*>::iterator it = vInfix.begin(); it != vInfix.end(); it++) { wrdPtr = *it; if (strcmp(wrdPtr, "&&") == 0 || strcmp(wrdPtr, "||") == 0 || strcmp(wrdPtr, ";") == 0 || strcmp(wrdPtr, "(") == 0 || strcmp(wrdPtr, ")") == 0) { if (strcmp(wrdPtr, "(") == 0) { cntrStack.push(wrdPtr); } else if (strcmp(wrdPtr, ")") == 0) { while (strcmp(cntrStack.top(), "(") != 0) { vPostfix.push_back(cntrStack.top()); cntrStack.pop(); } cntrStack.pop(); } else { while (!cntrStack.empty() && priority(wrdPtr) <= priority(cntrStack.top())) { if (strcmp(cntrStack.top(), "(") == 0) { break; } vPostfix.push_back(cntrStack.top()); cntrStack.pop(); } cntrStack.push(wrdPtr); } } else { vPostfix.push_back(wrdPtr); } } while (!cntrStack.empty()) { vPostfix.push_back(cntrStack.top()); cntrStack.pop(); } return vPostfix; } int priority(char* c) { if (strcmp(c, "(") == 0) { return 3; } else if (strcmp(c, ";") == 0) { return 1; } return 2; } <|endoftext|>
<commit_before>#include <Game.hpp> #include <Menu.hpp> #include <string> int main(int argc, char* argv[]); int main(int argc, char* argv[]){ Menu menu; if (argc <= 1) { menu.mainMenu(); } else{ if (std::string(argv[1]) == "--version") { std::cout << "PapraGame v0.4 -- Crepitum Anatum" << std::endl << "Copyright c 2016 TiWinDeTea (https://github.com/TiWinDeTea)" << std::endl << std::endl << "Covered Software is provided under this License on an \"as is\"" << std::endl << "basis, without warranty of any kind, either expressed, implied, or" << std::endl << "statutory, including, without limitation, warranties that the" << std::endl << "Covered Software is free of defects, merchantable, fit for a" << std::endl << "particular purpose or non-infringing. The entire risk as to the" << std::endl << "quality and performance of the Covered Software is with You." << std::endl << "Should any Covered Software prove defective in any respect, You" << std::endl << "(not any Contributor) assume the cost of any necessary servicing," << std::endl << "repair, or correction. This disclaimer of warranty constitutes an" << std::endl << "essential part of this License. No use of any Covered Software is" << std::endl << "authorized under this License except under this disclaimer." << std::endl << std::endl << "Game currently under development" << std::endl; } else{ menu.setBiome(std::string(argv[1])); menu.mainMenu(); } } return 0; } <commit_msg>Updating main<commit_after>#include <Game.hpp> #include <Menu.hpp> #include <string> int main(int argc, char* argv[]); int main(int argc, char* argv[]){ if (argc <= 1) { Menu menu; menu.mainMenu(); } else{ if (std::string(argv[1]) == "--version") { std::cout << "PapraGame v1.0 -- Temerarium Anatum " << std::endl << "Copyright c 2016 TiWinDeTea (https://github.com/TiWinDeTea). Game under the " << "Mozilla Public License v2.0" << std::endl << std::endl << "License extract : " << std::endl << "Covered Software is provided under this License on an \"as is\"" << std::endl << "basis, without warranty of any kind, either expressed, implied, or" << std::endl << "statutory, including, without limitation, warranties that the" << std::endl << "Covered Software is free of defects, merchantable, fit for a" << std::endl << "particular purpose or non-infringing. The entire risk as to the" << std::endl << "quality and performance of the Covered Software is with You." << std::endl << "Should any Covered Software prove defective in any respect, You" << std::endl << "(not any Contributor) assume the cost of any necessary servicing," << std::endl << "repair, or correction. This disclaimer of warranty constitutes an" << std::endl << "essential part of this License. No use of any Covered Software is" << std::endl << "authorized under this License except under this disclaimer." << std::endl << std::endl; } else{ Menu menu; menu.setBiome(std::string(argv[1])); menu.mainMenu(); } } return 0; } <|endoftext|>
<commit_before>/* * This file is part of SKATRAK Playground. * * SKATRAK Playground 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 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> or * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth * Floor, Boston, MA 02110-1301 USA * * Sergio M. Afonso Fumero <[email protected]> */ #include "../include/SKATRAK_PLAYGROUND.hpp" #include "../include/shared_attributes.hpp" /* Definiciones de las rutas por defecto de los recursos */ const char* MUS_PATH = "../../resources/sound/"; const char* SFX_PATH = "../../resources/sound/"; const char* FONT_PATH = "../../resources/fonts/"; const char* IMG_PATH = "../../resources/images/"; const char* INI_PATH = "../../resources/settings/"; /* Prototipos de los mens de los distintos minijuegos */ returnVal mainMenu(); //returnVal main3enRaya(); //returnVal mainConecta4(); //returnVal mainPong(); //[...] system_t* sistema = NULL; // La variable sistema se comparte entre todos los minijuegos y permanece igual para todos ellos. music_t* musica = NULL; // La variable musica se comparte por todos los minijuegos y cada uno puede tener su propia lista de reproduccin. int main(int argc, char* argv[]){ // Creamos la variable sistema (Iniciamos SDL) sistema = new system_t(1024, 768, 32); sistema->setIcon("icono_prueba.png"); // Cargamos 3 pistas de msica para que reproduzcan en el fondo musica = new music_t(3); musica->setVol(128); musica->setTrack(0, "track01.ogg"); musica->setTrack(1, "track02.ogg"); musica->setTrack(2, "track03.ogg"); // Imgenes para mostrar en el men inicio SDL_Surface* screen = sistema->scr(); if(screen == NULL){ fprintf(stderr, "La pantalla no se ha iniciado. Saliendo del programa...\n"); return 1; } image_t fondo("Fondo_inicio_prueba.png"); font_t nombreJuego("font01.ttf"); nombreJuego.setSize(72); nombreJuego.setText("SKATRAK Playground"); font_t empezar("font01.ttf"); empezar.setSize(32); empezar.setText("Pulse una tecla para comenzar"); timekeeper_t temporizador; // Variables para controlar el game loop SDL_Event event; bool salir = false; // Comenzamos a reproducir la msica musica->play(); int alpha = 0; while((int)alpha < SDL_ALPHA_OPAQUE){ temporizador.refresh(); nombreJuego.setAlpha((int)alpha); fondo.blit(0, 0, screen); nombreJuego.blit((int)(screen->w / 2) - (int)(nombreJuego.width() / 2), (int)(screen->h / 2) - (int)(nombreJuego.height() / 2), screen); sistema->update(); temporizador.waitFramerate(30); alpha += 3; SDL_PollEvent(NULL); } nombreJuego.setAlpha(SDL_ALPHA_OPAQUE); bool alphaAdd = false; while(!salir){ // Reiniciamos el temporizador en cada ciclo temporizador.refresh(); // Gestionamos los eventos while(SDL_PollEvent(&event)){ switch(event.type){ case SDL_KEYDOWN: if(mainMenu() == ERROR) fprintf(stderr, "Se ha salido del programa con un error.\n"); salir = true; break; case SDL_QUIT: salir = true; } } // Para dar una sensacin de texto parpadeante if(alphaAdd) alpha += 5; else alpha -= 5; if(alpha <= SDL_ALPHA_TRANSPARENT) alphaAdd = true; else if(alpha >= SDL_ALPHA_OPAQUE) alphaAdd = false; empezar.setAlpha((int)alpha); // Imprimimos por pantalla todo lo que haga falta e intercambiamos los buffers de vdeo fondo.blit(0, 0, screen); nombreJuego.blit((int)(screen->w / 2) - (int)(nombreJuego.width() / 2), (int)(screen->h / 2) - (int)(nombreJuego.height() / 2), screen); empezar.blit((int)(screen->w / 2) - (int)(empezar.width() / 2), (int)(3 * screen->h / 4) - (int)(empezar.height() / 2), screen); sistema->update(); // Fijamos los FPS a 30 temporizador.waitFramerate(30); } // Paramos la msica antes de salir y liberamos recursos musica->halt(); printf("El programa ha estado abierto %d segundos y ha imprimido %d fotogramas.\n", (int)temporizador.elapsed()/1000, temporizador.renderedFrames()); if(musica != NULL) delete musica; if(sistema != NULL) delete sistema; return 0; } <commit_msg>Para que no se genere "blended" durante un segundo y se note la diferencia<commit_after>/* * This file is part of SKATRAK Playground. * * SKATRAK Playground 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 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> or * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth * Floor, Boston, MA 02110-1301 USA * * Sergio M. Afonso Fumero <[email protected]> */ #include "../include/SKATRAK_PLAYGROUND.hpp" #include "../include/shared_attributes.hpp" /* Definiciones de las rutas por defecto de los recursos */ const char* MUS_PATH = "../../resources/sound/"; const char* SFX_PATH = "../../resources/sound/"; const char* FONT_PATH = "../../resources/fonts/"; const char* IMG_PATH = "../../resources/images/"; const char* INI_PATH = "../../resources/settings/"; /* Prototipos de los mens de los distintos minijuegos */ returnVal mainMenu(); //returnVal main3enRaya(); //returnVal mainConecta4(); //returnVal mainPong(); //[...] system_t* sistema = NULL; // La variable sistema se comparte entre todos los minijuegos y permanece igual para todos ellos. music_t* musica = NULL; // La variable musica se comparte por todos los minijuegos y cada uno puede tener su propia lista de reproduccin. int main(int argc, char* argv[]){ // Creamos la variable sistema (Iniciamos SDL) sistema = new system_t(1024, 768, 32); sistema->setIcon("icono_prueba.png"); // Cargamos 3 pistas de msica para que reproduzcan en el fondo musica = new music_t(3); musica->setVol(128); musica->setTrack(0, "track01.ogg"); musica->setTrack(1, "track02.ogg"); musica->setTrack(2, "track03.ogg"); // Imgenes para mostrar en el men inicio SDL_Surface* screen = sistema->scr(); if(screen == NULL){ fprintf(stderr, "La pantalla no se ha iniciado. Saliendo del programa...\n"); return 1; } image_t fondo("Fondo_inicio_prueba.png"); font_t nombreJuego("font01.ttf"); nombreJuego.setSize(72); nombreJuego.setText("SKATRAK Playground"); font_t empezar("font01.ttf"); empezar.setSize(32); empezar.setText("Pulse una tecla para comenzar"); timekeeper_t temporizador; // Variables para controlar el game loop SDL_Event event; bool salir = false; // Comenzamos a reproducir la msica musica->play(); int alpha = 0; while((int)alpha < SDL_ALPHA_OPAQUE){ temporizador.refresh(); nombreJuego.setAlpha((int)alpha); fondo.blit(0, 0, screen); nombreJuego.blit((int)(screen->w / 2) - (int)(nombreJuego.width() / 2), (int)(screen->h / 2) - (int)(nombreJuego.height() / 2), screen); sistema->update(); temporizador.waitFramerate(30); alpha += 3; SDL_PollEvent(NULL); } nombreJuego.setAlpha(SDL_ALPHA_OPAQUE); bool alphaAdd = false; while(!salir){ // Reiniciamos el temporizador en cada ciclo temporizador.refresh(); // Gestionamos los eventos while(SDL_PollEvent(&event)){ switch(event.type){ case SDL_KEYDOWN: if(mainMenu() == ERROR) fprintf(stderr, "Se ha salido del programa con un error.\n"); salir = true; break; case SDL_QUIT: salir = true; } } // Para dar una sensacin de texto parpadeante if(alphaAdd) alpha += 5; else alpha -= 5; if(alpha <= SDL_ALPHA_TRANSPARENT) alphaAdd = true; else if(alpha >= SDL_ALPHA_OPAQUE - 5) alphaAdd = false; empezar.setAlpha((int)alpha); // Imprimimos por pantalla todo lo que haga falta e intercambiamos los buffers de vdeo fondo.blit(0, 0, screen); nombreJuego.blit((int)(screen->w / 2) - (int)(nombreJuego.width() / 2), (int)(screen->h / 2) - (int)(nombreJuego.height() / 2), screen); empezar.blit((int)(screen->w / 2) - (int)(empezar.width() / 2), (int)(3 * screen->h / 4) - (int)(empezar.height() / 2), screen); sistema->update(); // Fijamos los FPS a 30 temporizador.waitFramerate(30); } // Paramos la msica antes de salir y liberamos recursos musica->halt(); printf("El programa ha estado abierto %d segundos y ha imprimido %d fotogramas.\n", (int)temporizador.elapsed()/1000, temporizador.renderedFrames()); if(musica != NULL) delete musica; if(sistema != NULL) delete sistema; return 0; } <|endoftext|>
<commit_before>#include <QtQuick> #include <sailfishapp.h> #include <QScopedPointer> #include <QQuickView> #include <QQmlEngine> #include <QGuiApplication> #include "factor.h" void loadTranslations() { QString langCode = QLocale::system().name().mid(0, 2); const QString Prefix("sailfactor_"); if (QFile::exists(QString(":/lang/") + Prefix + langCode + ".qm")) { QTranslator *translator = new QTranslator(QCoreApplication::instance()); translator->load(Prefix + langCode, ":/lang"); QCoreApplication::installTranslator(translator); } } int main(int argc, char *argv[]) { QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv)); QScopedPointer<QQuickView> view(SailfishApp::createView()); loadTranslations(); Factorizer fact; #ifdef QT_QML_DEBUG runUnitTests(); #endif view->engine()->rootContext()->setContextProperty("fact", &fact); view->setSource(SailfishApp::pathTo("qml/main.qml")); view->setTitle("Sailfactor"); app->setApplicationName("harbour-sailfactor"); app->setApplicationDisplayName("Sailfactor"); view->show(); return app->exec(); } <commit_msg>Make loadTranslations() a static function.<commit_after>#include <QtQuick> #include <sailfishapp.h> #include <QScopedPointer> #include <QQuickView> #include <QQmlEngine> #include <QGuiApplication> #include "factor.h" static void loadTranslations() { QString langCode = QLocale::system().name().mid(0, 2); const QString Prefix("sailfactor_"); if (QFile::exists(QString(":/lang/") + Prefix + langCode + ".qm")) { QTranslator *translator = new QTranslator(QCoreApplication::instance()); translator->load(Prefix + langCode, ":/lang"); QCoreApplication::installTranslator(translator); } } int main(int argc, char *argv[]) { QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv)); QScopedPointer<QQuickView> view(SailfishApp::createView()); loadTranslations(); Factorizer fact; #ifdef QT_QML_DEBUG runUnitTests(); #endif view->engine()->rootContext()->setContextProperty("fact", &fact); view->setSource(SailfishApp::pathTo("qml/main.qml")); view->setTitle("Sailfactor"); app->setApplicationName("harbour-sailfactor"); app->setApplicationDisplayName("Sailfactor"); view->show(); return app->exec(); } <|endoftext|>
<commit_before>#include <iostream> #include <SDL2/SDL.h> #include <mosquitto.h> #include <math.h> // Sensor Patterns const char* SENSOR_STATE_PATT = "recruitment/ciot/state"; const char* SENSOR_VALUE_PATT = "recruitment/ciot/sensor1"; const char* SENSOR_WAKEUP_PATT = "recruitment/ciot/wake"; void message_callback(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message); void log_result(int resultCode); void connect_callback(struct mosquitto *mosq, void *userdata, int result); void draw(SDL_Renderer* renderer, float delta_time); int main(int, char**); void wakeup_sensor(struct mosquitto *mosq); void message_callback(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message) { //Simply print the data to standard out. if(message->payloadlen) { if( strcmp( message->topic, SENSOR_VALUE_PATT) == 0 ) { } else if(strcmp( message->topic, SENSOR_STATE_PATT) == 0 ) { wakeup_sensor( mosq ); } //Data is binary, but we cast it to a string because we're crazy. std::cout << message->topic << ": " << (const char*)message->payload << std::endl; } } void log_result(int resultCode) { switch( resultCode ) { case MOSQ_ERR_SUCCESS: std::cout << "OK" << std::endl; break; case MOSQ_ERR_INVAL: std::cout << "Invalid parameter" << std::endl; break; default: std::cout << "Error:" << resultCode << std::endl; break; } } void connect_callback(struct mosquitto *mosq, void *userdata, int result) { std::cout << "Connected to broker: "; log_result( result ); if(result == MOSQ_ERR_SUCCESS) { //Subscribe to broker information topics on successful connect. int res = mosquitto_subscribe(mosq, NULL, SENSOR_STATE_PATT, 2); std::cout << "Connected to sensor state: "; log_result( res ); res = mosquitto_subscribe(mosq, NULL, SENSOR_VALUE_PATT, 2); std::cout << "Connected to sensor value: "; log_result( res ); } } void wakeup_sensor(struct mosquitto *mosq) { std::cout << "Waking up sensor..."; int payload = 1; int payloadlen = 1; int qos = 2; bool retain = true; int res = mosquitto_publish(mosq, NULL, SENSOR_WAKEUP_PATT, payloadlen, &payload, qos, retain ); log_result( res ); } void publish_callback(struct mosquitto *mosq, void *userdata, int result) { std::cout << "Wakeup sent to sensor: "; log_result( result ); } //Draws a simple bar chart with a blue background in the center of the screen. void draw(SDL_Renderer* renderer, float delta_time) { static float time = 0; time += delta_time; SDL_SetRenderDrawColor(renderer, 0x00, 0x9f, 0xe3, 0xFF ); SDL_Rect rect = {100, 240, 600, 120}; //Background SDL_RenderFillRect(renderer, &rect); //Bars int count = 6; int padding = 2; int start_x = 120; int y = 340; int width = (rect.w - (start_x - rect.x) * 2 - padding * (count - 1))/count; //Draw the bars with a simple sine-wave modulation on height and transparency. for (int i = 0; i < count; ++i) { float offset = ((float)sin(time * 4 + i) + 1.0f)/2.f; int height = offset * 20 + 20; SDL_Rect bar = {start_x, y - height, width, height}; SDL_SetRenderDrawColor(renderer, 0xff, 0xff, 0xff, (unsigned char)(255 * (offset/2 + 0.5f))); SDL_RenderFillRect(renderer, &bar); start_x += padding + width; } } int main(int, char**) { SDL_Window *window = 0; SDL_Renderer *renderer = 0; int code = 0; struct mosquitto* mosq; bool run = true; unsigned int t0 = 0, t1 = 0; mosquitto_lib_init(); if((mosq = mosquitto_new(0, true, 0)) == 0) { std::cout << "Failed to initialize mosquitto." << std::endl; code = 1; goto end; } mosquitto_connect_callback_set(mosq, connect_callback); mosquitto_message_callback_set(mosq, message_callback); mosquitto_publish_callback_set(mosq, publish_callback); //Init SDL if (SDL_Init(SDL_INIT_VIDEO) != 0){ std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; code = 1; goto end; } //Create a window and renderer attached to it. window = SDL_CreateWindow("SDL Skeleton", 100, 100, 800, 600, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL); renderer = SDL_CreateRenderer(window, 0, SDL_RENDERER_PRESENTVSYNC); if(!window || !renderer) { std::cout << "SDL_CreateWindow or SDL_CreateRenderer Error: " << SDL_GetError() << std::endl; code = 1; goto end; } SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND); //Attempt mosquitto connection to local host. mosquitto_connect_async(mosq, "amee.interaktionsbyran.se", 1883, 60); //Start the mosquitto network thread. if(mosquitto_loop_start(mosq) != MOSQ_ERR_SUCCESS) { std::cout << "Failed mosquitto init " << mosq << std::endl; code = 1; goto end; } //Block untill the user closes the window SDL_Event e; while (run) { t1 = SDL_GetTicks(); float delta_time = (float)(t1 - t0)/1000.f; // check if the devices is sleeping at recruitment/ciot/state // wake up the device at recruitment/ciot/wake = 1 // ask for the data at recruitment/ciot/sensor1 while( SDL_PollEvent( &e ) != 0) { if( e.type == SDL_QUIT ) { run = false; break; } } //Clear buffer. SDL_SetRenderDrawColor(renderer, 0xff, 0xff, 0xff, 0xff); SDL_RenderClear(renderer); draw(renderer, delta_time); SDL_RenderPresent(renderer); t0 = t1; } end: SDL_Quit(); //Cleanup mqtt mosquitto_loop_stop(mosq, true); mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return code; } <commit_msg>refactoring, adding subject to the log_result<commit_after>#include <iostream> #include <SDL2/SDL.h> #include <mosquitto.h> #include <math.h> // Sensor Patterns const char* SENSOR_STATE_PATT = "recruitment/ciot/state"; const char* SENSOR_VALUE_PATT = "recruitment/ciot/sensor1"; const char* SENSOR_WAKEUP_PATT = "recruitment/ciot/wake"; void message_callback(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message); void log_result(const char * subject, int resultCode); void connect_callback(struct mosquitto *mosq, void *userdata, int result); void draw(SDL_Renderer* renderer, float delta_time); int main(int, char**); void wakeup_sensor(struct mosquitto *mosq); void message_callback(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message) { //Simply print the data to standard out. if(message->payloadlen) { if( strcmp( message->topic, SENSOR_VALUE_PATT) == 0 ) { } else if(strcmp( message->topic, SENSOR_STATE_PATT) == 0 ) { wakeup_sensor( mosq ); } //Data is binary, but we cast it to a string because we're crazy. std::cout << message->topic << ": " << (const char*)message->payload << std::endl; } } void log_result(const char * subject, int resultCode) { std::cout << subject; switch( resultCode ) { case MOSQ_ERR_SUCCESS: std::cout << "OK" << std::endl; break; case MOSQ_ERR_INVAL: std::cout << "Invalid parameter" << std::endl; break; default: std::cout << "Error:" << resultCode << std::endl; break; } } void connect_callback(struct mosquitto *mosq, void *userdata, int result) { log_result( "Connected to broker: ", result ); if(result == MOSQ_ERR_SUCCESS) { //Subscribe to broker information topics on successful connect. int res = mosquitto_subscribe(mosq, NULL, SENSOR_STATE_PATT, 2); log_result( "Connected to sensor state: ", res ); res = mosquitto_subscribe(mosq, NULL, SENSOR_VALUE_PATT, 2); log_result( "Connected to sensor value: ", res ); } } void wakeup_sensor(struct mosquitto *mosq) { int payload = 1; int payloadlen = 1; int qos = 2; bool retain = true; // yes, retain the msg on the broker int res = mosquitto_publish(mosq, NULL, SENSOR_WAKEUP_PATT, payloadlen, &payload, qos, retain ); log_result( "Waking up sensor...", res ); } void publish_callback(struct mosquitto *mosq, void *userdata, int result) { log_result( "Wakeup sent to sensor: ", result ); } //Draws a simple bar chart with a blue background in the center of the screen. void draw(SDL_Renderer* renderer, float delta_time) { static float time = 0; time += delta_time; SDL_SetRenderDrawColor(renderer, 0x00, 0x9f, 0xe3, 0xFF ); SDL_Rect rect = {100, 240, 600, 120}; //Background SDL_RenderFillRect(renderer, &rect); //Bars int count = 6; int padding = 2; int start_x = 120; int y = 340; int width = (rect.w - (start_x - rect.x) * 2 - padding * (count - 1))/count; //Draw the bars with a simple sine-wave modulation on height and transparency. for (int i = 0; i < count; ++i) { float offset = ((float)sin(time * 4 + i) + 1.0f)/2.f; int height = offset * 20 + 20; SDL_Rect bar = {start_x, y - height, width, height}; SDL_SetRenderDrawColor(renderer, 0xff, 0xff, 0xff, (unsigned char)(255 * (offset/2 + 0.5f))); SDL_RenderFillRect(renderer, &bar); start_x += padding + width; } } int main(int, char**) { SDL_Window *window = 0; SDL_Renderer *renderer = 0; int code = 0; struct mosquitto* mosq; bool run = true; unsigned int t0 = 0, t1 = 0; mosquitto_lib_init(); if((mosq = mosquitto_new(0, true, 0)) == 0) { std::cout << "Failed to initialize mosquitto." << std::endl; code = 1; goto end; } mosquitto_connect_callback_set(mosq, connect_callback); mosquitto_message_callback_set(mosq, message_callback); mosquitto_publish_callback_set(mosq, publish_callback); //Init SDL if (SDL_Init(SDL_INIT_VIDEO) != 0){ std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; code = 1; goto end; } //Create a window and renderer attached to it. window = SDL_CreateWindow("SDL Skeleton", 100, 100, 800, 600, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL); renderer = SDL_CreateRenderer(window, 0, SDL_RENDERER_PRESENTVSYNC); if(!window || !renderer) { std::cout << "SDL_CreateWindow or SDL_CreateRenderer Error: " << SDL_GetError() << std::endl; code = 1; goto end; } SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND); //Attempt mosquitto connection to local host. mosquitto_connect_async(mosq, "amee.interaktionsbyran.se", 1883, 60); //Start the mosquitto network thread. if(mosquitto_loop_start(mosq) != MOSQ_ERR_SUCCESS) { std::cout << "Failed mosquitto init " << mosq << std::endl; code = 1; goto end; } //Block untill the user closes the window SDL_Event e; while (run) { t1 = SDL_GetTicks(); float delta_time = (float)(t1 - t0)/1000.f; while( SDL_PollEvent( &e ) != 0) { if( e.type == SDL_QUIT ) { run = false; break; } } //Clear buffer. SDL_SetRenderDrawColor(renderer, 0xff, 0xff, 0xff, 0xff); SDL_RenderClear(renderer); draw(renderer, delta_time); SDL_RenderPresent(renderer); t0 = t1; } end: SDL_Quit(); //Cleanup mqtt mosquitto_loop_stop(mosq, true); mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return code; } <|endoftext|>
<commit_before> #include <v8.h> #include <node.h> #include <node_buffer.h> #include <node_object_wrap.h> #include "../deps/celt-0.7.1/libcelt/celt.h" #include "common.h" #include <nan.h> #include <string.h> using namespace node; using namespace v8; class CeltEncoder : public ObjectWrap { private: CELTMode* mode; CELTEncoder* encoder; CELTDecoder* decoder; Persistent<Object> modeReference; unsigned char compressedBuffer[43]; celt_int16* frameBuffer; int frameSize; protected: void EnsureEncoder() { if( encoder != NULL ) return; encoder = celt_encoder_create( mode, 1, NULL ); } void EnsureDecoder() { if( decoder != NULL ) return; decoder = celt_decoder_create( mode, 1, NULL ); } public: CeltEncoder( celt_int32 rate, int frame_size ): encoder( NULL ), decoder( NULL ), frameSize( frame_size ) { mode = celt_mode_create( rate, frame_size, NULL ); frameBuffer = new celt_int16[frame_size]; } ~CeltEncoder() { if( encoder != NULL ) celt_encoder_destroy( encoder ); if( decoder != NULL ) celt_decoder_destroy( decoder ); encoder = NULL; decoder = NULL; celt_mode_destroy( mode ); mode = 0; delete frameBuffer; frameBuffer = 0; } static NAN_METHOD(Encode) { REQ_OBJ_ARG( 0, pcmBuffer ); OPT_INT_ARG( 1, compressedSize, 43 ); // Read the PCM data. char* pcmData = Buffer::Data(pcmBuffer); celt_int16* pcm = reinterpret_cast<celt_int16*>( pcmData ); // Unwrap the encoder. CeltEncoder* self = ObjectWrap::Unwrap<CeltEncoder>( info.This() ); self->EnsureEncoder(); // Encode the samples. size_t compressedLength = (size_t)celt_encode( self->encoder, pcm, NULL, &(self->compressedBuffer[0]), compressedSize ); // Create a new result buffer. Local<Object> actualBuffer = Nan::CopyBuffer(reinterpret_cast<char*>(self->compressedBuffer), compressedLength ).ToLocalChecked(); info.GetReturnValue().Set( actualBuffer ); } static NAN_METHOD(Decode) { REQ_OBJ_ARG( 0, compressedBuffer ); // Read the compressed data. unsigned char* compressedData = (unsigned char*)Buffer::Data(compressedBuffer); size_t compressedDataLength = Buffer::Length(compressedBuffer); CeltEncoder* self = ObjectWrap::Unwrap<CeltEncoder>( info.This() ); self->EnsureDecoder(); // Encode the samples. celt_decode( self->decoder, compressedData, compressedDataLength, &(self->frameBuffer[0]) ); // Create a new result buffer. int dataSize = self->frameSize * 2; Local<Object> actualBuffer = Nan::CopyBuffer(reinterpret_cast<char*>(self->frameBuffer), dataSize).ToLocalChecked(); info.GetReturnValue().Set( actualBuffer ); } static NAN_METHOD(New) { if( !info.IsConstructCall()) { return Nan::ThrowTypeError("Use the new operator to construct the CeltEncoder."); } OPT_INT_ARG(0, rate, 42000); OPT_INT_ARG(1, size, rate/100); CeltEncoder* encoder = new CeltEncoder( rate, size ); encoder->Wrap( info.This() ); info.GetReturnValue().Set(info.This()); } static NAN_METHOD(SetBitrate) { REQ_INT_ARG( 0, bitrate ); CeltEncoder* self = ObjectWrap::Unwrap<CeltEncoder>( info.This() ); self->EnsureEncoder(); celt_encoder_ctl( self->encoder, CELT_SET_VBR_RATE( bitrate ) ); } static void Init(Handle<Object> exports) { Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New); tpl->SetClassName(Nan::New<String>("CeltEncoder").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); tpl->PrototypeTemplate()->Set( Nan::New<String>("encode").ToLocalChecked(), Nan::New<FunctionTemplate>( Encode )->GetFunction() ); tpl->PrototypeTemplate()->Set( Nan::New<String>("decode").ToLocalChecked(), Nan::New<FunctionTemplate>( Decode )->GetFunction() ); tpl->PrototypeTemplate()->Set( Nan::New<String>("setBitrate").ToLocalChecked(), Nan::New<FunctionTemplate>( SetBitrate )->GetFunction() ); //v8::Persistent<v8::FunctionTemplate> constructor; //NanAssignPersistent(constructor, tpl); exports->Set(Nan::New<String>("CeltEncoder").ToLocalChecked(), tpl->GetFunction()); } }; void NodeInit(Handle<Object> exports) { CeltEncoder::Init( exports ); } NODE_MODULE(node_celt, NodeInit) <commit_msg>Fixed prototype functions<commit_after> #include <v8.h> #include <node.h> #include <node_buffer.h> #include <node_object_wrap.h> #include "../deps/celt-0.7.1/libcelt/celt.h" #include "common.h" #include <nan.h> #include <string.h> using namespace node; using namespace v8; class CeltEncoder : public ObjectWrap { private: CELTMode* mode; CELTEncoder* encoder; CELTDecoder* decoder; Persistent<Object> modeReference; unsigned char compressedBuffer[43]; celt_int16* frameBuffer; int frameSize; protected: void EnsureEncoder() { if( encoder != NULL ) return; encoder = celt_encoder_create( mode, 1, NULL ); } void EnsureDecoder() { if( decoder != NULL ) return; decoder = celt_decoder_create( mode, 1, NULL ); } public: CeltEncoder( celt_int32 rate, int frame_size ): encoder( NULL ), decoder( NULL ), frameSize( frame_size ) { mode = celt_mode_create( rate, frame_size, NULL ); frameBuffer = new celt_int16[frame_size]; } ~CeltEncoder() { if( encoder != NULL ) celt_encoder_destroy( encoder ); if( decoder != NULL ) celt_decoder_destroy( decoder ); encoder = NULL; decoder = NULL; celt_mode_destroy( mode ); mode = 0; delete frameBuffer; frameBuffer = 0; } static NAN_METHOD(Encode) { REQ_OBJ_ARG( 0, pcmBuffer ); OPT_INT_ARG( 1, compressedSize, 43 ); // Read the PCM data. char* pcmData = Buffer::Data(pcmBuffer); celt_int16* pcm = reinterpret_cast<celt_int16*>( pcmData ); // Unwrap the encoder. CeltEncoder* self = ObjectWrap::Unwrap<CeltEncoder>( info.This() ); self->EnsureEncoder(); // Encode the samples. size_t compressedLength = (size_t)celt_encode( self->encoder, pcm, NULL, &(self->compressedBuffer[0]), compressedSize ); // Create a new result buffer. Local<Object> actualBuffer = Nan::CopyBuffer(reinterpret_cast<char*>(self->compressedBuffer), compressedLength ).ToLocalChecked(); info.GetReturnValue().Set( actualBuffer ); } static NAN_METHOD(Decode) { REQ_OBJ_ARG( 0, compressedBuffer ); // Read the compressed data. unsigned char* compressedData = (unsigned char*)Buffer::Data(compressedBuffer); size_t compressedDataLength = Buffer::Length(compressedBuffer); CeltEncoder* self = ObjectWrap::Unwrap<CeltEncoder>( info.This() ); self->EnsureDecoder(); // Encode the samples. celt_decode( self->decoder, compressedData, compressedDataLength, &(self->frameBuffer[0]) ); // Create a new result buffer. int dataSize = self->frameSize * 2; Local<Object> actualBuffer = Nan::CopyBuffer(reinterpret_cast<char*>(self->frameBuffer), dataSize).ToLocalChecked(); info.GetReturnValue().Set( actualBuffer ); } static NAN_METHOD(New) { if( !info.IsConstructCall()) { return Nan::ThrowTypeError("Use the new operator to construct the CeltEncoder."); } OPT_INT_ARG(0, rate, 42000); OPT_INT_ARG(1, size, rate/100); CeltEncoder* encoder = new CeltEncoder( rate, size ); encoder->Wrap( info.This() ); info.GetReturnValue().Set(info.This()); } static NAN_METHOD(SetBitrate) { REQ_INT_ARG( 0, bitrate ); CeltEncoder* self = ObjectWrap::Unwrap<CeltEncoder>( info.This() ); self->EnsureEncoder(); celt_encoder_ctl( self->encoder, CELT_SET_VBR_RATE( bitrate ) ); } static void Init(Handle<Object> exports) { Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New); tpl->SetClassName(Nan::New<String>("CeltEncoder").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod( tpl, "encode", Encode ); Nan::SetPrototypeMethod( tpl, "decode", Decode ); Nan::SetPrototypeMethod( tpl, "setBitrate", SetBitrate ); //v8::Persistent<v8::FunctionTemplate> constructor; //NanAssignPersistent(constructor, tpl); exports->Set(Nan::New<String>("CeltEncoder").ToLocalChecked(), tpl->GetFunction()); } }; void NodeInit(Handle<Object> exports) { CeltEncoder::Init( exports ); } NODE_MODULE(node_celt, NodeInit) <|endoftext|>
<commit_before>/* * Copyright (c) 2011, Nathan Rajlich <[email protected]> * * Permission to use, copy, modify, and/or 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 DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR 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 <v8.h> #include <node.h> #include <node_buffer.h> #include <lame/lame.h> using namespace v8; using namespace node; namespace { /* Wrapper ObjectTemplate to hold `lame_t` instances */ Persistent<ObjectTemplate> gfpClass; /* get_lame_version() */ Handle<Value> node_get_lame_version (const Arguments& args) { HandleScope scope; return scope.Close(String::New(get_lame_version())); } /* malloc()'s a `lame_t` struct and returns it to JS land */ Handle<Value> node_malloc_gfp (const Arguments& args) { HandleScope scope; lame_global_flags *gfp = lame_init(); Local<Object> wrapper = gfpClass->NewInstance(); wrapper->SetPointerInInternalField(0, gfp); return scope.Close(wrapper); } /* lame_encode_buffer_interleaved() */ Handle<Value> node_lame_encode_buffer_interleaved (const Arguments& args) { HandleScope scope; // TODO: Argument validation Local<Object> wrapper = args[0]->ToObject(); lame_global_flags *gfp = (lame_global_flags *)wrapper->GetPointerFromInternalField(0); // Turn into 'short int []' char *input = Buffer::Data(args[1]->ToObject()); short int *pcm = (short int *)input; // num in 1 channel, not entire pcm array int num_samples = args[2]->Int32Value(); Local<Object> outbuf = args[3]->ToObject(); unsigned char *mp3buf = (unsigned char *)Buffer::Data(outbuf); int mp3buf_size = Buffer::Length(outbuf); int b = lame_encode_buffer_interleaved(gfp, pcm, num_samples, mp3buf, mp3buf_size); return scope.Close(Integer::New(b)); } /* lame_encode_flush() */ Handle<Value> node_lame_encode_flush (const Arguments& args) { HandleScope scope; // TODO: Argument validation Local<Object> wrapper = args[0]->ToObject(); lame_global_flags *gfp = (lame_global_flags *)wrapper->GetPointerFromInternalField(0); Local<Object> outbuf = args[1]->ToObject(); unsigned char *mp3buf = (unsigned char *)Buffer::Data(outbuf); int mp3buf_size = Buffer::Length(outbuf); int b = lame_encode_flush(gfp, mp3buf, mp3buf_size); return scope.Close(Integer::New(b)); } /* lame_get_num_channels(gfp) */ Handle<Value> node_lame_get_num_channels (const Arguments& args) { HandleScope scope; // TODO: Argument validation Local<Object> wrapper = args[0]->ToObject(); lame_global_flags *gfp = (lame_global_flags *)wrapper->GetPointerFromInternalField(0); return scope.Close(Integer::New(lame_get_num_channels(gfp))); } /* lame_set_num_channels(gfp) */ Handle<Value> node_lame_set_num_channels (const Arguments& args) { HandleScope scope; // TODO: Argument validation Local<Object> wrapper = args[0]->ToObject(); lame_global_flags *gfp = (lame_global_flags *)wrapper->GetPointerFromInternalField(0); Local<Number> val = args[1]->ToNumber(); return scope.Close(Integer::New(lame_set_num_channels(gfp, val->Int32Value()))); } /* lame_init_params(gfp) */ Handle<Value> node_lame_init_params (const Arguments& args) { HandleScope scope; // TODO: Argument validation Local<Object> wrapper = args[0]->ToObject(); lame_global_flags *gfp = (lame_global_flags *)wrapper->GetPointerFromInternalField(0); if (lame_init_params(gfp) < 0) { return ThrowException(String::New("lame_init_params() failed")); } return Undefined(); } /* lame_print_internals() */ Handle<Value> node_lame_print_internals (const Arguments& args) { HandleScope scope; // TODO: Argument validation Local<Object> wrapper = args[0]->ToObject(); lame_global_flags *gfp = (lame_global_flags *)wrapper->GetPointerFromInternalField(0); lame_print_internals(gfp); return Undefined(); } /* lame_print_config() */ Handle<Value> node_lame_print_config (const Arguments& args) { HandleScope scope; // TODO: Argument validation Local<Object> wrapper = args[0]->ToObject(); lame_global_flags *gfp = (lame_global_flags *)wrapper->GetPointerFromInternalField(0); lame_print_config(gfp); return Undefined(); } void Initialize(Handle<Object> target) { HandleScope scope; gfpClass = Persistent<ObjectTemplate>::New(ObjectTemplate::New()); gfpClass->SetInternalFieldCount(1); NODE_SET_METHOD(target, "get_lame_version", node_get_lame_version); NODE_SET_METHOD(target, "lame_encode_buffer_interleaved", node_lame_encode_buffer_interleaved); NODE_SET_METHOD(target, "lame_encode_flush", node_lame_encode_flush); NODE_SET_METHOD(target, "lame_get_num_channels", node_lame_get_num_channels); NODE_SET_METHOD(target, "lame_set_num_channels", node_lame_set_num_channels); NODE_SET_METHOD(target, "lame_init_params", node_lame_init_params); NODE_SET_METHOD(target, "lame_print_config", node_lame_print_config); NODE_SET_METHOD(target, "lame_print_internals", node_lame_print_internals); NODE_SET_METHOD(target, "malloc_gfp", node_malloc_gfp); } } // anonymous namespace NODE_MODULE(nodelame, Initialize); <commit_msg>Add lame_close() binding<commit_after>/* * Copyright (c) 2011, Nathan Rajlich <[email protected]> * * Permission to use, copy, modify, and/or 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 DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR 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 <v8.h> #include <node.h> #include <node_buffer.h> #include <lame/lame.h> using namespace v8; using namespace node; namespace { /* Wrapper ObjectTemplate to hold `lame_t` instances */ Persistent<ObjectTemplate> gfpClass; /* get_lame_version() */ Handle<Value> node_get_lame_version (const Arguments& args) { HandleScope scope; return scope.Close(String::New(get_lame_version())); } /* lame_close() */ Handle<Value> node_lame_close (const Arguments& args) { HandleScope scope; // TODO: Argument validation Local<Object> wrapper = args[0]->ToObject(); lame_global_flags *gfp = (lame_global_flags *)wrapper->GetPointerFromInternalField(0); lame_close(gfp); return Undefined(); } /* malloc()'s a `lame_t` struct and returns it to JS land */ Handle<Value> node_malloc_gfp (const Arguments& args) { HandleScope scope; lame_global_flags *gfp = lame_init(); Local<Object> wrapper = gfpClass->NewInstance(); wrapper->SetPointerInInternalField(0, gfp); return scope.Close(wrapper); } /* lame_encode_buffer_interleaved() */ Handle<Value> node_lame_encode_buffer_interleaved (const Arguments& args) { HandleScope scope; // TODO: Argument validation Local<Object> wrapper = args[0]->ToObject(); lame_global_flags *gfp = (lame_global_flags *)wrapper->GetPointerFromInternalField(0); // Turn into 'short int []' char *input = Buffer::Data(args[1]->ToObject()); short int *pcm = (short int *)input; // num in 1 channel, not entire pcm array int num_samples = args[2]->Int32Value(); Local<Object> outbuf = args[3]->ToObject(); unsigned char *mp3buf = (unsigned char *)Buffer::Data(outbuf); int mp3buf_size = Buffer::Length(outbuf); int b = lame_encode_buffer_interleaved(gfp, pcm, num_samples, mp3buf, mp3buf_size); return scope.Close(Integer::New(b)); } /* lame_encode_flush() */ Handle<Value> node_lame_encode_flush (const Arguments& args) { HandleScope scope; // TODO: Argument validation Local<Object> wrapper = args[0]->ToObject(); lame_global_flags *gfp = (lame_global_flags *)wrapper->GetPointerFromInternalField(0); Local<Object> outbuf = args[1]->ToObject(); unsigned char *mp3buf = (unsigned char *)Buffer::Data(outbuf); int mp3buf_size = Buffer::Length(outbuf); int b = lame_encode_flush(gfp, mp3buf, mp3buf_size); return scope.Close(Integer::New(b)); } /* lame_get_num_channels(gfp) */ Handle<Value> node_lame_get_num_channels (const Arguments& args) { HandleScope scope; // TODO: Argument validation Local<Object> wrapper = args[0]->ToObject(); lame_global_flags *gfp = (lame_global_flags *)wrapper->GetPointerFromInternalField(0); return scope.Close(Integer::New(lame_get_num_channels(gfp))); } /* lame_set_num_channels(gfp) */ Handle<Value> node_lame_set_num_channels (const Arguments& args) { HandleScope scope; // TODO: Argument validation Local<Object> wrapper = args[0]->ToObject(); lame_global_flags *gfp = (lame_global_flags *)wrapper->GetPointerFromInternalField(0); Local<Number> val = args[1]->ToNumber(); return scope.Close(Integer::New(lame_set_num_channels(gfp, val->Int32Value()))); } /* lame_init_params(gfp) */ Handle<Value> node_lame_init_params (const Arguments& args) { HandleScope scope; // TODO: Argument validation Local<Object> wrapper = args[0]->ToObject(); lame_global_flags *gfp = (lame_global_flags *)wrapper->GetPointerFromInternalField(0); if (lame_init_params(gfp) < 0) { return ThrowException(String::New("lame_init_params() failed")); } return Undefined(); } /* lame_print_internals() */ Handle<Value> node_lame_print_internals (const Arguments& args) { HandleScope scope; // TODO: Argument validation Local<Object> wrapper = args[0]->ToObject(); lame_global_flags *gfp = (lame_global_flags *)wrapper->GetPointerFromInternalField(0); lame_print_internals(gfp); return Undefined(); } /* lame_print_config() */ Handle<Value> node_lame_print_config (const Arguments& args) { HandleScope scope; // TODO: Argument validation Local<Object> wrapper = args[0]->ToObject(); lame_global_flags *gfp = (lame_global_flags *)wrapper->GetPointerFromInternalField(0); lame_print_config(gfp); return Undefined(); } void Initialize(Handle<Object> target) { HandleScope scope; gfpClass = Persistent<ObjectTemplate>::New(ObjectTemplate::New()); gfpClass->SetInternalFieldCount(1); NODE_SET_METHOD(target, "get_lame_version", node_get_lame_version); NODE_SET_METHOD(target, "lame_close", node_lame_close); NODE_SET_METHOD(target, "lame_encode_buffer_interleaved", node_lame_encode_buffer_interleaved); NODE_SET_METHOD(target, "lame_encode_flush", node_lame_encode_flush); NODE_SET_METHOD(target, "lame_get_num_channels", node_lame_get_num_channels); NODE_SET_METHOD(target, "lame_set_num_channels", node_lame_set_num_channels); NODE_SET_METHOD(target, "lame_init_params", node_lame_init_params); NODE_SET_METHOD(target, "lame_print_config", node_lame_print_config); NODE_SET_METHOD(target, "lame_print_internals", node_lame_print_internals); NODE_SET_METHOD(target, "malloc_gfp", node_malloc_gfp); } } // anonymous namespace NODE_MODULE(nodelame, Initialize); <|endoftext|>
<commit_before>#include "timer.h" #include <cassert> #include <chrono> #include <condition_variable> #include <mutex> #include <queue> #include <thread> #include <unordered_set> namespace ivm { /** * Contains data on a timer. This is shared between the timer_t handle and the thread responsible * for the timer. */ struct timer_data_t { timer_data_t( std::chrono::steady_clock::time_point timeout, void** holder, timer_t::callback_t callback, const std::lock_guard<std::mutex>& /*lock*/ ) : callback{std::move(callback)}, holder{holder}, timeout{timeout} { if (holder != nullptr) { last_holder_value = std::exchange(*holder, static_cast<void*>(this)); } } auto adjust() -> bool { if (paused_duration == std::chrono::steady_clock::duration{}) { return false; } else { timeout += paused_duration; paused_duration = {}; return true; } } auto is_paused() const -> bool { return paused_at != std::chrono::steady_clock::time_point{}; } void pause() { paused_at = std::chrono::steady_clock::now(); } void resume() { paused_duration += std::chrono::steady_clock::now() - paused_at; paused_at = {}; } struct cmp { auto operator()(const std::shared_ptr<timer_data_t>& left, const std::shared_ptr<timer_data_t>& right) const { return left->timeout > right->timeout; } }; timer_t::callback_t callback; void** holder = nullptr; void* last_holder_value; std::chrono::steady_clock::time_point timeout; std::chrono::steady_clock::time_point paused_at{}; std::chrono::steady_clock::duration paused_duration{}; std::shared_ptr<timer_data_t> threadless_self; bool is_alive = true; bool is_running = false; bool is_dtor_waiting = false; }; namespace { /** * Stash these here in case statics are destroyed while the module is unloading but timers are still * active */ struct shared_state_t { std::unordered_set<struct timer_thread_t*> threads; std::condition_variable cv; std::mutex mutex; }; auto global_shared_state = std::make_shared<shared_state_t>(); /** * Manager for a thread which handles 1 or many timers. */ struct timer_thread_t { explicit timer_thread_t(std::shared_ptr<timer_data_t> first_timer) : next_timeout{first_timer->timeout}, shared_state{global_shared_state} { queue.emplace(std::move(first_timer)); std::thread thread{[this] { entry(); }}; thread.detach(); } void entry() { std::unique_lock<std::mutex> lock{shared_state->mutex, std::defer_lock}; while (true) { std::this_thread::sleep_until(next_timeout); lock.lock(); next_timeout = std::chrono::steady_clock::now(); run_next(lock); if (queue.empty()) { auto ii = shared_state->threads.find(this); assert(ii != shared_state->threads.end()); shared_state->threads.erase(ii); lock.unlock(); delete this; return; } next_timeout = queue.top()->timeout; lock.unlock(); } } void maybe_run_next(std::unique_lock<std::mutex>& lock) { if (!queue.empty() && queue.top()->timeout <= next_timeout) { run_next(lock); } } void run_next(std::unique_lock<std::mutex>& lock) { auto data = queue.top(); queue.pop(); { if (data->is_alive) { if (data->is_paused()) { data->threadless_self = std::move(data); } else if (data->adjust()) { start_or_join_timer(std::move(data), lock); } else { data->is_running = true; lock.unlock(); data->callback(reinterpret_cast<void*>(this)); lock.lock(); data->is_running = false; if (data->is_dtor_waiting) { shared_state->cv.notify_all(); } return; } } else { data.reset(); } } maybe_run_next(lock); } // Requires lock template <template<class> class Lock> static void start_or_join_timer(std::shared_ptr<timer_data_t> data, const Lock<std::mutex>& /*lock*/) { // Try to find a thread to put this timer into for (const auto& thread : global_shared_state->threads) { if (thread->next_timeout < data->timeout) { thread->queue.push(std::move(data)); return; } } // Time to spawn a new thread global_shared_state->threads.insert(new timer_thread_t(std::move(data))); } std::priority_queue< std::shared_ptr<timer_data_t>, std::deque<std::shared_ptr<timer_data_t>>, timer_data_t::cmp > queue; std::chrono::steady_clock::time_point next_timeout; std::shared_ptr<shared_state_t> shared_state; }; } // anonymous namespace /** * timer_t implementation */ timer_t::timer_t(uint32_t ms, void** holder, const callback_t& callback) { std::lock_guard<std::mutex> lock{global_shared_state->mutex}; data = std::make_shared<timer_data_t>( std::chrono::steady_clock::now() + std::chrono::milliseconds{ms}, holder, callback, lock ); timer_thread_t::start_or_join_timer(data, lock); } timer_t::~timer_t() { std::unique_lock<std::mutex> lock{global_shared_state->mutex}; if (data->is_running) { data->is_dtor_waiting = true; do { global_shared_state->cv.wait(lock); } while (data->is_running); } data->is_alive = false; if (data->holder != nullptr) { *data->holder = data->last_holder_value; } } void timer_t::chain(void* ptr) { auto& thread = *reinterpret_cast<timer_thread_t*>(ptr); std::unique_lock<std::mutex> lock{global_shared_state->mutex}; thread.maybe_run_next(lock); } void timer_t::pause(void*& holder) { std::unique_lock<std::mutex> lock{global_shared_state->mutex}; if (holder != nullptr) { auto& data = *static_cast<timer_data_t*>(holder); data.pause(); } } void timer_t::resume(void*& holder) { std::unique_lock<std::mutex> lock{global_shared_state->mutex}; if (holder != nullptr) { auto& data = *static_cast<timer_data_t*>(holder); data.resume(); if (data.threadless_self) { timer_thread_t::start_or_join_timer(std::move(data.threadless_self), lock); } } } void timer_t::wait_detached(uint32_t ms, const callback_t& callback) { std::lock_guard<std::mutex> lock{global_shared_state->mutex}; timer_thread_t::start_or_join_timer(std::make_shared<timer_data_t>( std::chrono::steady_clock::now() + std::chrono::milliseconds{ms}, nullptr, callback, lock ), lock); } } // namespace ivm <commit_msg>Add missing #include<commit_after>#include "timer.h" #include <cassert> #include <chrono> #include <condition_variable> #include <mutex> #include <queue> #include <thread> #include <utility> #include <unordered_set> namespace ivm { /** * Contains data on a timer. This is shared between the timer_t handle and the thread responsible * for the timer. */ struct timer_data_t { timer_data_t( std::chrono::steady_clock::time_point timeout, void** holder, timer_t::callback_t callback, const std::lock_guard<std::mutex>& /*lock*/ ) : callback{std::move(callback)}, holder{holder}, timeout{timeout} { if (holder != nullptr) { last_holder_value = std::exchange(*holder, static_cast<void*>(this)); } } auto adjust() -> bool { if (paused_duration == std::chrono::steady_clock::duration{}) { return false; } else { timeout += paused_duration; paused_duration = {}; return true; } } auto is_paused() const -> bool { return paused_at != std::chrono::steady_clock::time_point{}; } void pause() { paused_at = std::chrono::steady_clock::now(); } void resume() { paused_duration += std::chrono::steady_clock::now() - paused_at; paused_at = {}; } struct cmp { auto operator()(const std::shared_ptr<timer_data_t>& left, const std::shared_ptr<timer_data_t>& right) const { return left->timeout > right->timeout; } }; timer_t::callback_t callback; void** holder = nullptr; void* last_holder_value; std::chrono::steady_clock::time_point timeout; std::chrono::steady_clock::time_point paused_at{}; std::chrono::steady_clock::duration paused_duration{}; std::shared_ptr<timer_data_t> threadless_self; bool is_alive = true; bool is_running = false; bool is_dtor_waiting = false; }; namespace { /** * Stash these here in case statics are destroyed while the module is unloading but timers are still * active */ struct shared_state_t { std::unordered_set<struct timer_thread_t*> threads; std::condition_variable cv; std::mutex mutex; }; auto global_shared_state = std::make_shared<shared_state_t>(); /** * Manager for a thread which handles 1 or many timers. */ struct timer_thread_t { explicit timer_thread_t(std::shared_ptr<timer_data_t> first_timer) : next_timeout{first_timer->timeout}, shared_state{global_shared_state} { queue.emplace(std::move(first_timer)); std::thread thread{[this] { entry(); }}; thread.detach(); } void entry() { std::unique_lock<std::mutex> lock{shared_state->mutex, std::defer_lock}; while (true) { std::this_thread::sleep_until(next_timeout); lock.lock(); next_timeout = std::chrono::steady_clock::now(); run_next(lock); if (queue.empty()) { auto ii = shared_state->threads.find(this); assert(ii != shared_state->threads.end()); shared_state->threads.erase(ii); lock.unlock(); delete this; return; } next_timeout = queue.top()->timeout; lock.unlock(); } } void maybe_run_next(std::unique_lock<std::mutex>& lock) { if (!queue.empty() && queue.top()->timeout <= next_timeout) { run_next(lock); } } void run_next(std::unique_lock<std::mutex>& lock) { auto data = queue.top(); queue.pop(); { if (data->is_alive) { if (data->is_paused()) { data->threadless_self = std::move(data); } else if (data->adjust()) { start_or_join_timer(std::move(data), lock); } else { data->is_running = true; lock.unlock(); data->callback(reinterpret_cast<void*>(this)); lock.lock(); data->is_running = false; if (data->is_dtor_waiting) { shared_state->cv.notify_all(); } return; } } else { data.reset(); } } maybe_run_next(lock); } // Requires lock template <template<class> class Lock> static void start_or_join_timer(std::shared_ptr<timer_data_t> data, const Lock<std::mutex>& /*lock*/) { // Try to find a thread to put this timer into for (const auto& thread : global_shared_state->threads) { if (thread->next_timeout < data->timeout) { thread->queue.push(std::move(data)); return; } } // Time to spawn a new thread global_shared_state->threads.insert(new timer_thread_t(std::move(data))); } std::priority_queue< std::shared_ptr<timer_data_t>, std::deque<std::shared_ptr<timer_data_t>>, timer_data_t::cmp > queue; std::chrono::steady_clock::time_point next_timeout; std::shared_ptr<shared_state_t> shared_state; }; } // anonymous namespace /** * timer_t implementation */ timer_t::timer_t(uint32_t ms, void** holder, const callback_t& callback) { std::lock_guard<std::mutex> lock{global_shared_state->mutex}; data = std::make_shared<timer_data_t>( std::chrono::steady_clock::now() + std::chrono::milliseconds{ms}, holder, callback, lock ); timer_thread_t::start_or_join_timer(data, lock); } timer_t::~timer_t() { std::unique_lock<std::mutex> lock{global_shared_state->mutex}; if (data->is_running) { data->is_dtor_waiting = true; do { global_shared_state->cv.wait(lock); } while (data->is_running); } data->is_alive = false; if (data->holder != nullptr) { *data->holder = data->last_holder_value; } } void timer_t::chain(void* ptr) { auto& thread = *reinterpret_cast<timer_thread_t*>(ptr); std::unique_lock<std::mutex> lock{global_shared_state->mutex}; thread.maybe_run_next(lock); } void timer_t::pause(void*& holder) { std::unique_lock<std::mutex> lock{global_shared_state->mutex}; if (holder != nullptr) { auto& data = *static_cast<timer_data_t*>(holder); data.pause(); } } void timer_t::resume(void*& holder) { std::unique_lock<std::mutex> lock{global_shared_state->mutex}; if (holder != nullptr) { auto& data = *static_cast<timer_data_t*>(holder); data.resume(); if (data.threadless_self) { timer_thread_t::start_or_join_timer(std::move(data.threadless_self), lock); } } } void timer_t::wait_detached(uint32_t ms, const callback_t& callback) { std::lock_guard<std::mutex> lock{global_shared_state->mutex}; timer_thread_t::start_or_join_timer(std::make_shared<timer_data_t>( std::chrono::steady_clock::now() + std::chrono::milliseconds{ms}, nullptr, callback, lock ), lock); } } // namespace ivm <|endoftext|>
<commit_before>#include "Game.hpp" Game::Game(std::string nickname, std::string address, std::string port): mOgreRoot(0), mOgreResourcesCfg(Ogre::StringUtil::BLANK), mOgrePluginsCfg(Ogre::StringUtil::BLANK), mSceneMgr(0), mCameraManager(0), mGameWindow(0), mInput(0), mNickname(nickname), mLocalPlayer(0), mPlayerList(new LocalPlayerList()), mBombManager(0), mLocalMap(0), mAddress(address), mPort(port), mNMFactory(new NetworkMessage::NetworkMessageFactory()), mGCListener(0), mOnlineMode(false), mServerJoined(false), mGameSetUp(false), mSceneCreated(false), mGameRunning(false), mShutDownFlag(false) { if(mAddress != "") mOnlineMode = true; } Game::~Game(){ Ogre::LogManager::getSingletonPtr()->logMessage("Deleting Client Listener"); delete mGCListener; Ogre::LogManager::getSingletonPtr()->logMessage("Deleting Inputs"); delete mInput; Ogre::LogManager::getSingletonPtr()->logMessage("Deleting Camera Manager"); delete mCameraManager; Ogre::LogManager::getSingletonPtr()->logMessage("Deleting Local Map"); delete mLocalMap; Ogre::LogManager::getSingletonPtr()->logMessage("Deleting Local Player"); delete mLocalPlayer; Ogre::LogManager::getSingletonPtr()->logMessage("Deleting Game Window"); delete mGameWindow; Ogre::LogManager::getSingletonPtr()->logMessage("Deleting OGRE Root"); delete mOgreRoot; } void Game::go(){ #ifdef _DEBUG mOgreResourcesCfg = "resources_d.cfg"; mOgrePluginsCfg = "plugins_d.cfg"; #else mOgreResourcesCfg = "resources.cfg"; mOgrePluginsCfg = "plugins.cfg"; #endif if (!setup()) return; mOgreRoot->startRendering(); // clean up destroyScene(); } void Game::shutDown(){ mShutDownFlag = true; } bool Game::injectMouseMove(const OIS::MouseEvent &arg){ if(mGameSetUp) return mLocalPlayer->injectMouseMove(arg); return true; } bool Game::injectMouseDown( const OIS::MouseEvent &arg, OIS::MouseButtonID id ){ if(mGameSetUp) return mLocalPlayer->injectMouseDown(arg, id); return true; } bool Game::injectMouseUp( const OIS::MouseEvent &arg, OIS::MouseButtonID id ){ if(mGameSetUp) return mLocalPlayer->injectMouseUp(arg, id); return true; } bool Game::injectKeyDown(const OIS::KeyEvent &arg){ if(arg.key == OIS::KC_ESCAPE) mShutDownFlag = true; if(mOnlineMode && arg.key == OIS::KC_R) mGCListener->sendMessage( mNMFactory->buildMessage(NetworkMessage::GAMESTART) ); mGameWindow->injectKeyDown(arg); if(mGameSetUp) return mLocalPlayer->injectKeyDown(arg); return true; } bool Game::injectKeyUp(const OIS::KeyEvent &arg){ if(mGameSetUp) return mLocalPlayer->injectKeyUp(arg); return true; } bool Game::injectHeadMove(const Ogre::Vector3 &evt){ if(mGameSetUp) return mLocalPlayer->injectHeadMove(evt); return true; } void Game::injectClientClose(){ if(!mGameSetUp){ if(mServerJoined){ Ogre::LogManager::getSingletonPtr()->logMessage("Lost connection to the server, shutting down"); shutDown(); } else{ Ogre::LogManager::getSingletonPtr()->logMessage("Error while joining server, setting up the game as single player"); offlineSetup(); } } } void Game::injectJoinAccept(NetworkMessage::JoinAccept *message){ mServerJoined = true; PlayerList *pl = message->getPlayerList(); LocalPlayer *tmp; Ogre::LogManager::getSingletonPtr()->logMessage("Creating Local Map"); mLocalMap = new LocalMap( mSceneMgr, mWorld, message->getMapHeight(), message->getMapWidth(), message->getSeed() ); mBombManager = new BombManager(mWorld, mLocalMap); Ogre::LogManager::getSingletonPtr()->logMessage("Filling player list"); for(unsigned int i = 0; i < pl->size(); i++){ if((*pl)[i]->getNickname() == mNickname) tmp = new LocalPlayer(mNickname, mWorld, mCameraManager); else tmp = new LocalPlayer((*pl)[i]->getNickname(), mWorld); tmp->setNodePositionX((*pl)[i]->getNodePositionX()); tmp->setNodePositionY((*pl)[i]->getNodePositionY()); tmp->setNodePositionZ((*pl)[i]->getNodePositionZ()); mPlayerList->addPlayer(tmp); } Ogre::LogManager::getSingletonPtr()->logMessage("Creating Local Player"); mLocalPlayer = mPlayerList->getPlayerByName(mNickname); mGameSetUp = true; } void Game::injectJoinRefuse(NetworkMessage::JoinRefuse *message){ shutDown(); } void Game::injectPlayerJoined(NetworkMessage::PlayerJoined *message){ if(!mGameRunning){ Ogre::LogManager::getSingletonPtr()->logMessage("Adding new player"); LocalPlayer *lp = new LocalPlayer(message->getNickname(), mWorld); lp->setNodePositionX(message->getPositionX()); lp->setNodePositionY(message->getPositionY()); lp->setNodePositionZ(message->getPositionZ()); mPlayerList->addPlayer(lp); } } void Game::injectPlayerLeft(NetworkMessage::PlayerLeft *message){ Ogre::LogManager::getSingletonPtr()->logMessage("Removing player"); mPlayerList->removePlayer( mPlayerList->getPlayerByName(message->getNickname()) ); } void Game::injectGameStart(NetworkMessage::GameStart *message){ Ogre::LogManager::getSingletonPtr()->logMessage("Starting game"); mGameRunning = true; } void Game::injectGameEnd(NetworkMessage::GameEnd *message){ Ogre::LogManager::getSingletonPtr()->logMessage("Ending game"); mGameRunning = false; } void Game::injectPlayerInput(NetworkMessage::PlayerInput *message){ std::string nickname = message->getNickname(); if(nickname != mNickname) mPlayerList->getPlayerByName(nickname)->injectPlayerInput(message); } bool Game::setup(){ mOgreRoot = new Ogre::Root(mOgrePluginsCfg); setupResources(); chooseSceneManager(); if(!configure()) return false; // Create any resource listeners (for loading screens) createResourceListener(); // Load resources loadResources(); mGameWindow->setViewMode("oculus"); // Create the frame listener createFrameListener(); return true; } void Game::chooseSceneManager(){ // Get the SceneManager, in this case a generic one mSceneMgr = mOgreRoot->createSceneManager(Ogre::ST_GENERIC); } bool Game::configure(){ // Show the configuration dialog and initialise the system // You can skip this and use root.restoreConfig() to load configuration // settings if you were sure there are valid ones saved in ogre.cfg if(mOgreRoot->showConfigDialog()){ Ogre::LogManager::getSingletonPtr()->logMessage("Creating Camera Manager"); mCameraManager = new CameraManager(mSceneMgr); Ogre::LogManager::getSingletonPtr()->logMessage("Creating Game Window"); mGameWindow = new GameWindow( mCameraManager, mOgreRoot->initialise(true, "Game Render Window") ); bulletSetup(); if(mOnlineMode) networkSetup(); else offlineSetup(); return true; } else return false; } bool Game::networkSetup(){ Ogre::LogManager::getSingletonPtr()->logMessage("Starting Game Client"); mGCListener = new GameClient::Listener(mAddress, mPort); createNetworkListener(); mGCListener->start(); mGCListener->sendMessage(mNMFactory->buildMessage(NetworkMessage::JOIN, mNickname)); return true; } bool Game::offlineSetup(){ Ogre::LogManager::getSingletonPtr()->logMessage("Generating Local Map"); mLocalMap = new LocalMap(mSceneMgr, mWorld, 15, 15); mBombManager = new BombManager(mWorld, mLocalMap); Ogre::LogManager::getSingletonPtr()->logMessage("Creating Local Player"); mLocalPlayer = new LocalPlayer(mNickname, mWorld, mCameraManager); mPlayerList->addPlayer(mLocalPlayer); mLocalMap->setStartingPosition(0, mLocalPlayer); mOnlineMode = false; mGameSetUp = true; mGameRunning = true; return true; } bool Game::bulletSetup(){ AxisAlignedBox bounds( Ogre::Vector3 (-10000, -10000, -10000), Ogre::Vector3 (10000, 10000, 10000) ); Vector3 gravityVector(0,-9.81 * 2,0); mWorld = new OgreBulletDynamics::DynamicsWorld(mSceneMgr, bounds, gravityVector); debugDrawer = new OgreBulletCollisions::DebugDrawer(); debugDrawer->setDrawWireframe(true); // we want to see the Bullet containers mWorld->setDebugDrawer(debugDrawer); mWorld->setShowDebugShapes(true); // enable it if you want to see the Bullet containers SceneNode *node = mSceneMgr->getRootSceneNode()->createChildSceneNode("debugDrawer", Ogre::Vector3::ZERO); node->attachObject(static_cast <SimpleRenderable *> (debugDrawer)); return true; } void Game::createNetworkListener(){ mGCListener->setCallbackClose(boost::bind(&Game::injectClientClose, this)); mGCListener->setCallbackJoinAccept( boost::bind(&Game::injectJoinAccept, this, _1) ); mGCListener->setCallbackJoinRefuse( boost::bind(&Game::injectJoinRefuse, this, _1) ); mGCListener->setCallbackPlayerJoined( boost::bind(&Game::injectPlayerJoined, this, _1) ); mGCListener->setCallbackPlayerLeft( boost::bind(&Game::injectPlayerLeft, this, _1) ); mGCListener->setCallbackGameStart( boost::bind(&Game::injectGameStart, this, _1) ); mGCListener->setCallbackGameEnd( boost::bind(&Game::injectGameEnd, this, _1) ); mGCListener->setCallbackPlayerInput( boost::bind(&Game::injectPlayerInput, this, _1) ); } void Game::createFrameListener(){ Ogre::LogManager::getSingletonPtr()->logMessage("Creating Input"); mInput = new Input(mGameWindow->getWindow()); mInput->setMouseListener( boost::bind(&Game::injectMouseMove, this, _1), boost::bind(&Game::injectMouseDown, this, _1, _2), boost::bind(&Game::injectMouseUp, this, _1, _2) ); mInput->setKeyboardListener( boost::bind(&Game::injectKeyDown, this, _1), boost::bind(&Game::injectKeyUp, this, _1) ); mInput->setSensorFusionListener( boost::bind(&Game::injectHeadMove, this, _1) ); mOgreRoot->addFrameListener(this); } void Game::createScene(){ Animation::setDefaultInterpolationMode(Animation::IM_LINEAR); Animation::setDefaultRotationInterpolationMode(Animation::RIM_LINEAR); Ogre::LogManager::getSingletonPtr()->logMessage("Generating player graphics"); for(unsigned int i = 0; i < mPlayerList->size(); i++) (*mPlayerList)[i]->generateGraphics(); mLocalPlayer->lookAt(mLocalMap->getMapCenter()); Ogre::LogManager::getSingletonPtr()->logMessage("Generating Local Map"); mLocalMap->generate(); // Lights mSceneMgr->setAmbientLight(Ogre::ColourValue(0.5f, 0.5f, 0.5f)); mSceneMgr->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_ADDITIVE); mSceneCreated = true; } void Game::destroyScene(){} void Game::setupResources(){ // Load resource paths from config file Ogre::ConfigFile cf; cf.load(mOgreResourcesCfg); // Go through all sections & settings in the file Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator(); Ogre::String secName, typeName, archName; while (seci.hasMoreElements()){ secName = seci.peekNextKey(); Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext(); Ogre::ConfigFile::SettingsMultiMap::iterator i; for (i = settings->begin(); i != settings->end(); ++i){ typeName = i->first; archName = i->second; Ogre::ResourceGroupManager::getSingleton().addResourceLocation( archName, typeName, secName); } } } void Game::createResourceListener(){} void Game::loadResources(){ Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); } bool Game::frameRenderingQueued(const Ogre::FrameEvent &evt){ if(mShutDownFlag) return false; if(mOnlineMode && mGCListener->isClosed()) return false; mInput->capture(); if(mGameRunning){ if(!mSceneCreated) createScene(); for(unsigned int i = 0; i < mPlayerList->size(); i++) (*mPlayerList)[i]->frameRenderingQueued(evt); mBombManager->add("Target6", Ogre::Vector3(10,5,10)); mBombManager->frameRenderingQueued(); if(mOnlineMode && mLocalPlayer->hadUsefulInput()) sendPlayerInput(); mWorld->stepSimulation(evt.timeSinceLastFrame); } return true; } void Game::sendPlayerInput(){ mGCListener->sendMessage( mNMFactory->buildMessage(NetworkMessage::PLAYERINPUT, mLocalPlayer) ); } <commit_msg>set the defaut camera mode to default (simple camera)<commit_after>#include "Game.hpp" Game::Game(std::string nickname, std::string address, std::string port): mOgreRoot(0), mOgreResourcesCfg(Ogre::StringUtil::BLANK), mOgrePluginsCfg(Ogre::StringUtil::BLANK), mSceneMgr(0), mCameraManager(0), mGameWindow(0), mInput(0), mNickname(nickname), mLocalPlayer(0), mPlayerList(new LocalPlayerList()), mBombManager(0), mLocalMap(0), mAddress(address), mPort(port), mNMFactory(new NetworkMessage::NetworkMessageFactory()), mGCListener(0), mOnlineMode(false), mServerJoined(false), mGameSetUp(false), mSceneCreated(false), mGameRunning(false), mShutDownFlag(false) { if(mAddress != "") mOnlineMode = true; } Game::~Game(){ Ogre::LogManager::getSingletonPtr()->logMessage("Deleting Client Listener"); delete mGCListener; Ogre::LogManager::getSingletonPtr()->logMessage("Deleting Inputs"); delete mInput; Ogre::LogManager::getSingletonPtr()->logMessage("Deleting Camera Manager"); delete mCameraManager; Ogre::LogManager::getSingletonPtr()->logMessage("Deleting Local Map"); delete mLocalMap; Ogre::LogManager::getSingletonPtr()->logMessage("Deleting Local Player"); delete mLocalPlayer; Ogre::LogManager::getSingletonPtr()->logMessage("Deleting Game Window"); delete mGameWindow; Ogre::LogManager::getSingletonPtr()->logMessage("Deleting OGRE Root"); delete mOgreRoot; } void Game::go(){ #ifdef _DEBUG mOgreResourcesCfg = "resources_d.cfg"; mOgrePluginsCfg = "plugins_d.cfg"; #else mOgreResourcesCfg = "resources.cfg"; mOgrePluginsCfg = "plugins.cfg"; #endif if (!setup()) return; mOgreRoot->startRendering(); // clean up destroyScene(); } void Game::shutDown(){ mShutDownFlag = true; } bool Game::injectMouseMove(const OIS::MouseEvent &arg){ if(mGameSetUp) return mLocalPlayer->injectMouseMove(arg); return true; } bool Game::injectMouseDown( const OIS::MouseEvent &arg, OIS::MouseButtonID id ){ if(mGameSetUp) return mLocalPlayer->injectMouseDown(arg, id); return true; } bool Game::injectMouseUp( const OIS::MouseEvent &arg, OIS::MouseButtonID id ){ if(mGameSetUp) return mLocalPlayer->injectMouseUp(arg, id); return true; } bool Game::injectKeyDown(const OIS::KeyEvent &arg){ if(arg.key == OIS::KC_ESCAPE) mShutDownFlag = true; if(mOnlineMode && arg.key == OIS::KC_R) mGCListener->sendMessage( mNMFactory->buildMessage(NetworkMessage::GAMESTART) ); mGameWindow->injectKeyDown(arg); if(mGameSetUp) return mLocalPlayer->injectKeyDown(arg); return true; } bool Game::injectKeyUp(const OIS::KeyEvent &arg){ if(mGameSetUp) return mLocalPlayer->injectKeyUp(arg); return true; } bool Game::injectHeadMove(const Ogre::Vector3 &evt){ if(mGameSetUp) return mLocalPlayer->injectHeadMove(evt); return true; } void Game::injectClientClose(){ if(!mGameSetUp){ if(mServerJoined){ Ogre::LogManager::getSingletonPtr()->logMessage("Lost connection to the server, shutting down"); shutDown(); } else{ Ogre::LogManager::getSingletonPtr()->logMessage("Error while joining server, setting up the game as single player"); offlineSetup(); } } } void Game::injectJoinAccept(NetworkMessage::JoinAccept *message){ mServerJoined = true; PlayerList *pl = message->getPlayerList(); LocalPlayer *tmp; Ogre::LogManager::getSingletonPtr()->logMessage("Creating Local Map"); mLocalMap = new LocalMap( mSceneMgr, mWorld, message->getMapHeight(), message->getMapWidth(), message->getSeed() ); mBombManager = new BombManager(mWorld, mLocalMap); Ogre::LogManager::getSingletonPtr()->logMessage("Filling player list"); for(unsigned int i = 0; i < pl->size(); i++){ if((*pl)[i]->getNickname() == mNickname) tmp = new LocalPlayer(mNickname, mWorld, mCameraManager); else tmp = new LocalPlayer((*pl)[i]->getNickname(), mWorld); tmp->setNodePositionX((*pl)[i]->getNodePositionX()); tmp->setNodePositionY((*pl)[i]->getNodePositionY()); tmp->setNodePositionZ((*pl)[i]->getNodePositionZ()); mPlayerList->addPlayer(tmp); } Ogre::LogManager::getSingletonPtr()->logMessage("Creating Local Player"); mLocalPlayer = mPlayerList->getPlayerByName(mNickname); mGameSetUp = true; } void Game::injectJoinRefuse(NetworkMessage::JoinRefuse *message){ shutDown(); } void Game::injectPlayerJoined(NetworkMessage::PlayerJoined *message){ if(!mGameRunning){ Ogre::LogManager::getSingletonPtr()->logMessage("Adding new player"); LocalPlayer *lp = new LocalPlayer(message->getNickname(), mWorld); lp->setNodePositionX(message->getPositionX()); lp->setNodePositionY(message->getPositionY()); lp->setNodePositionZ(message->getPositionZ()); mPlayerList->addPlayer(lp); } } void Game::injectPlayerLeft(NetworkMessage::PlayerLeft *message){ Ogre::LogManager::getSingletonPtr()->logMessage("Removing player"); mPlayerList->removePlayer( mPlayerList->getPlayerByName(message->getNickname()) ); } void Game::injectGameStart(NetworkMessage::GameStart *message){ Ogre::LogManager::getSingletonPtr()->logMessage("Starting game"); mGameRunning = true; } void Game::injectGameEnd(NetworkMessage::GameEnd *message){ Ogre::LogManager::getSingletonPtr()->logMessage("Ending game"); mGameRunning = false; } void Game::injectPlayerInput(NetworkMessage::PlayerInput *message){ std::string nickname = message->getNickname(); if(nickname != mNickname) mPlayerList->getPlayerByName(nickname)->injectPlayerInput(message); } bool Game::setup(){ mOgreRoot = new Ogre::Root(mOgrePluginsCfg); setupResources(); chooseSceneManager(); if(!configure()) return false; // Create any resource listeners (for loading screens) createResourceListener(); // Load resources loadResources(); mGameWindow->setViewMode("default"); // Create the frame listener createFrameListener(); return true; } void Game::chooseSceneManager(){ // Get the SceneManager, in this case a generic one mSceneMgr = mOgreRoot->createSceneManager(Ogre::ST_GENERIC); } bool Game::configure(){ // Show the configuration dialog and initialise the system // You can skip this and use root.restoreConfig() to load configuration // settings if you were sure there are valid ones saved in ogre.cfg if(mOgreRoot->showConfigDialog()){ Ogre::LogManager::getSingletonPtr()->logMessage("Creating Camera Manager"); mCameraManager = new CameraManager(mSceneMgr); Ogre::LogManager::getSingletonPtr()->logMessage("Creating Game Window"); mGameWindow = new GameWindow( mCameraManager, mOgreRoot->initialise(true, "Game Render Window") ); bulletSetup(); if(mOnlineMode) networkSetup(); else offlineSetup(); return true; } else return false; } bool Game::networkSetup(){ Ogre::LogManager::getSingletonPtr()->logMessage("Starting Game Client"); mGCListener = new GameClient::Listener(mAddress, mPort); createNetworkListener(); mGCListener->start(); mGCListener->sendMessage(mNMFactory->buildMessage(NetworkMessage::JOIN, mNickname)); return true; } bool Game::offlineSetup(){ Ogre::LogManager::getSingletonPtr()->logMessage("Generating Local Map"); mLocalMap = new LocalMap(mSceneMgr, mWorld, 15, 15); mBombManager = new BombManager(mWorld, mLocalMap); Ogre::LogManager::getSingletonPtr()->logMessage("Creating Local Player"); mLocalPlayer = new LocalPlayer(mNickname, mWorld, mCameraManager); mPlayerList->addPlayer(mLocalPlayer); mLocalMap->setStartingPosition(0, mLocalPlayer); mOnlineMode = false; mGameSetUp = true; mGameRunning = true; return true; } bool Game::bulletSetup(){ AxisAlignedBox bounds( Ogre::Vector3 (-10000, -10000, -10000), Ogre::Vector3 (10000, 10000, 10000) ); Vector3 gravityVector(0,-9.81 * 2,0); mWorld = new OgreBulletDynamics::DynamicsWorld(mSceneMgr, bounds, gravityVector); debugDrawer = new OgreBulletCollisions::DebugDrawer(); debugDrawer->setDrawWireframe(true); // we want to see the Bullet containers mWorld->setDebugDrawer(debugDrawer); mWorld->setShowDebugShapes(true); // enable it if you want to see the Bullet containers SceneNode *node = mSceneMgr->getRootSceneNode()->createChildSceneNode("debugDrawer", Ogre::Vector3::ZERO); node->attachObject(static_cast <SimpleRenderable *> (debugDrawer)); return true; } void Game::createNetworkListener(){ mGCListener->setCallbackClose(boost::bind(&Game::injectClientClose, this)); mGCListener->setCallbackJoinAccept( boost::bind(&Game::injectJoinAccept, this, _1) ); mGCListener->setCallbackJoinRefuse( boost::bind(&Game::injectJoinRefuse, this, _1) ); mGCListener->setCallbackPlayerJoined( boost::bind(&Game::injectPlayerJoined, this, _1) ); mGCListener->setCallbackPlayerLeft( boost::bind(&Game::injectPlayerLeft, this, _1) ); mGCListener->setCallbackGameStart( boost::bind(&Game::injectGameStart, this, _1) ); mGCListener->setCallbackGameEnd( boost::bind(&Game::injectGameEnd, this, _1) ); mGCListener->setCallbackPlayerInput( boost::bind(&Game::injectPlayerInput, this, _1) ); } void Game::createFrameListener(){ Ogre::LogManager::getSingletonPtr()->logMessage("Creating Input"); mInput = new Input(mGameWindow->getWindow()); mInput->setMouseListener( boost::bind(&Game::injectMouseMove, this, _1), boost::bind(&Game::injectMouseDown, this, _1, _2), boost::bind(&Game::injectMouseUp, this, _1, _2) ); mInput->setKeyboardListener( boost::bind(&Game::injectKeyDown, this, _1), boost::bind(&Game::injectKeyUp, this, _1) ); mInput->setSensorFusionListener( boost::bind(&Game::injectHeadMove, this, _1) ); mOgreRoot->addFrameListener(this); } void Game::createScene(){ Animation::setDefaultInterpolationMode(Animation::IM_LINEAR); Animation::setDefaultRotationInterpolationMode(Animation::RIM_LINEAR); Ogre::LogManager::getSingletonPtr()->logMessage("Generating player graphics"); for(unsigned int i = 0; i < mPlayerList->size(); i++) (*mPlayerList)[i]->generateGraphics(); mLocalPlayer->lookAt(mLocalMap->getMapCenter()); Ogre::LogManager::getSingletonPtr()->logMessage("Generating Local Map"); mLocalMap->generate(); // Lights mSceneMgr->setAmbientLight(Ogre::ColourValue(0.5f, 0.5f, 0.5f)); mSceneMgr->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_ADDITIVE); mSceneCreated = true; } void Game::destroyScene(){} void Game::setupResources(){ // Load resource paths from config file Ogre::ConfigFile cf; cf.load(mOgreResourcesCfg); // Go through all sections & settings in the file Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator(); Ogre::String secName, typeName, archName; while (seci.hasMoreElements()){ secName = seci.peekNextKey(); Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext(); Ogre::ConfigFile::SettingsMultiMap::iterator i; for (i = settings->begin(); i != settings->end(); ++i){ typeName = i->first; archName = i->second; Ogre::ResourceGroupManager::getSingleton().addResourceLocation( archName, typeName, secName); } } } void Game::createResourceListener(){} void Game::loadResources(){ Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); } bool Game::frameRenderingQueued(const Ogre::FrameEvent &evt){ if(mShutDownFlag) return false; if(mOnlineMode && mGCListener->isClosed()) return false; mInput->capture(); if(mGameRunning){ if(!mSceneCreated) createScene(); for(unsigned int i = 0; i < mPlayerList->size(); i++) (*mPlayerList)[i]->frameRenderingQueued(evt); mBombManager->add("Target6", Ogre::Vector3(10,5,10)); mBombManager->frameRenderingQueued(); if(mOnlineMode && mLocalPlayer->hadUsefulInput()) sendPlayerInput(); mWorld->stepSimulation(evt.timeSinceLastFrame); } return true; } void Game::sendPlayerInput(){ mGCListener->sendMessage( mNMFactory->buildMessage(NetworkMessage::PLAYERINPUT, mLocalPlayer) ); } <|endoftext|>
<commit_before>/************************************************* * Library Internal/Global State Source File * * (C) 1999-2006 The Botan Project * *************************************************/ #include <botan/libstate.h> #include <botan/config.h> #include <botan/modules.h> #include <botan/engine.h> #include <botan/x509stat.h> #include <botan/stl_util.h> #include <botan/mutex.h> #include <botan/timers.h> #include <botan/charset.h> #include <algorithm> namespace Botan { /************************************************* * Botan's global state * *************************************************/ namespace { Library_State* global_lib_state = 0; } /************************************************* * Access the global state object * *************************************************/ Library_State& global_state() { if(!global_lib_state) { abort(); throw Invalid_State("Library was not initialized correctly"); } return (*global_lib_state); } /************************************************* * Set a new global state object * *************************************************/ void set_global_state(Library_State* new_state) { delete swap_global_state(new_state); } /************************************************* * Swap two global state objects * *************************************************/ Library_State* swap_global_state(Library_State* new_state) { Library_State* old_state = global_lib_state; global_lib_state = new_state; return old_state; } /************************************************* * Increment the Engine iterator * *************************************************/ Engine* Library_State::Engine_Iterator::next() { return lib.get_engine_n(n++); } /************************************************* * Get a new mutex object * *************************************************/ Mutex* Library_State::get_mutex() const { return mutex_factory->make(); } /************************************************* * Get a persistent named mutex object * *************************************************/ Mutex* Library_State::get_named_mutex(const std::string& name) { Mutex* mux = search_map<std::string, Mutex*>(locks, name, 0); if(mux) return mux; return (locks[name] = get_mutex()); } /************************************************* * Get an allocator by its name * *************************************************/ Allocator* Library_State::get_allocator(const std::string& type) const { Named_Mutex_Holder lock("allocator"); if(type != "") return search_map<std::string, Allocator*>(alloc_factory, type, 0); if(!cached_default_allocator) { std::string chosen = config().option("base/default_allocator"); if(chosen == "") chosen = "malloc"; cached_default_allocator = search_map<std::string, Allocator*>(alloc_factory, chosen, 0); } return cached_default_allocator; } /************************************************* * Create a new name to object mapping * *************************************************/ void Library_State::add_allocator(Allocator* allocator, bool set_as_default) { Named_Mutex_Holder lock("allocator"); allocator->init(); const std::string type = allocator->type(); if(alloc_factory[type]) delete alloc_factory[type]; alloc_factory[type] = allocator; if(set_as_default) config().set("conf", "base/default_allocator", type); } /************************************************* * Set the high resolution clock implementation * *************************************************/ void Library_State::set_timer(Timer* new_timer) { if(new_timer) { delete timer; timer = new_timer; } } /************************************************* * Read a high resolution clock * *************************************************/ u64bit Library_State::system_clock() const { return (timer) ? timer->clock() : 0; } /************************************************* * Set the global PRNG * *************************************************/ void Library_State::set_prng(RandomNumberGenerator* new_rng) { Named_Mutex_Holder lock("rng"); delete rng; rng = new_rng; } /************************************************* * Get bytes from the global PRNG * *************************************************/ void Library_State::randomize(byte out[], u32bit length) { Named_Mutex_Holder lock("rng"); rng->randomize(out, length); } /************************************************* * Add a new entropy source to use * *************************************************/ void Library_State::add_entropy_source(EntropySource* src, bool last_in_list) { Named_Mutex_Holder lock("rng"); if(last_in_list) entropy_sources.push_back(src); else entropy_sources.insert(entropy_sources.begin(), src); } /************************************************* * Add some bytes of entropy to the global PRNG * *************************************************/ void Library_State::add_entropy(const byte in[], u32bit length) { Named_Mutex_Holder lock("rng"); rng->add_entropy(in, length); } /************************************************* * Add some bytes of entropy to the global PRNG * *************************************************/ void Library_State::add_entropy(EntropySource& source, bool slow_poll) { Named_Mutex_Holder lock("rng"); rng->add_entropy(source, slow_poll); } /************************************************* * Gather entropy for our PRNG object * *************************************************/ u32bit Library_State::seed_prng(bool slow_poll, u32bit bits_to_get) { Named_Mutex_Holder lock("rng"); u32bit bits = 0; for(u32bit j = 0; j != entropy_sources.size(); ++j) { bits += rng->add_entropy(*(entropy_sources[j]), slow_poll); if(bits_to_get && bits >= bits_to_get) return bits; } return bits; } /************************************************* * Get an engine out of the list * *************************************************/ Engine* Library_State::get_engine_n(u32bit n) const { Named_Mutex_Holder lock("engine"); if(n >= engines.size()) return 0; return engines[n]; } /************************************************* * Add a new engine to the list * *************************************************/ void Library_State::add_engine(Engine* engine) { Named_Mutex_Holder lock("engine"); engines.push_back(engine); } /************************************************* * Set the character set transcoder object * *************************************************/ void Library_State::set_transcoder(class Charset_Transcoder* transcoder) { if(this->transcoder) delete this->transcoder; this->transcoder = transcoder; } /************************************************* * Transcode a string from one charset to another * *************************************************/ std::string Library_State::transcode(const std::string str, Character_Set to, Character_Set from) const { if(!transcoder) throw Invalid_State("Library_State::transcode: No transcoder set"); return transcoder->transcode(str, to, from); } /************************************************* * Set the X509 global state class * *************************************************/ void Library_State::set_x509_state(X509_GlobalState* new_x509_state_obj) { delete x509_state_obj; x509_state_obj = new_x509_state_obj; } /************************************************* * Get the X509 global state class * *************************************************/ X509_GlobalState& Library_State::x509_state() { if(!x509_state_obj) x509_state_obj = new X509_GlobalState(); return (*x509_state_obj); } /************************************************* * Set the configuration object * *************************************************/ Config& Library_State::config() const { if(!config_obj) throw Invalid_State("Library_State::config(): No config set"); return (*config_obj); } /************************************************* * Load modules * *************************************************/ void Library_State::load(Modules& modules) { set_timer(modules.timer()); set_transcoder(modules.transcoder()); std::vector<Allocator*> allocators = modules.allocators(); for(u32bit j = 0; j != allocators.size(); j++) add_allocator(allocators[j], allocators[j]->type() == modules.default_allocator()); std::vector<Engine*> engines = modules.engines(); for(u32bit j = 0; j != engines.size(); ++j) add_engine(engines[j]); std::vector<EntropySource*> sources = modules.entropy_sources(); for(u32bit j = 0; j != sources.size(); ++j) add_entropy_source(sources[j]); } /************************************************* * Library_State Constructor * *************************************************/ Library_State::Library_State(Mutex_Factory* mutex_factory) { if(!mutex_factory) throw Exception("Library_State: no mutex found"); mutex_factory = new Mutex_Factory; this->mutex_factory = mutex_factory; this->timer = new Timer(); this->transcoder = 0; this->config_obj = new Config(); locks["settings"] = get_mutex(); locks["allocator"] = get_mutex(); locks["rng"] = get_mutex(); locks["engine"] = get_mutex(); rng = 0; cached_default_allocator = 0; x509_state_obj = 0; } /************************************************* * Library_State Destructor * *************************************************/ Library_State::~Library_State() { delete x509_state_obj; delete transcoder; delete rng; delete timer; std::for_each(entropy_sources.begin(), entropy_sources.end(), del_fun<EntropySource>()); std::for_each(engines.begin(), engines.end(), del_fun<Engine>()); cached_default_allocator = 0; for(std::map<std::string, Allocator*>::iterator j = alloc_factory.begin(); j != alloc_factory.end(); ++j) { j->second->destroy(); delete j->second; } std::for_each(locks.begin(), locks.end(), delete2nd<std::map<std::string, Mutex*>::value_type>); delete mutex_factory; } } <commit_msg>Remove a line that should have been deleted in the last commit.<commit_after>/************************************************* * Library Internal/Global State Source File * * (C) 1999-2006 The Botan Project * *************************************************/ #include <botan/libstate.h> #include <botan/config.h> #include <botan/modules.h> #include <botan/engine.h> #include <botan/x509stat.h> #include <botan/stl_util.h> #include <botan/mutex.h> #include <botan/timers.h> #include <botan/charset.h> #include <algorithm> namespace Botan { /************************************************* * Botan's global state * *************************************************/ namespace { Library_State* global_lib_state = 0; } /************************************************* * Access the global state object * *************************************************/ Library_State& global_state() { if(!global_lib_state) { abort(); throw Invalid_State("Library was not initialized correctly"); } return (*global_lib_state); } /************************************************* * Set a new global state object * *************************************************/ void set_global_state(Library_State* new_state) { delete swap_global_state(new_state); } /************************************************* * Swap two global state objects * *************************************************/ Library_State* swap_global_state(Library_State* new_state) { Library_State* old_state = global_lib_state; global_lib_state = new_state; return old_state; } /************************************************* * Increment the Engine iterator * *************************************************/ Engine* Library_State::Engine_Iterator::next() { return lib.get_engine_n(n++); } /************************************************* * Get a new mutex object * *************************************************/ Mutex* Library_State::get_mutex() const { return mutex_factory->make(); } /************************************************* * Get a persistent named mutex object * *************************************************/ Mutex* Library_State::get_named_mutex(const std::string& name) { Mutex* mux = search_map<std::string, Mutex*>(locks, name, 0); if(mux) return mux; return (locks[name] = get_mutex()); } /************************************************* * Get an allocator by its name * *************************************************/ Allocator* Library_State::get_allocator(const std::string& type) const { Named_Mutex_Holder lock("allocator"); if(type != "") return search_map<std::string, Allocator*>(alloc_factory, type, 0); if(!cached_default_allocator) { std::string chosen = config().option("base/default_allocator"); if(chosen == "") chosen = "malloc"; cached_default_allocator = search_map<std::string, Allocator*>(alloc_factory, chosen, 0); } return cached_default_allocator; } /************************************************* * Create a new name to object mapping * *************************************************/ void Library_State::add_allocator(Allocator* allocator, bool set_as_default) { Named_Mutex_Holder lock("allocator"); allocator->init(); const std::string type = allocator->type(); if(alloc_factory[type]) delete alloc_factory[type]; alloc_factory[type] = allocator; if(set_as_default) config().set("conf", "base/default_allocator", type); } /************************************************* * Set the high resolution clock implementation * *************************************************/ void Library_State::set_timer(Timer* new_timer) { if(new_timer) { delete timer; timer = new_timer; } } /************************************************* * Read a high resolution clock * *************************************************/ u64bit Library_State::system_clock() const { return (timer) ? timer->clock() : 0; } /************************************************* * Set the global PRNG * *************************************************/ void Library_State::set_prng(RandomNumberGenerator* new_rng) { Named_Mutex_Holder lock("rng"); delete rng; rng = new_rng; } /************************************************* * Get bytes from the global PRNG * *************************************************/ void Library_State::randomize(byte out[], u32bit length) { Named_Mutex_Holder lock("rng"); rng->randomize(out, length); } /************************************************* * Add a new entropy source to use * *************************************************/ void Library_State::add_entropy_source(EntropySource* src, bool last_in_list) { Named_Mutex_Holder lock("rng"); if(last_in_list) entropy_sources.push_back(src); else entropy_sources.insert(entropy_sources.begin(), src); } /************************************************* * Add some bytes of entropy to the global PRNG * *************************************************/ void Library_State::add_entropy(const byte in[], u32bit length) { Named_Mutex_Holder lock("rng"); rng->add_entropy(in, length); } /************************************************* * Add some bytes of entropy to the global PRNG * *************************************************/ void Library_State::add_entropy(EntropySource& source, bool slow_poll) { Named_Mutex_Holder lock("rng"); rng->add_entropy(source, slow_poll); } /************************************************* * Gather entropy for our PRNG object * *************************************************/ u32bit Library_State::seed_prng(bool slow_poll, u32bit bits_to_get) { Named_Mutex_Holder lock("rng"); u32bit bits = 0; for(u32bit j = 0; j != entropy_sources.size(); ++j) { bits += rng->add_entropy(*(entropy_sources[j]), slow_poll); if(bits_to_get && bits >= bits_to_get) return bits; } return bits; } /************************************************* * Get an engine out of the list * *************************************************/ Engine* Library_State::get_engine_n(u32bit n) const { Named_Mutex_Holder lock("engine"); if(n >= engines.size()) return 0; return engines[n]; } /************************************************* * Add a new engine to the list * *************************************************/ void Library_State::add_engine(Engine* engine) { Named_Mutex_Holder lock("engine"); engines.push_back(engine); } /************************************************* * Set the character set transcoder object * *************************************************/ void Library_State::set_transcoder(class Charset_Transcoder* transcoder) { if(this->transcoder) delete this->transcoder; this->transcoder = transcoder; } /************************************************* * Transcode a string from one charset to another * *************************************************/ std::string Library_State::transcode(const std::string str, Character_Set to, Character_Set from) const { if(!transcoder) throw Invalid_State("Library_State::transcode: No transcoder set"); return transcoder->transcode(str, to, from); } /************************************************* * Set the X509 global state class * *************************************************/ void Library_State::set_x509_state(X509_GlobalState* new_x509_state_obj) { delete x509_state_obj; x509_state_obj = new_x509_state_obj; } /************************************************* * Get the X509 global state class * *************************************************/ X509_GlobalState& Library_State::x509_state() { if(!x509_state_obj) x509_state_obj = new X509_GlobalState(); return (*x509_state_obj); } /************************************************* * Set the configuration object * *************************************************/ Config& Library_State::config() const { if(!config_obj) throw Invalid_State("Library_State::config(): No config set"); return (*config_obj); } /************************************************* * Load modules * *************************************************/ void Library_State::load(Modules& modules) { set_timer(modules.timer()); set_transcoder(modules.transcoder()); std::vector<Allocator*> allocators = modules.allocators(); for(u32bit j = 0; j != allocators.size(); j++) add_allocator(allocators[j], allocators[j]->type() == modules.default_allocator()); std::vector<Engine*> engines = modules.engines(); for(u32bit j = 0; j != engines.size(); ++j) add_engine(engines[j]); std::vector<EntropySource*> sources = modules.entropy_sources(); for(u32bit j = 0; j != sources.size(); ++j) add_entropy_source(sources[j]); } /************************************************* * Library_State Constructor * *************************************************/ Library_State::Library_State(Mutex_Factory* mutex_factory) { if(!mutex_factory) throw Exception("Library_State: no mutex found"); this->mutex_factory = mutex_factory; this->timer = new Timer(); this->transcoder = 0; this->config_obj = new Config(); locks["settings"] = get_mutex(); locks["allocator"] = get_mutex(); locks["rng"] = get_mutex(); locks["engine"] = get_mutex(); rng = 0; cached_default_allocator = 0; x509_state_obj = 0; } /************************************************* * Library_State Destructor * *************************************************/ Library_State::~Library_State() { delete x509_state_obj; delete transcoder; delete rng; delete timer; std::for_each(entropy_sources.begin(), entropy_sources.end(), del_fun<EntropySource>()); std::for_each(engines.begin(), engines.end(), del_fun<Engine>()); cached_default_allocator = 0; for(std::map<std::string, Allocator*>::iterator j = alloc_factory.begin(); j != alloc_factory.end(); ++j) { j->second->destroy(); delete j->second; } std::for_each(locks.begin(), locks.end(), delete2nd<std::map<std::string, Mutex*>::value_type>); delete mutex_factory; } } <|endoftext|>
<commit_before>/* kopetemessagemanager.cpp - Manages all chats Copyright (c) 2002 by Duncan Mac-Vicar Prett <[email protected]> Copyright (c) 2002 by Daniel Stone <[email protected]> Copyright (c) 2002 by Martijn Klingens <[email protected]> Copyright (c) 2002-2003 by Olivier Goffart <[email protected]> Copyright (c) 2003 by Jason Keirstead <[email protected]> Kopete (c) 2002-2003 by the Kopete developers <[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 of the License, or (at your option) any later version. * * * ************************************************************************* */ #include <kdebug.h> #include <klocale.h> #include <kopetenotifyclient.h> #include <qapplication.h> #include <kglobal.h> #include <qregexp.h> #include <kmessagebox.h> #include "kopeteaccount.h" #include "kopetemessagemanager.h" #include "kopetemessagemanagerfactory.h" #include "kopeteprefs.h" #include "kopetemetacontact.h" #include "kopetecommandhandler.h" #include "kopeteview.h" struct KMMPrivate { KopeteContactPtrList mContactList; const KopeteContact *mUser; QMap<const KopeteContact *, KopeteOnlineStatus> contactStatus; KopeteProtocol *mProtocol; int mId; bool isEmpty; bool mCanBeDeleted; QDateTime awayTime; QString displayName; KopeteView *view; }; KopeteMessageManager::KopeteMessageManager( const KopeteContact *user, KopeteContactPtrList others, KopeteProtocol *protocol, int id, const char *name ) : QObject( user->account(), name ) { d = new KMMPrivate; d->mUser = user; d->mProtocol = protocol; d->mId = id; d->isEmpty= others.isEmpty(); d->mCanBeDeleted = true; d->view=0L; for( KopeteContact *c = others.first(); c; c = others.next() ) { addContact(c,true); } connect( user, SIGNAL( onlineStatusChanged( KopeteContact *, const KopeteOnlineStatus &, const KopeteOnlineStatus & ) ), this, SLOT( slotStatusChanged( KopeteContact *, const KopeteOnlineStatus &, const KopeteOnlineStatus & ) ) ); connect( this, SIGNAL( contactChanged() ), this, SLOT( slotUpdateDisplayName() ) ); } KopeteMessageManager::~KopeteMessageManager() { /* for( KopeteContact *c = d->mContactList.first(); c; c = d->mContactList.next() ) c->setConversations( c->conversations() - 1 );*/ if (!d) return; d->mCanBeDeleted = false; //prevent double deletion KopeteMessageManagerFactory::factory()->removeSession( this ); emit(closing( this ) ); delete d; } void KopeteMessageManager::slotStatusChanged( KopeteContact *c, const KopeteOnlineStatus &status, const KopeteOnlineStatus &oldStatus ) { if(!KopetePrefs::prefs()->notifyAway()) return; if( status.status() == KopeteOnlineStatus::Away ) { d->awayTime = QDateTime::currentDateTime(); KopeteMessage msg(c, d->mContactList, i18n("%1 has been marked as away.") .arg( QString::fromLatin1("/me") ), KopeteMessage::Outbound, KopeteMessage::PlainText); sendMessage( msg ); } else if( oldStatus.status() == KopeteOnlineStatus::Away && status.status() == KopeteOnlineStatus::Online ) { KopeteMessage msg(c, d->mContactList, i18n("%1 is no longer marked as away. Gone since %1") .arg( QString::fromLatin1("/me") ).arg(KGlobal::locale()->formatDateTime(d->awayTime, true)), KopeteMessage::Outbound, KopeteMessage::PlainText); sendMessage( msg ); } } void KopeteMessageManager::setContactOnlineStatus( const KopeteContact *contact, const KopeteOnlineStatus &status ) { d->contactStatus[ contact ] = status; } const KopeteOnlineStatus KopeteMessageManager::contactOnlineStatus( const KopeteContact *contact ) const { if( d->contactStatus.contains( contact ) ) return d->contactStatus[ contact ]; return contact->onlineStatus(); } const QString KopeteMessageManager::displayName() { if( d->displayName.isNull() ) { connect( this, SIGNAL( contactChanged() ), this, SLOT( slotUpdateDisplayName() ) ); slotUpdateDisplayName(); } return d->displayName; } void KopeteMessageManager::setDisplayName( const QString &newName ) { disconnect( this, SIGNAL( contactChanged() ), this, SLOT( slotUpdateDisplayName() ) ); d->displayName = newName; emit( displayNameChanged() ); } void KopeteMessageManager::slotUpdateDisplayName() { QString nextDisplayName; KopeteContact *c = d->mContactList.first(); if( c->metaContact() ) d->displayName = c->metaContact()->displayName(); else d->displayName = c->displayName(); //If we have only 1 contact, add the status of him if( d->mContactList.count() == 1 ) { d->displayName.append( QString::fromLatin1( " (%1)").arg( c->onlineStatus().description() ) ); } else { while( ( c = d->mContactList.next() ) ) { if( c->metaContact() ) nextDisplayName = c->metaContact()->displayName(); else nextDisplayName = c->displayName(); d->displayName.append( QString::fromLatin1( ", " ) ).append( nextDisplayName ); } } emit( displayNameChanged() ); } const KopeteContactPtrList& KopeteMessageManager::members() const { return d->mContactList; } const KopeteContact* KopeteMessageManager::user() const { return d->mUser; } KopeteProtocol* KopeteMessageManager::protocol() const { return d->mProtocol; } int KopeteMessageManager::mmId() const { return d->mId; } void KopeteMessageManager::setMMId( int id ) { d->mId = id; } void KopeteMessageManager::sendMessage(KopeteMessage &message) { message.setManager(this); KopeteMessage sentMessage = message; if( !KopeteCommandHandler::commandHandler()->processMessage( message, this ) ) { emit messageSent(sentMessage, this); if ( !account()->isAway() || KopetePrefs::prefs()->soundIfAway() ) KNotifyClient::event( 0 , QString::fromLatin1( "kopete_outgoing" ), i18n( "Outgoing Message Sent" ) ); } else emit( messageSuccess() ); } void KopeteMessageManager::messageSucceeded() { emit( messageSuccess() ); } void KopeteMessageManager::appendMessage( KopeteMessage &msg ) { msg.setManager(this); if( msg.direction() == KopeteMessage::Inbound ) { if( KopetePrefs::prefs()->highlightEnabled() && !user()->displayName().isEmpty() && msg.plainBody().contains( QRegExp(QString::fromLatin1("\\b(%1)\\b").arg(user()->displayName()),false) ) ) msg.setImportance( KopeteMessage::Highlight ); emit( messageReceived( msg, this ) ); } emit messageAppended( msg, this ); } void KopeteMessageManager::addContact( const KopeteContact *c, bool suppress ) { if ( d->mContactList.contains(c) ) { kdDebug(14010) << k_funcinfo << "Contact already exists" <<endl; emit contactAdded(c, suppress); } else { if(d->mContactList.count()==1 && d->isEmpty) { KopeteContact *old=d->mContactList.first(); d->mContactList.remove(old); d->mContactList.append(c); //disconnect (old, SIGNAL(displayNameChanged(const QString &, const QString &)), this, SIGNAL(contactChanged())); disconnect (old, SIGNAL(onlineStatusChanged( KopeteContact*, const KopeteOnlineStatus&, const KopeteOnlineStatus&)), this, SIGNAL(contactChanged())); if(old->metaContact()) disconnect (old->metaContact(), SIGNAL(displayNameChanged(const QString &, const QString &)), this, SIGNAL(contactChanged())); emit contactAdded(c, suppress); emit contactRemoved(old, QString::null); } else { d->mContactList.append(c); emit contactAdded(c, suppress); } //c->setConversations( c->conversations() + 1 ); //connect (c, SIGNAL(displayNameChanged(const QString &,const QString &)), this, SIGNAL(contactChanged())); connect (c, SIGNAL(onlineStatusChanged( KopeteContact*, const KopeteOnlineStatus&, const KopeteOnlineStatus&)), this, SIGNAL(contactChanged())); if(c->metaContact()) connect (c->metaContact(), SIGNAL(displayNameChanged(const QString &, const QString &)), this, SIGNAL(contactChanged())); connect (c, SIGNAL(contactDestroyed(KopeteContact*)) , this , SLOT(slotContactDestroyed(KopeteContact*))); } d->isEmpty=false; slotUpdateDisplayName(); } void KopeteMessageManager::removeContact( const KopeteContact *c, const QString& raison ) { if(!c || !d->mContactList.contains(c)) return; if(d->mContactList.count()==1) { kdDebug(14010) << k_funcinfo << "Contact not removed. Keep always one contact" <<endl; d->isEmpty=true; } else { d->mContactList.remove( c ); //disconnect (c, SIGNAL(displayNameChanged(const QString &, const QString &)), this, SIGNAL(contactChanged())); disconnect (c, SIGNAL(onlineStatusChanged( KopeteContact*, const KopeteOnlineStatus&, const KopeteOnlineStatus&)), this, SIGNAL(contactChanged())); if(c->metaContact()) disconnect (c->metaContact(), SIGNAL(displayNameChanged(const QString &, const QString &)), this, SIGNAL(contactChanged())); disconnect (c, SIGNAL(contactDestroyed(KopeteContact*)) , this , SLOT(slotContactDestroyed(KopeteContact*))); //c->setConversations( c->conversations() - 1 ); } emit contactRemoved(c, raison); slotUpdateDisplayName(); } void KopeteMessageManager::receivedTypingMsg( const KopeteContact *c , bool t ) { emit(remoteTyping( c, t )); } void KopeteMessageManager::receivedTypingMsg( const QString &contactId , bool t ) { for( KopeteContact *it = d->mContactList.first(); it; it = d->mContactList.next() ) { if( it->contactId() == contactId ) { receivedTypingMsg( it, t ); return; } } } void KopeteMessageManager::typing ( bool t ) { emit typingMsg(t); } void KopeteMessageManager::setCanBeDeleted ( bool b ) { d->mCanBeDeleted = b; if(b && !d->view) deleteLater(); } KopeteView* KopeteMessageManager::view(bool canCreate , KopeteMessage::MessageType type ) { if(!d->view && canCreate) { d->view=KopeteMessageManagerFactory::factory()->createView( this , type ); if(d->view) connect( d->view->mainWidget(), SIGNAL( closing( KopeteView * ) ), this, SLOT( slotViewDestroyed( ) ) ); else KMessageBox::error( 0L, i18n( "<qt>An error has occurred when creating a new chat window. The chat window has not been created.</qt>" ), i18n( "Error while creating the chat window - Kopete" ) ); } return d->view; } void KopeteMessageManager::slotViewDestroyed() { d->view=0L; if(d->mCanBeDeleted) deleteLater(); } KopeteAccount *KopeteMessageManager::account() const { return user()->account(); } void KopeteMessageManager::slotContactDestroyed( KopeteContact *contact ) { if( !contact || !d->mContactList.contains( contact ) ) return; d->mContactList.remove( contact ); emit contactRemoved( contact, QString::null ); if ( d->mContactList.isEmpty() ) deleteLater(); } #include "kopetemessagemanager.moc" // vim: set noet ts=4 sts=4 sw=4: <commit_msg>show the IRC topic as well in the chatwindow caption.<commit_after>/* kopetemessagemanager.cpp - Manages all chats Copyright (c) 2002 by Duncan Mac-Vicar Prett <[email protected]> Copyright (c) 2002 by Daniel Stone <[email protected]> Copyright (c) 2002 by Martijn Klingens <[email protected]> Copyright (c) 2002-2003 by Olivier Goffart <[email protected]> Copyright (c) 2003 by Jason Keirstead <[email protected]> Kopete (c) 2002-2003 by the Kopete developers <[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 of the License, or (at your option) any later version. * * * ************************************************************************* */ #include <kdebug.h> #include <klocale.h> #include <kopetenotifyclient.h> #include <qapplication.h> #include <kglobal.h> #include <qregexp.h> #include <kmessagebox.h> #include "kopeteaccount.h" #include "kopetemessagemanager.h" #include "kopetemessagemanagerfactory.h" #include "kopeteprefs.h" #include "kopetemetacontact.h" #include "kopetecommandhandler.h" #include "kopeteview.h" struct KMMPrivate { KopeteContactPtrList mContactList; const KopeteContact *mUser; QMap<const KopeteContact *, KopeteOnlineStatus> contactStatus; KopeteProtocol *mProtocol; int mId; bool isEmpty; bool mCanBeDeleted; QDateTime awayTime; QString displayName; KopeteView *view; }; KopeteMessageManager::KopeteMessageManager( const KopeteContact *user, KopeteContactPtrList others, KopeteProtocol *protocol, int id, const char *name ) : QObject( user->account(), name ) { d = new KMMPrivate; d->mUser = user; d->mProtocol = protocol; d->mId = id; d->isEmpty= others.isEmpty(); d->mCanBeDeleted = true; d->view=0L; for( KopeteContact *c = others.first(); c; c = others.next() ) { addContact(c,true); } connect( user, SIGNAL( onlineStatusChanged( KopeteContact *, const KopeteOnlineStatus &, const KopeteOnlineStatus & ) ), this, SLOT( slotStatusChanged( KopeteContact *, const KopeteOnlineStatus &, const KopeteOnlineStatus & ) ) ); connect( this, SIGNAL( contactChanged() ), this, SLOT( slotUpdateDisplayName() ) ); slotUpdateDisplayName(); } KopeteMessageManager::~KopeteMessageManager() { /* for( KopeteContact *c = d->mContactList.first(); c; c = d->mContactList.next() ) c->setConversations( c->conversations() - 1 );*/ if (!d) return; d->mCanBeDeleted = false; //prevent double deletion KopeteMessageManagerFactory::factory()->removeSession( this ); emit(closing( this ) ); delete d; } void KopeteMessageManager::slotStatusChanged( KopeteContact *c, const KopeteOnlineStatus &status, const KopeteOnlineStatus &oldStatus ) { if(!KopetePrefs::prefs()->notifyAway()) return; if( status.status() == KopeteOnlineStatus::Away ) { d->awayTime = QDateTime::currentDateTime(); KopeteMessage msg(c, d->mContactList, i18n("%1 has been marked as away.") .arg( QString::fromLatin1("/me") ), KopeteMessage::Outbound, KopeteMessage::PlainText); sendMessage( msg ); } else if( oldStatus.status() == KopeteOnlineStatus::Away && status.status() == KopeteOnlineStatus::Online ) { KopeteMessage msg(c, d->mContactList, i18n("%1 is no longer marked as away. Gone since %1") .arg( QString::fromLatin1("/me") ).arg(KGlobal::locale()->formatDateTime(d->awayTime, true)), KopeteMessage::Outbound, KopeteMessage::PlainText); sendMessage( msg ); } } void KopeteMessageManager::setContactOnlineStatus( const KopeteContact *contact, const KopeteOnlineStatus &status ) { d->contactStatus[ contact ] = status; } const KopeteOnlineStatus KopeteMessageManager::contactOnlineStatus( const KopeteContact *contact ) const { if( d->contactStatus.contains( contact ) ) return d->contactStatus[ contact ]; return contact->onlineStatus(); } const QString KopeteMessageManager::displayName() { if( d->displayName.isNull() ) { connect( this, SIGNAL( contactChanged() ), this, SLOT( slotUpdateDisplayName() ) ); slotUpdateDisplayName(); } return d->displayName; } void KopeteMessageManager::setDisplayName( const QString &newName ) { disconnect( this, SIGNAL( contactChanged() ), this, SLOT( slotUpdateDisplayName() ) ); d->displayName = newName; emit( displayNameChanged() ); } void KopeteMessageManager::slotUpdateDisplayName() { QString nextDisplayName; KopeteContact *c = d->mContactList.first(); if( c->metaContact() ) d->displayName = c->metaContact()->displayName(); else d->displayName = c->displayName(); //If we have only 1 contact, add the status of him if( d->mContactList.count() == 1 ) { d->displayName.append( QString::fromLatin1( " (%1)").arg( c->onlineStatus().description() ) ); } else { while( ( c = d->mContactList.next() ) ) { if( c->metaContact() ) nextDisplayName = c->metaContact()->displayName(); else nextDisplayName = c->displayName(); d->displayName.append( QString::fromLatin1( ", " ) ).append( nextDisplayName ); } } emit( displayNameChanged() ); } const KopeteContactPtrList& KopeteMessageManager::members() const { return d->mContactList; } const KopeteContact* KopeteMessageManager::user() const { return d->mUser; } KopeteProtocol* KopeteMessageManager::protocol() const { return d->mProtocol; } int KopeteMessageManager::mmId() const { return d->mId; } void KopeteMessageManager::setMMId( int id ) { d->mId = id; } void KopeteMessageManager::sendMessage(KopeteMessage &message) { message.setManager(this); KopeteMessage sentMessage = message; if( !KopeteCommandHandler::commandHandler()->processMessage( message, this ) ) { emit messageSent(sentMessage, this); if ( !account()->isAway() || KopetePrefs::prefs()->soundIfAway() ) KNotifyClient::event( 0 , QString::fromLatin1( "kopete_outgoing" ), i18n( "Outgoing Message Sent" ) ); } else emit( messageSuccess() ); } void KopeteMessageManager::messageSucceeded() { emit( messageSuccess() ); } void KopeteMessageManager::appendMessage( KopeteMessage &msg ) { msg.setManager(this); if( msg.direction() == KopeteMessage::Inbound ) { if( KopetePrefs::prefs()->highlightEnabled() && !user()->displayName().isEmpty() && msg.plainBody().contains( QRegExp(QString::fromLatin1("\\b(%1)\\b").arg(user()->displayName()),false) ) ) msg.setImportance( KopeteMessage::Highlight ); emit( messageReceived( msg, this ) ); } emit messageAppended( msg, this ); } void KopeteMessageManager::addContact( const KopeteContact *c, bool suppress ) { if ( d->mContactList.contains(c) ) { kdDebug(14010) << k_funcinfo << "Contact already exists" <<endl; emit contactAdded(c, suppress); } else { if(d->mContactList.count()==1 && d->isEmpty) { KopeteContact *old=d->mContactList.first(); d->mContactList.remove(old); d->mContactList.append(c); //disconnect (old, SIGNAL(displayNameChanged(const QString &, const QString &)), this, SIGNAL(contactChanged())); disconnect (old, SIGNAL(onlineStatusChanged( KopeteContact*, const KopeteOnlineStatus&, const KopeteOnlineStatus&)), this, SIGNAL(contactChanged())); if(old->metaContact()) disconnect (old->metaContact(), SIGNAL(displayNameChanged(const QString &, const QString &)), this, SIGNAL(contactChanged())); emit contactAdded(c, suppress); emit contactRemoved(old, QString::null); } else { d->mContactList.append(c); emit contactAdded(c, suppress); } //c->setConversations( c->conversations() + 1 ); //connect (c, SIGNAL(displayNameChanged(const QString &,const QString &)), this, SIGNAL(contactChanged())); connect (c, SIGNAL(onlineStatusChanged( KopeteContact*, const KopeteOnlineStatus&, const KopeteOnlineStatus&)), this, SIGNAL(contactChanged())); if(c->metaContact()) connect (c->metaContact(), SIGNAL(displayNameChanged(const QString &, const QString &)), this, SIGNAL(contactChanged())); connect (c, SIGNAL(contactDestroyed(KopeteContact*)) , this , SLOT(slotContactDestroyed(KopeteContact*))); } d->isEmpty=false; emit contactChanged(); } void KopeteMessageManager::removeContact( const KopeteContact *c, const QString& raison ) { if(!c || !d->mContactList.contains(c)) return; if(d->mContactList.count()==1) { kdDebug(14010) << k_funcinfo << "Contact not removed. Keep always one contact" <<endl; d->isEmpty=true; } else { d->mContactList.remove( c ); //disconnect (c, SIGNAL(displayNameChanged(const QString &, const QString &)), this, SIGNAL(contactChanged())); disconnect (c, SIGNAL(onlineStatusChanged( KopeteContact*, const KopeteOnlineStatus&, const KopeteOnlineStatus&)), this, SIGNAL(contactChanged())); if(c->metaContact()) disconnect (c->metaContact(), SIGNAL(displayNameChanged(const QString &, const QString &)), this, SIGNAL(contactChanged())); disconnect (c, SIGNAL(contactDestroyed(KopeteContact*)) , this , SLOT(slotContactDestroyed(KopeteContact*))); //c->setConversations( c->conversations() - 1 ); } emit contactRemoved(c, raison); emit contactChanged(); } void KopeteMessageManager::receivedTypingMsg( const KopeteContact *c , bool t ) { emit(remoteTyping( c, t )); } void KopeteMessageManager::receivedTypingMsg( const QString &contactId , bool t ) { for( KopeteContact *it = d->mContactList.first(); it; it = d->mContactList.next() ) { if( it->contactId() == contactId ) { receivedTypingMsg( it, t ); return; } } } void KopeteMessageManager::typing ( bool t ) { emit typingMsg(t); } void KopeteMessageManager::setCanBeDeleted ( bool b ) { d->mCanBeDeleted = b; if(b && !d->view) deleteLater(); } KopeteView* KopeteMessageManager::view(bool canCreate , KopeteMessage::MessageType type ) { if(!d->view && canCreate) { d->view=KopeteMessageManagerFactory::factory()->createView( this , type ); if(d->view) connect( d->view->mainWidget(), SIGNAL( closing( KopeteView * ) ), this, SLOT( slotViewDestroyed( ) ) ); else KMessageBox::error( 0L, i18n( "<qt>An error has occurred when creating a new chat window. The chat window has not been created.</qt>" ), i18n( "Error while creating the chat window - Kopete" ) ); } return d->view; } void KopeteMessageManager::slotViewDestroyed() { d->view=0L; if(d->mCanBeDeleted) deleteLater(); } KopeteAccount *KopeteMessageManager::account() const { return user()->account(); } void KopeteMessageManager::slotContactDestroyed( KopeteContact *contact ) { if( !contact || !d->mContactList.contains( contact ) ) return; d->mContactList.remove( contact ); emit contactRemoved( contact, QString::null ); if ( d->mContactList.isEmpty() ) deleteLater(); } #include "kopetemessagemanager.moc" // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>#include "Game.h" #include "util/Sysout.h" #include "util/Sysin.h" #include "util/SentenceStateBuilder.h" #include "command/CmdDictionary.h" #include "language/Grammar.h" #include "world/World.h" #include "world/Player.h" Game::Game() : running(false) { } void Game::run() { // We are running now running = true; // Last input vector std::vector<std::string>* lastInput = new std::vector<std::string>(); // world = new World(); // player = new Player(world->getRoom(Point3i(5, 5, 5))); // While running, run! while(running) { // Prompt Sysout::print("FCM:\\>"); Sysin::getWordsLowercase(lastInput); Sysout::println(); // Run command from the raw input runCommandFromRawInput(lastInput); } // Delete our storage for the last container delete lastInput; // Maybe now would be a good time to save? delete world; } bool Game::runCommandFromSudoInput(std::string sudoLine) { std::vector<std::string>* inputWords = new std::vector<std::string>(); Sysin::splitWords(sudoLine, inputWords); bool success = runCommandFromRawInput(inputWords); delete inputWords; return success; } bool Game::runCommandFromRawInput(std::vector<std::string>* inputWords) { // If we have no words if(inputWords->size() == 0) { // [Then obviously it cannot match anything] // Return unsuccessful return false; } // Loop through all commands for(unsigned int testCommandId = 0; testCommandId < CmdDictionary::cmdByAlias->size(); ++ testCommandId) { // Split the command's alias into a vector of individual words std::vector<std::string>* commandWords = new std::vector<std::string>(); Sysin::splitWords(CmdDictionary::cmdByAlias->at(testCommandId).first, commandWords); // Check if we have enough input for it to be possible if(inputWords->size() < commandWords->size()) { // [It cannot be this command] // Skip this one continue; } // Keeps track if the command comparison proves the input to start with the needed command bool commandMatches = true; // Get iterator for command words std::vector<std::string>::iterator commandWordFocus = commandWords->begin(); // Iterate through the input words parallel std::vector<std::string>::iterator inputWordFocus = inputWords->begin(); // Iterate through the command words while(commandWordFocus != commandWords->end()) { // Check if this word is different if(*commandWordFocus != *inputWordFocus) { // [It is not] // The command therefore does not match commandMatches = false; // Stop checking, because it cannot possibly be it anymore break; } // Next ++ commandWordFocus; ++ inputWordFocus; } // If the command matches if(commandMatches) { // Get the command arguments std::vector<std::string>* argumentWords = new std::vector<std::string>(*inputWords); argumentWords->erase(argumentWords->begin(), argumentWords->begin() + commandWords->size()); // Process them gmr::SentenceState* stncState = SentenceStateBuilder::processStatement(argumentWords); // Print debug stuff #ifdef DEBUG Sysout::print("Syntax: "); Sysout::println(Sysout::toFriendlyString(stncState)); #endif // Run the command [-----------Function Pointer----------------------][-----------------------Function Parameters----------------------------------] bool commandSuccessful = CmdDictionary::cmdByAlias->at(testCommandId).second(stncState, argumentWords, CmdDictionary::cmdByAlias->at(testCommandId).first); // Delete them, since they are no longer needed. delete argumentWords; delete stncState; // If it was successful if(commandSuccessful) { // Return successful return true; } // [The command was not successful] } // [The command did not match] // Delete our command word interpreter. delete commandWords; } // [None of the commands matched] // Inform #ifdef DEBUG Sysout::print("Could not understand input: "); Sysout::println(Sysout::toFriendlyString(inputWords)); #endif Sysout::println("Misunderstanding."); Sysout::println(); // Return unsuccessful return false; } <commit_msg>Output misunderstanding message change<commit_after>#include "Game.h" #include "util/Sysout.h" #include "util/Sysin.h" #include "util/SentenceStateBuilder.h" #include "command/CmdDictionary.h" #include "language/Grammar.h" #include "world/World.h" #include "world/Player.h" Game::Game() : running(false) { } void Game::run() { // We are running now running = true; // Last input vector std::vector<std::string>* lastInput = new std::vector<std::string>(); // world = new World(); // player = new Player(world->getRoom(Point3i(5, 5, 5))); // While running, run! while(running) { // Prompt Sysout::print("FCM:\\>"); Sysin::getWordsLowercase(lastInput); Sysout::println(); // Run command from the raw input bool success = runCommandFromRawInput(lastInput); if(!success) { // Inform #ifdef DEBUG Sysout::print("Could not understand input: "); Sysout::println(Sysout::toFriendlyString(lastInput)); #endif Sysout::println("Misunderstanding."); Sysout::println(); } } // Delete our storage for the last container delete lastInput; // Maybe now would be a good time to save? delete world; } bool Game::runCommandFromSudoInput(std::string sudoLine) { std::vector<std::string>* inputWords = new std::vector<std::string>(); Sysin::splitWords(sudoLine, inputWords); bool success = runCommandFromRawInput(inputWords); delete inputWords; return success; } bool Game::runCommandFromRawInput(std::vector<std::string>* inputWords) { #ifdef DEBUG Sysout::println("-BEGIN INPUT PROCESSING"); Sysout::print("-Processing: "); Sysout::println(Sysout::toFriendlyString(inputWords)); #endif // DEBUG // If we have no words if(inputWords->size() == 0) { // [Then obviously it cannot match anything] // Return unsuccessful return false; } // Loop through all commands for(unsigned int testCommandId = 0; testCommandId < CmdDictionary::cmdByAlias->size(); ++ testCommandId) { // Split the command's alias into a vector of individual words std::vector<std::string>* commandWords = new std::vector<std::string>(); Sysin::splitWords(CmdDictionary::cmdByAlias->at(testCommandId).first, commandWords); // Check if we have enough input for it to be possible if(inputWords->size() < commandWords->size()) { // [It cannot be this command] // Skip this one continue; } // Keeps track if the command comparison proves the input to start with the needed command bool commandMatches = true; // Get iterator for command words std::vector<std::string>::iterator commandWordFocus = commandWords->begin(); // Iterate through the input words parallel std::vector<std::string>::iterator inputWordFocus = inputWords->begin(); // Iterate through the command words while(commandWordFocus != commandWords->end()) { // Check if this word is different if(*commandWordFocus != *inputWordFocus) { // [It is not] // The command therefore does not match commandMatches = false; // Stop checking, because it cannot possibly be it anymore break; } // Next ++ commandWordFocus; ++ inputWordFocus; } // If the command matches if(commandMatches) { // Debug #ifdef DEBUG Sysout::println("--BEGIN COMMAND PROCESSING"); Sysout::print("--Command: "); Sysout::println(CmdDictionary::cmdByAlias->at(testCommandId).first); #endif // DEBUG // Get the command arguments std::vector<std::string>* argumentWords = new std::vector<std::string>(*inputWords); argumentWords->erase(argumentWords->begin(), argumentWords->begin() + commandWords->size()); // Process them gmr::SentenceState* stncState = SentenceStateBuilder::processStatement(argumentWords); // Print debug stuff #ifdef DEBUG Sysout::print("--Syntax: "); Sysout::println(Sysout::toFriendlyString(stncState)); #endif // Run the command [-----------Function Pointer----------------------][-----------------------Function Parameters----------------------------------] bool commandSuccessful = CmdDictionary::cmdByAlias->at(testCommandId).second(stncState, argumentWords, CmdDictionary::cmdByAlias->at(testCommandId).first); // Delete them, since they are no longer needed. delete argumentWords; delete stncState; // If it was successful if(commandSuccessful) { // Debug #ifdef DEBUG Sysout::println("--Command successful."); Sysout::println("--END COMMAND PROCESSING"); Sysout::println("-END INPUT PROCESSING"); #endif // DEBUG // Return successful return true; } // [The command was not successful] // Debug #ifdef DEBUG Sysout::println("--Command failed."); Sysout::println("--END COMMAND PROCESSING"); #endif // DEBUG } // [The command did not match] // Delete our command word interpreter. delete commandWords; } // [None of the commands matched] // Debug #ifdef DEBUG Sysout::println("-END INPUT PROCESSING"); #endif // DEBUG // Return unsuccessful return false; } <|endoftext|>
<commit_before>#include "Game.h" #include "InputHandler.h" #include "MenuState.h" #include "NoJoystickState.h" #include "PlayState.h" #include <iostream> #include <errno.h> static Game* s_pInstance; Game::Game() { m_pWindow = 0; m_pRenderer = 0; } Game::~Game() { InputHandler::Instance()->clean(); InputHandler::free(); TextureManager::free(); _cleanGameMachine(); SDL_DestroyWindow(m_pWindow); SDL_DestroyRenderer(m_pRenderer); // clean up SDL SDL_Quit(); } Game *Game::Instance() { if (s_pInstance == 0) { s_pInstance = new Game(); } return s_pInstance; } void Game::free() { delete s_pInstance; s_pInstance = 0; } bool Game::_initSDL( const char* title, const int x, const int y, const int w, const int h, const bool fullScreen ) { bool l_bReturn = true; int flags = 0; if (fullScreen) { flags |= SDL_WINDOW_FULLSCREEN; } // initialize SDL if (SDL_Init(SDL_INIT_EVERYTHING) < 0) { std::cout << "SDL Init failed\n"; l_bReturn = false; } else { // if succeeded create our window m_pWindow = SDL_CreateWindow(title, x, y, w, h, flags); // if the window creation succeeded create our renderer if (m_pWindow == 0) { std::cout << "Window creation failed\n"; l_bReturn = false; } else { m_pRenderer = SDL_CreateRenderer(m_pWindow, -1, 0); if (m_pRenderer == 0) { std::cout << "Renderer creation failed\n"; l_bReturn = false; } } } return l_bReturn; } bool Game::_loadResources() { const char* fileName = "resources/char9.bmp"; const char* errorPattern = "An error occured while loading the file %s\n%s\n"; char errorMessage[strlen(fileName) + strlen(errorPattern) - 2]; bool textureLoaded = m_textureManager->load( fileName, "animate", m_pRenderer ); if (!textureLoaded) { sprintf(errorMessage, errorPattern, fileName, strerror(errno)); std::cout << errorMessage; return false; } return true; } void Game::_initGameMachine() { m_pGameStateMachine = new GameStateMachine(); GameState* initialState; if (!InputHandler::Instance()->joysticksInitialised()) { initialState = new NoJoystickState(); } else { initialState = new MenuState(); } m_pGameStateMachine->changeState(initialState); } void Game::_cleanGameMachine() { m_pGameStateMachine->clean(); delete m_pGameStateMachine; m_pGameStateMachine = NULL; } bool Game::init( const char* title, const int x, const int y, const int w, const int h, const bool fullScreen ) { bool l_bReturn = true; m_textureManager = TextureManager::Instance(); l_bReturn &= _initSDL(title, x, y, w, h, fullScreen); l_bReturn &= _loadResources(); m_bRunning = l_bReturn; if (l_bReturn) { InputHandler::Instance()->initialiseJoysticks(); _initGameMachine(); } return l_bReturn; } void Game::handleEvents() { bool keepRunning = InputHandler::Instance()->update(); if (!keepRunning) { m_bRunning = false; } else { if (InputHandler::Instance()->getButtonState(0, 0)) { m_pGameStateMachine->changeState(new PlayState()); } } } void Game::update() { m_pGameStateMachine->update(); } void Game::render() { // set to black // This function expects Red, Green, Blue and // Alpha as color values SDL_SetRenderDrawColor(m_pRenderer, 0, 0, 0, 255); // clear the window to black SDL_RenderClear(m_pRenderer); m_pGameStateMachine->render(); // show the window SDL_RenderPresent(m_pRenderer); } bool Game::isRunning() { return m_bRunning; } SDL_Renderer* Game::getRenderer() { return m_pRenderer; } <commit_msg>Methods moved around<commit_after>#include "Game.h" #include "InputHandler.h" #include "MenuState.h" #include "NoJoystickState.h" #include "PlayState.h" #include <iostream> #include <errno.h> static Game* s_pInstance; Game::Game() { m_pWindow = 0; m_pRenderer = 0; } Game::~Game() { InputHandler::Instance()->clean(); InputHandler::free(); TextureManager::free(); _cleanGameMachine(); SDL_DestroyWindow(m_pWindow); SDL_DestroyRenderer(m_pRenderer); // clean up SDL SDL_Quit(); } Game *Game::Instance() { if (s_pInstance == 0) { s_pInstance = new Game(); } return s_pInstance; } void Game::free() { delete s_pInstance; s_pInstance = 0; } bool Game::init( const char* title, const int x, const int y, const int w, const int h, const bool fullScreen ) { bool l_bReturn = true; m_textureManager = TextureManager::Instance(); l_bReturn &= _initSDL(title, x, y, w, h, fullScreen); l_bReturn &= _loadResources(); m_bRunning = l_bReturn; if (l_bReturn) { InputHandler::Instance()->initialiseJoysticks(); _initGameMachine(); } return l_bReturn; } bool Game::_initSDL( const char* title, const int x, const int y, const int w, const int h, const bool fullScreen ) { bool l_bReturn = true; int flags = 0; if (fullScreen) { flags |= SDL_WINDOW_FULLSCREEN; } // initialize SDL if (SDL_Init(SDL_INIT_EVERYTHING) < 0) { std::cout << "SDL Init failed\n"; l_bReturn = false; } else { // if succeeded create our window m_pWindow = SDL_CreateWindow(title, x, y, w, h, flags); // if the window creation succeeded create our renderer if (m_pWindow == 0) { std::cout << "Window creation failed\n"; l_bReturn = false; } else { m_pRenderer = SDL_CreateRenderer(m_pWindow, -1, 0); if (m_pRenderer == 0) { std::cout << "Renderer creation failed\n"; l_bReturn = false; } } } return l_bReturn; } bool Game::_loadResources() { const char* fileName = "resources/char9.bmp"; const char* errorPattern = "An error occured while loading the file %s\n%s\n"; char errorMessage[strlen(fileName) + strlen(errorPattern) - 2]; bool textureLoaded = m_textureManager->load( fileName, "animate", m_pRenderer ); if (!textureLoaded) { sprintf(errorMessage, errorPattern, fileName, strerror(errno)); std::cout << errorMessage; return false; } return true; } void Game::_initGameMachine() { m_pGameStateMachine = new GameStateMachine(); GameState* initialState; if (!InputHandler::Instance()->joysticksInitialised()) { initialState = new NoJoystickState(); } else { initialState = new MenuState(); } m_pGameStateMachine->changeState(initialState); } void Game::handleEvents() { bool keepRunning = InputHandler::Instance()->update(); if (!keepRunning) { m_bRunning = false; } else { if (InputHandler::Instance()->getButtonState(0, 0)) { m_pGameStateMachine->changeState(new PlayState()); } } } void Game::update() { m_pGameStateMachine->update(); } void Game::render() { // set to black // This function expects Red, Green, Blue and // Alpha as color values SDL_SetRenderDrawColor(m_pRenderer, 0, 0, 0, 255); // clear the window to black SDL_RenderClear(m_pRenderer); m_pGameStateMachine->render(); // show the window SDL_RenderPresent(m_pRenderer); } void Game::_cleanGameMachine() { m_pGameStateMachine->clean(); delete m_pGameStateMachine; m_pGameStateMachine = NULL; } bool Game::isRunning() { return m_bRunning; } SDL_Renderer* Game::getRenderer() { return m_pRenderer; } <|endoftext|>
<commit_before>#include <iostream> #include "Emulator.h" #include "Debugger.h" enum MainFlags : uint8_t { F_DEFAULT = 1, F_ROMINFO = 1 << 1, F_DEBUG = 1 << 2, F_NOSTART = 1 << 3 }; int main(int argc, char **argv) { std::cout << "mfemu v." << VERSION << " rev." << COMMIT << std::endl << std::endl; std::string romFile("test.gb"); uint8_t flags = F_DEFAULT; for (int i = 1; i < argc; i += 1) { if (argv[i][0] == '-') { switch (argv[i][1]) { case 'v': return 0; // we already printed the version case 'i': // only print ROM information and exit flags = F_ROMINFO; break; case 'd': flags |= F_DEBUG; break; case 'n': flags |= F_NOSTART; break; default: std::cout << "Usage: " << argv[0] << " [-hvidn] <file.gb>\r\n" << "\t-h: get this help\r\n" << "\t-v: print version and exit\r\n" << "\t-i: print ROM info and exit\r\n" << "\t-d: run the debugger on the given rom\r\n" << "\t-n: don't start the emulation right away" << std::endl; return 0; } } else { romFile = std::string(argv[i]); } } if (flags & F_ROMINFO) { ROM rom = ROM::FromFile(romFile); rom.debugPrintData(); return 0; } Emulator emulator(romFile); if (flags & F_DEBUG) { uint8_t debugger_flags = Debug::DBG_INTERACTIVE; if (flags & F_NOSTART) { debugger_flags |= Debug::DBG_NOSTART; } Debugger debugger(&emulator, debugger_flags); debugger.Run(); } else { // Create CPU and load ROM into it std::cout << "Starting emulation..." << std::endl; emulator.Run(); } return 0; } <commit_msg>allow passing multiple flags with a single dash<commit_after>#include <iostream> #include <cstring> #include "Emulator.h" #include "Debugger.h" enum MainFlags : uint8_t { F_DEFAULT = 1, F_ROMINFO = 1 << 1, F_DEBUG = 1 << 2, F_NOSTART = 1 << 3 }; int main(int argc, char **argv) { std::cout << "mfemu v." << VERSION << " rev." << COMMIT << std::endl << std::endl; std::string romFile("test.gb"); uint8_t flags = F_DEFAULT; for (uint16_t i = 1; i < argc; i += 1) { if (argv[i][0] == '-') { uint16_t j = 1, len = strlen(argv[i]); do { switch (argv[i][j]) { case 'v': return 0; // we already printed the version case 'i': // only print ROM information and exit flags = F_ROMINFO; break; case 'd': flags |= F_DEBUG; break; case 'n': flags |= F_NOSTART; break; default: std::cout << "Usage: " << argv[0] << " [-hvidn] <file.gb>\r\n" << "\t-h: get this help\r\n" << "\t-v: print version and exit\r\n" << "\t-i: print ROM info and exit\r\n" << "\t-d: run the debugger on the given rom\r\n" << "\t-n: don't start the emulation right away" << std::endl; return 0; } } while (++j < len); } else { romFile = std::string(argv[i]); } } if (flags & F_ROMINFO) { ROM rom = ROM::FromFile(romFile); rom.debugPrintData(); return 0; } Emulator emulator(romFile); if (flags & F_DEBUG) { uint8_t debugger_flags = Debug::DBG_INTERACTIVE; if (flags & F_NOSTART) { debugger_flags |= Debug::DBG_NOSTART; } Debugger debugger(&emulator, debugger_flags); debugger.Run(); } else { // Create CPU and load ROM into it std::cout << "Starting emulation..." << std::endl; emulator.Run(); } return 0; } <|endoftext|>
<commit_before>#include <cstdio> #include <SDL2/SDL.h> #include "draw.hpp" const char * game_name = "Game Of Life On Surface"; int screen_width = 640; int screen_height = 640; int R = 200; bool quit_flag = false; SDL_Window * window = NULL; SDL_Renderer * render = NULL; SDL_Event event; void game_send_error( int code ) { printf( "[error]: %s\n", SDL_GetError() ); exit( code ); } void game_event( SDL_Event * event ) { SDL_PollEvent( event ); switch ( event->type ) { case SDL_QUIT: quit_flag = true; break; case SDL_WINDOWEVENT: if ( event->window.event == SDL_WINDOWEVENT_RESIZED ) { screen_width = event->window.data1; screen_height = event->window.data2; } break; case SDL_KEYDOWN: switch ( event->key.keysym.sym ) { case SDLK_ESCAPE: quit_flag = true; break; default: break; } default: break; } } void game_loop( void ) { // insert code } void draw_point( int x, int y, int size ) { SDL_Rect rect = { x, y, size, size }; SDL_RenderFillRect( render, &rect ); } void game_render( void ) { SDL_RenderClear( render ); set_coloru( COLOR_WHITE ); // меридианы for ( float p = 0; p <= 0.5; p += 0.1 ) { draw_ellipse( screen_width / 2, screen_height / 2, R * cos( p * M_PI ), R ); } // широты for ( float p = 0; p < 1; p += 0.1 ) { draw_ellipse( screen_width / 2, screen_height / 2 + R * cos(p * M_PI), R * sin( p * M_PI ), 0 ); } set_coloru( COLOR_BLACK ); SDL_RenderPresent( render ); } void game_destroy( void ) { SDL_DestroyRenderer( render ); SDL_DestroyWindow( window ); SDL_Quit(); } void game_init( void ) { SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS ); window = SDL_CreateWindow( game_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screen_width, screen_height, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE ); if ( window == NULL ) { game_send_error( EXIT_FAILURE ); } render = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE ); if ( render == NULL ) { game_send_error( EXIT_FAILURE ); } SDL_SetRenderDrawBlendMode( render, SDL_BLENDMODE_BLEND ); draw_init( render ); } int main( int argc, char * argv[] ) { Uint32 FPS_MAX = 1000 / 63; // ~ 60 fps game_init(); while ( quit_flag == false ) { game_event( &event ); game_loop(); game_render(); SDL_Delay( FPS_MAX ); } game_destroy(); return EXIT_SUCCESS; } <commit_msg>[add] sphere segment<commit_after>#include <cstdio> #include <SDL2/SDL.h> #include "draw.hpp" const char * game_name = "Game Of Life On Surface"; const int segments = 16; int screen_width = 640; int screen_height = 640; int R = 200; bool quit_flag = false; SDL_Window * window = NULL; SDL_Renderer * render = NULL; SDL_Event event; void game_send_error( int code ) { printf( "[error]: %s\n", SDL_GetError() ); exit( code ); } void game_event( SDL_Event * event ) { SDL_PollEvent( event ); switch ( event->type ) { case SDL_QUIT: quit_flag = true; break; case SDL_WINDOWEVENT: if ( event->window.event == SDL_WINDOWEVENT_RESIZED ) { screen_width = event->window.data1; screen_height = event->window.data2; } break; case SDL_KEYDOWN: switch ( event->key.keysym.sym ) { case SDLK_ESCAPE: quit_flag = true; break; default: break; } default: break; } } void game_loop( void ) { // insert code } void draw_point( int x, int y, int size ) { SDL_Rect rect = { x, y, size, size }; SDL_RenderFillRect( render, &rect ); } void game_render( void ) { SDL_RenderClear( render ); set_coloru( COLOR_WHITE ); // меридианы for ( float p = 0; p <= 0.5; p += 0.5f / ( segments / 2 ) ) { draw_ellipse( screen_width / 2, screen_height / 2, R * cos( p * M_PI ), R ); } // широты for ( float p = 0; p < 1.0f; p += 1.0f / segments ) { draw_ellipse( screen_width / 2, screen_height / 2 + R * cos( p * M_PI ), R * sin( p * M_PI ), 0 ); } set_coloru( COLOR_BLACK ); SDL_RenderPresent( render ); } void game_destroy( void ) { SDL_DestroyRenderer( render ); SDL_DestroyWindow( window ); SDL_Quit(); } void game_init( void ) { SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS ); window = SDL_CreateWindow( game_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screen_width, screen_height, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE ); if ( window == NULL ) { game_send_error( EXIT_FAILURE ); } render = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE ); if ( render == NULL ) { game_send_error( EXIT_FAILURE ); } SDL_SetRenderDrawBlendMode( render, SDL_BLENDMODE_BLEND ); draw_init( render ); } int main( int argc, char * argv[] ) { Uint32 FPS_MAX = 1000 / 63; // ~ 60 fps game_init(); while ( quit_flag == false ) { game_event( &event ); game_loop(); game_render(); SDL_Delay( FPS_MAX ); } game_destroy(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Copyright 2014 Google Inc. 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 "listener_internal_state.h" #include "pindrop/pindrop.h" namespace pindrop { void Listener::Clear() { state_ = nullptr; } bool Listener::Valid() const { return state_ != nullptr && state_->InList(); } void Listener::SetOrientation(const mathfu::Vector<float, 3>& location, const mathfu::Vector<float, 3>& direction, const mathfu::Vector<float, 3>& up) { SetMatrix( mathfu::Matrix<float, 4>::LookAt(location + direction, location, up)); } mathfu::Vector<float, 3> Listener::Location() const { return state_->inverse_matrix().TranslationVector3D(); } void Listener::SetLocation(const mathfu::Vector<float, 3>& location) { SetMatrix(mathfu::Matrix<float, 4>::FromTranslationVector(-location)); } void Listener::SetMatrix(const mathfu::Matrix<float, 4>& matrix) { assert(Valid()); state_->set_inverse_matrix(matrix.Inverse()); } const mathfu::Matrix<float, 4> Listener::Matrix() const { return state_->inverse_matrix().Inverse(); } } // namespace pindrop <commit_msg>Fixed math error in listener positioning.<commit_after>// Copyright 2014 Google Inc. 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 "listener_internal_state.h" #include "pindrop/pindrop.h" namespace pindrop { void Listener::Clear() { state_ = nullptr; } bool Listener::Valid() const { return state_ != nullptr && state_->InList(); } void Listener::SetOrientation(const mathfu::Vector<float, 3>& location, const mathfu::Vector<float, 3>& direction, const mathfu::Vector<float, 3>& up) { assert(Valid()); state_->set_inverse_matrix( mathfu::Matrix<float, 4>::LookAt(location + direction, location, up)); } mathfu::Vector<float, 3> Listener::Location() const { return state_->inverse_matrix().TranslationVector3D(); } void Listener::SetLocation(const mathfu::Vector<float, 3>& location) { assert(Valid()); SetMatrix(mathfu::Matrix<float, 4>::FromTranslationVector(location)); } void Listener::SetMatrix(const mathfu::Matrix<float, 4>& matrix) { assert(Valid()); state_->set_inverse_matrix(matrix.Inverse()); } const mathfu::Matrix<float, 4> Listener::Matrix() const { return state_->inverse_matrix().Inverse(); } } // namespace pindrop <|endoftext|>
<commit_before>// Copyright (C) 2016 xaizek <[email protected]> // // This file is part of uncov. // // uncov 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 // (at your option) any later version. // // uncov 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 uncov. If not, see <http://www.gnu.org/licenses/>. #include "listings.hpp" #include <boost/filesystem/path.hpp> #include <boost/optional.hpp> #include <map> #include <ostream> #include <string> #include <vector> #include "utils/fs.hpp" #include "BuildHistory.hpp" #include "coverage.hpp" #include "printing.hpp" static std::map<std::string, CovInfo> getDirsCoverage(const Build &build, const std::string &dirFilter); static CovChange getBuildCovChange(BuildHistory *bh, const Build &build, const CovInfo &covInfo); static void printFileHeader(std::ostream &os, const std::string &filePath, const CovInfo &covInfo, const CovChange &covChange); static CovChange getFileCovChange(BuildHistory *bh, const Build &build, const std::string &path, boost::optional<Build> *prevBuildHint, const CovInfo &covInfo); std::vector<std::string> describeBuild(BuildHistory *bh, const Build &build) { CovInfo covInfo(build); CovChange covChange = getBuildCovChange(bh, build, covInfo); return { "#" + std::to_string(build.getId()), covInfo.formatCoverageRate(), covInfo.formatLines(" / "), covChange.formatCoverageRate(), covChange.formatLines(" / "), build.getRefName(), Revision{build.getRef()}, Time{build.getTimestamp()} }; } std::vector<std::vector<std::string>> describeBuildDirs(BuildHistory *bh, const Build &build, const std::string &dirFilter) { std::map<std::string, CovInfo> newDirs = getDirsCoverage(build, dirFilter); std::map<std::string, CovInfo> prevDirs; if (const int prevBuildId = bh->getPreviousBuildId(build.getId())) { prevDirs = getDirsCoverage(*bh->getBuild(prevBuildId), dirFilter); } std::vector<std::vector<std::string>> rows; rows.reserve(newDirs.size()); for (const auto &entry : newDirs) { const CovInfo &covInfo = entry.second; CovChange covChange(prevDirs[entry.first], covInfo); rows.push_back({ entry.first + '/', covInfo.formatCoverageRate(), covInfo.formatLines(" / "), covChange.formatCoverageRate(), covChange.formatLines(" / ") }); } return rows; } static std::map<std::string, CovInfo> getDirsCoverage(const Build &build, const std::string &dirFilter) { std::map<std::string, CovInfo> dirs; for (const std::string &filePath : build.getPaths()) { if (!pathIsInSubtree(dirFilter, filePath)) { continue; } boost::filesystem::path dirPath = filePath; dirPath.remove_filename(); File &file = *build.getFile(filePath); CovInfo &info = dirs[dirPath.string()]; info.add(CovInfo(file)); } return dirs; } std::vector<std::vector<std::string>> describeBuildFiles(BuildHistory *bh, const Build &build, const std::string &dirFilter) { const std::vector<std::string> &paths = build.getPaths(); std::vector<std::vector<std::string>> rows; rows.reserve(paths.size()); boost::optional<Build> prevBuild; if (const int prevBuildId = bh->getPreviousBuildId(build.getId())) { prevBuild = bh->getBuild(prevBuildId); } for (const std::string &filePath : paths) { if (!pathIsInSubtree(dirFilter, filePath)) { continue; } CovInfo covInfo(*build.getFile(filePath)); CovChange covChange = getFileCovChange(bh, build, filePath, &prevBuild, covInfo); rows.push_back({ filePath, covInfo.formatCoverageRate(), covInfo.formatLines(" / "), covChange.formatCoverageRate(), covChange.formatLines(" / "), }); } return rows; } void printBuildHeader(std::ostream &os, BuildHistory *bh, const Build &build) { CovInfo covInfo(build); CovChange covChange = getBuildCovChange(bh, build, covInfo); os << Label{"Build"} << ": #" << build.getId() << ", " << covInfo.formatCoverageRate() << ' ' << '(' << covInfo.formatLines("/") << "), " << covChange.formatCoverageRate() << ' ' << '(' << covChange.formatLines("/") << "), " << build.getRefName() << " at " << Revision{build.getRef()} << '\n'; } static CovChange getBuildCovChange(BuildHistory *bh, const Build &build, const CovInfo &covInfo) { CovInfo prevCovInfo; if (const int prevBuildId = bh->getPreviousBuildId(build.getId())) { prevCovInfo = CovInfo(*bh->getBuild(prevBuildId)); } return CovChange(prevCovInfo, covInfo); } void printFileHeader(std::ostream &os, BuildHistory *bh, const Build &build, const File &file) { CovInfo covInfo(file); CovChange covChange = getFileCovChange(bh, build, file.getPath(), nullptr, covInfo); printFileHeader(os, file.getPath(), covInfo, covChange); } void printFileHeader(std::ostream &os, BuildHistory *bh, const Build &build, const std::string &filePath) { CovInfo covInfo; CovChange covChange = getFileCovChange(bh, build, filePath, nullptr, covInfo); printFileHeader(os, filePath, covInfo, covChange); } static void printFileHeader(std::ostream &os, const std::string &filePath, const CovInfo &covInfo, const CovChange &covChange) { os << Label{"File"} << ": " << filePath << ", " << covInfo.formatCoverageRate() << ' ' << '(' << covInfo.formatLines("/") << "), " << covChange.formatCoverageRate() << ' ' << '(' << covChange.formatLines("/") << ")\n"; } static CovChange getFileCovChange(BuildHistory *bh, const Build &build, const std::string &path, boost::optional<Build> *prevBuildHint, const CovInfo &covInfo) { boost::optional<Build> prevBuild; if (prevBuildHint == nullptr) { if (const int prevBuildId = bh->getPreviousBuildId(build.getId())) { prevBuild = bh->getBuild(prevBuildId); } prevBuildHint = &prevBuild; } CovInfo prevCovInfo; if (*prevBuildHint) { boost::optional<File &> file = (*prevBuildHint)->getFile(path); if (file) { prevCovInfo = CovInfo(*file); } } return CovChange(prevCovInfo, covInfo); } <commit_msg>Fix printing header of file specified by path<commit_after>// Copyright (C) 2016 xaizek <[email protected]> // // This file is part of uncov. // // uncov 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 // (at your option) any later version. // // uncov 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 uncov. If not, see <http://www.gnu.org/licenses/>. #include "listings.hpp" #include <boost/filesystem/path.hpp> #include <boost/optional.hpp> #include <map> #include <ostream> #include <string> #include <vector> #include "utils/fs.hpp" #include "BuildHistory.hpp" #include "coverage.hpp" #include "printing.hpp" static std::map<std::string, CovInfo> getDirsCoverage(const Build &build, const std::string &dirFilter); static CovChange getBuildCovChange(BuildHistory *bh, const Build &build, const CovInfo &covInfo); static void printFileHeader(std::ostream &os, const std::string &filePath, const CovInfo &covInfo, const CovChange &covChange); static CovChange getFileCovChange(BuildHistory *bh, const Build &build, const std::string &path, boost::optional<Build> *prevBuildHint, const CovInfo &covInfo); std::vector<std::string> describeBuild(BuildHistory *bh, const Build &build) { CovInfo covInfo(build); CovChange covChange = getBuildCovChange(bh, build, covInfo); return { "#" + std::to_string(build.getId()), covInfo.formatCoverageRate(), covInfo.formatLines(" / "), covChange.formatCoverageRate(), covChange.formatLines(" / "), build.getRefName(), Revision{build.getRef()}, Time{build.getTimestamp()} }; } std::vector<std::vector<std::string>> describeBuildDirs(BuildHistory *bh, const Build &build, const std::string &dirFilter) { std::map<std::string, CovInfo> newDirs = getDirsCoverage(build, dirFilter); std::map<std::string, CovInfo> prevDirs; if (const int prevBuildId = bh->getPreviousBuildId(build.getId())) { prevDirs = getDirsCoverage(*bh->getBuild(prevBuildId), dirFilter); } std::vector<std::vector<std::string>> rows; rows.reserve(newDirs.size()); for (const auto &entry : newDirs) { const CovInfo &covInfo = entry.second; CovChange covChange(prevDirs[entry.first], covInfo); rows.push_back({ entry.first + '/', covInfo.formatCoverageRate(), covInfo.formatLines(" / "), covChange.formatCoverageRate(), covChange.formatLines(" / ") }); } return rows; } static std::map<std::string, CovInfo> getDirsCoverage(const Build &build, const std::string &dirFilter) { std::map<std::string, CovInfo> dirs; for (const std::string &filePath : build.getPaths()) { if (!pathIsInSubtree(dirFilter, filePath)) { continue; } boost::filesystem::path dirPath = filePath; dirPath.remove_filename(); File &file = *build.getFile(filePath); CovInfo &info = dirs[dirPath.string()]; info.add(CovInfo(file)); } return dirs; } std::vector<std::vector<std::string>> describeBuildFiles(BuildHistory *bh, const Build &build, const std::string &dirFilter) { const std::vector<std::string> &paths = build.getPaths(); std::vector<std::vector<std::string>> rows; rows.reserve(paths.size()); boost::optional<Build> prevBuild; if (const int prevBuildId = bh->getPreviousBuildId(build.getId())) { prevBuild = bh->getBuild(prevBuildId); } for (const std::string &filePath : paths) { if (!pathIsInSubtree(dirFilter, filePath)) { continue; } CovInfo covInfo(*build.getFile(filePath)); CovChange covChange = getFileCovChange(bh, build, filePath, &prevBuild, covInfo); rows.push_back({ filePath, covInfo.formatCoverageRate(), covInfo.formatLines(" / "), covChange.formatCoverageRate(), covChange.formatLines(" / "), }); } return rows; } void printBuildHeader(std::ostream &os, BuildHistory *bh, const Build &build) { CovInfo covInfo(build); CovChange covChange = getBuildCovChange(bh, build, covInfo); os << Label{"Build"} << ": #" << build.getId() << ", " << covInfo.formatCoverageRate() << ' ' << '(' << covInfo.formatLines("/") << "), " << covChange.formatCoverageRate() << ' ' << '(' << covChange.formatLines("/") << "), " << build.getRefName() << " at " << Revision{build.getRef()} << '\n'; } static CovChange getBuildCovChange(BuildHistory *bh, const Build &build, const CovInfo &covInfo) { CovInfo prevCovInfo; if (const int prevBuildId = bh->getPreviousBuildId(build.getId())) { prevCovInfo = CovInfo(*bh->getBuild(prevBuildId)); } return CovChange(prevCovInfo, covInfo); } void printFileHeader(std::ostream &os, BuildHistory *bh, const Build &build, const File &file) { CovInfo covInfo(file); CovChange covChange = getFileCovChange(bh, build, file.getPath(), nullptr, covInfo); printFileHeader(os, file.getPath(), covInfo, covChange); } void printFileHeader(std::ostream &os, BuildHistory *bh, const Build &build, const std::string &filePath) { CovInfo covInfo; if (boost::optional<File &> file = build.getFile(filePath)) { covInfo = CovInfo(*file); } CovChange covChange = getFileCovChange(bh, build, filePath, nullptr, covInfo); printFileHeader(os, filePath, covInfo, covChange); } static void printFileHeader(std::ostream &os, const std::string &filePath, const CovInfo &covInfo, const CovChange &covChange) { os << Label{"File"} << ": " << filePath << ", " << covInfo.formatCoverageRate() << ' ' << '(' << covInfo.formatLines("/") << "), " << covChange.formatCoverageRate() << ' ' << '(' << covChange.formatLines("/") << ")\n"; } static CovChange getFileCovChange(BuildHistory *bh, const Build &build, const std::string &path, boost::optional<Build> *prevBuildHint, const CovInfo &covInfo) { boost::optional<Build> prevBuild; if (prevBuildHint == nullptr) { if (const int prevBuildId = bh->getPreviousBuildId(build.getId())) { prevBuild = bh->getBuild(prevBuildId); } prevBuildHint = &prevBuild; } CovInfo prevCovInfo; if (*prevBuildHint) { if (boost::optional<File &> file = (*prevBuildHint)->getFile(path)) { prevCovInfo = CovInfo(*file); } } return CovChange(prevCovInfo, covInfo); } <|endoftext|>
<commit_before>/* * main.cpp * * Created on: Jul 13, 2014 * Author: Pimenta */ #include <cstdio> #include "metallicar.hpp" using namespace std; using namespace metallicar; class Space2D : public GameObjectComponent { private: string family() const { return "spatial"; } void init() { object->fields().write("x", 640.0f); object->fields().write("y", 360.0f); } void update() { } bool destroy() { return false; } }; class Renderer : public GameObjectComponent { public: Sprite spr; Renderer() : spr("asset/metallicar.png") { } private: string family() const { return "renderer"; } vector<string> depends() const { return {"spatial"}; } void init() { } void update() { GameRenderers::add(0.0, [this]() { //glRotatef(90.0f, 0.0f, 0.0f, 1.0f); spr.render(object->fields().read<float>("x"), object->fields().read<float>("y"), Corner::CENTER); }); } bool destroy() { return false; } }; int main(int argc, char* argv[]) { Game::init(WindowOptions("metallicar test", 1280, 720)); (new GameObjectScene())->addObjects({ new CompositeGameObject({new Space2D, new Renderer}) }); Game::run(); return 0; } <commit_msg>Fixing bug<commit_after>/* * main.cpp * * Created on: Jul 13, 2014 * Author: Pimenta */ #include <cstdio> #include "metallicar.hpp" using namespace std; using namespace metallicar; class Space2D : public GameObjectComponent { private: string family() const { return "spatial"; } void init() { object->fields().write("x", 640.0f); object->fields().write("y", 360.0f); } void update() { } bool destroy() { return false; } }; class Renderer : public GameObjectComponent { public: Sprite spr; Renderer() : spr("asset/metallicar.png") { } private: string family() const { return "renderer"; } vector<string> depends() const { return {"spatial"}; } void init() { } void update() { GameRenderers::add(0.0, [this]() { //glRotatef(90.0f, 0.0f, 0.0f, 1.0f); spr.render(object->fields().read<float>("x"), object->fields().read<float>("y"), Corner::CENTER); }); } bool destroy() { return false; } }; int main(int argc, char* argv[]) { Game::init(); (new GameObjectScene())->addObjects({ new CompositeGameObject({new Space2D, new Renderer}) }); Game::run(); return 0; } <|endoftext|>
<commit_before>#include "RTIMULib.h" #include <fstream> std::ostream &operator<<(std::ostream &stream, const RTVector3 &vector) { stream<<vector.x()<<" "<<vector.y()<<" "<<vector.z(); return stream; } int main(int argc, char **argv) { RTIMUSettings *settings = new RTIMUSettings("RTIMULib"); RTIMU *imu = RTIMU::createIMU(settings); imu->IMUInit(); imu->setSlerpPower(0.02); imu->setGyroEnable(true); imu->setAccelEnable(true); imu->setCompassEnable(true); int sampleCount = 0; int sampleRate = 0; uint64_t rateTimer; uint64_t displayTimer; uint64_t now; std::fstream fs; fs.open("output.m", std::fstream::out); fs << "[\n"; rateTimer = RTMath::currentUSecsSinceEpoch(); for (int i = 0; i < 1000; ++i) { usleep(imu->IMUGetPollInterval() * 1000); while(imu->IMURead()) { RTIMU_DATA imuData = imu->getIMUData(); fs << imuData.timestamp << " " << imuData.fusionPose << " " << imuData.accel<< "\n"; } } fs << "];"; fs.close(); } <commit_msg>Formatting + streams for blow.cpp<commit_after>#include "RTIMULib.h" #include <fstream> #include <iostream> std::ostream &operator<<(std::ostream &stream, const RTVector3 &vector) { stream<<vector.x()<<" "<<vector.y()<<" "<<vector.z(); return stream; } std::ostream &operator<<(std::ostream &stream, const RTQuaternion &q) { stream<<q.scalar()<<" "<<q.x()<<" "<<q.y()<<" "<<q.z(); return stream; } std::ostream &operator<<(std::ostream &stream, const RTIMU_DATA &data) { stream<<data.fusionQPose<< " " << data.accel; return stream; } int main(int argc, char **argv) { int sampleCount = 0; int sampleRate = 0; uint64_t rateTimer; uint64_t displayTimer; uint64_t now; RTIMUSettings *settings = new RTIMUSettings("RTIMULib"); RTIMU *imu = RTIMU::createIMU(settings); if ((imu == NULL) || (imu->IMUType() == RTIMU_TYPE_NULL)) { std::cerr<<"No IMU found\n"<<std::endl; exit(1); } imu->IMUInit(); imu->setSlerpPower(0.02); imu->setGyroEnable(true); imu->setAccelEnable(true); imu->setCompassEnable(true); std::fstream fs; fs.open("output.m", std::fstream::out); fs << "[\n"; rateTimer = RTMath::currentUSecsSinceEpoch(); for (int i = 0; i < 1000; ++i) { usleep(imu->IMUGetPollInterval() * 1000); while(imu->IMURead()) { RTIMU_DATA imuData = imu->getIMUData(); fs << imuData.timestamp << " " << imuData << std::endl; } } fs << "];"; fs.close(); delete imu; delete settings; } <|endoftext|>
<commit_before>#include <iostream> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include "Path.h" using namespace std; int main(int argc, char *argv[]) { sf::RenderWindow window( sf::VideoMode(800, 600), "SuperTeacher" ); cout << "SRC:" << _SRC_DIR << endl; sf::Font font; std::string test = get_file(FONT_INDIE_FLOWER); if(!font.loadFromFile(get_file(FONT_INDIE_FLOWER))){ cout << "FONT NOT FOUND" << endl; return -1; } sf::Music song; if(!song.openFromFile(get_file(SONG_1))){ return -1; } sf::Text text("Hello SuperTeacher", font, 50); text.move(25,25); sf::CircleShape shape(50); shape.setFillColor(sf::Color::Green); shape.move(25,200); cout << "SuperTeaching is starting..." << endl; song.play(); while(window.isOpen()){ sf::Event event; while(window.pollEvent(event)){ switch(event.type){ // Window manager request a close case sf::Event::Closed: window.close(); break; case sf::Event::KeyPressed: switch(event.key.code){ case sf::Keyboard::Right: shape.move(10,0); break; case sf::Keyboard::Left: shape.move(-10,0); break; default: break; } break; default: break; } } window.clear(sf::Color::Black); // Dessin window.draw(shape); window.draw(text); window.display(); } fprintf(stdout, "Window is closing\n"); return 0; } <commit_msg>Add more keys actions<commit_after>#include <iostream> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include "Path.h" using namespace std; int main(int argc, char *argv[]) { sf::RenderWindow window( sf::VideoMode(800, 600), "SuperTeacher" ); cout << "SRC:" << _SRC_DIR << endl; sf::Font font; std::string test = get_file(FONT_INDIE_FLOWER); if(!font.loadFromFile(get_file(FONT_INDIE_FLOWER))){ cout << "FONT NOT FOUND" << endl; return -1; } sf::Music song; if(!song.openFromFile(get_file(SONG_1))){ return -1; } sf::Text text("Hello SuperTeacher", font, 50); text.move(25,25); sf::CircleShape shape(50); shape.setFillColor(sf::Color::Green); shape.move(25,200); cout << "SuperTeaching is starting..." << endl; song.play(); while(window.isOpen()){ sf::Event event; while(window.pollEvent(event)){ switch(event.type){ // Window manager request a close case sf::Event::Closed: window.close(); break; case sf::Event::KeyPressed: switch(event.key.code){ case sf::Keyboard::Right: shape.move(10,0); break; case sf::Keyboard::Left: shape.move(-10,0); break; case sf::Keyboard::Up: shape.move(0, -10); break; case sf::Keyboard::Down: shape.move(0, 10); break; case sf::Keyboard::Escape: window.close(); break; default: break; } break; default: break; } } window.clear(sf::Color::Black); // Dessin window.draw(shape); window.draw(text); window.display(); } fprintf(stdout, "Window is closing\n"); return 0; } <|endoftext|>
<commit_before> /* * bltCoreInit.c -- * * This module initials the non-Tk command of the BLT toolkit, registering the * commands with the TCL interpreter. * * Copyright 1991-2004 George A Howlett. * * 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 "bltInt.h" #include "bltNsUtil.h" #include "bltArrayObj.h" #include "bltMath.h" #ifndef BLT_LIBRARY # ifdef WIN32 # define BLT_LIBRARY "c:/Program Files/Tcl/lib/blt"##BLT_VERSION # else # define BLT_LIBRARY "unknown" # endif #endif #if (_TCL_VERSION >= _VERSION(8,5,0)) #define TCL_VERSION_LOADED TCL_PATCH_LEVEL #else #define TCL_VERSION_LOADED TCL_VERSION #endif static double bltNaN; BLT_EXTERN Tcl_AppInitProc Blt_core_Init; BLT_EXTERN Tcl_AppInitProc Blt_core_SafeInit; static Tcl_MathProc MinMathProc, MaxMathProc; static char libPath[1024] = { BLT_LIBRARY }; /* * Script to set the BLT library path in the variable global "blt_library" * * Checks the usual locations for a file (bltGraph.pro) from the BLT library. * The places searched in order are * * $BLT_LIBRARY * $BLT_LIBRARY/blt2.4 * $BLT_LIBRARY/.. * $BLT_LIBRARY/../blt2.4 * $blt_libPath * $blt_libPath/blt2.4 * $blt_libPath/.. * $blt_libPath/../blt2.4 * $tcl_library * $tcl_library/blt2.4 * $tcl_library/.. * $tcl_library/../blt2.4 * $env(TCL_LIBRARY) * $env(TCL_LIBRARY)/blt2.4 * $env(TCL_LIBRARY)/.. * $env(TCL_LIBRARY)/../blt2.4 * * The TCL variable "blt_library" is set to the discovered path. If the file * wasn't found, no error is returned. The actual usage of $blt_library is * purposely deferred so that it can be set from within a script. */ /* FIXME: Change this to a namespace procedure in 3.0 */ static char initScript[] = {"\n\ global blt_library blt_libPath blt_version tcl_library env\n\ set blt_library {}\n\ set path {}\n\ foreach var { env(BLT_LIBRARY) blt_libPath tcl_library env(TCL_LIBRARY) } { \n\ if { ![info exists $var] } { \n\ continue \n\ } \n\ set path [set $var] \n\ if { [file readable [file join $path bltGraph.pro]] } { \n\ set blt_library $path\n\ break \n\ } \n\ set path [file join $path blt$blt_version ] \n\ if { [file readable [file join $path bltGraph.pro]] } { \n\ set blt_library $path\n\ break \n\ } \n\ set path [file dirname [set $var]] \n\ if { [file readable [file join $path bltGraph.pro]] } { \n\ set blt_library $path\n\ break \n\ } \n\ set path [file join $path blt$blt_version ] \n\ if { [file readable [file join $path bltGraph.pro]] } { \n\ set blt_library $path\n\ break \n\ } \n\ } \n\ if { $blt_library != \"\" } { \n\ global auto_path \n\ lappend auto_path $blt_library \n\ }\n\ unset var path\n\ \n" }; static Tcl_AppInitProc *cmdProcs[] = { Blt_VectorCmdInitProc, (Tcl_AppInitProc *) NULL }; double Blt_NaN(void) { return bltNaN; } static double MakeNaN(void) { union DoubleValue { unsigned int words[2]; double value; } result; #ifdef WORDS_BIGENDIAN result.words[0] = 0x7ff80000; result.words[1] = 0x00000000; #else result.words[0] = 0x00000000; result.words[1] = 0x7ff80000; #endif return result.value; } /* ARGSUSED */ static int MinMathProc( ClientData clientData, /* Not used. */ Tcl_Interp *interp, /* Not used. */ Tcl_Value *argsPtr, Tcl_Value *resultPtr) { Tcl_Value *op1Ptr, *op2Ptr; op1Ptr = argsPtr, op2Ptr = argsPtr + 1; if ((op1Ptr->type == TCL_INT) && (op2Ptr->type == TCL_INT)) { resultPtr->intValue = MIN(op1Ptr->intValue, op2Ptr->intValue); resultPtr->type = TCL_INT; } else { double a, b; a = (op1Ptr->type == TCL_INT) ? (double)op1Ptr->intValue : op1Ptr->doubleValue; b = (op2Ptr->type == TCL_INT) ? (double)op2Ptr->intValue : op2Ptr->doubleValue; resultPtr->doubleValue = MIN(a, b); resultPtr->type = TCL_DOUBLE; } return TCL_OK; } /*ARGSUSED*/ static int MaxMathProc( ClientData clientData, /* Not used. */ Tcl_Interp *interp, /* Not used. */ Tcl_Value *argsPtr, Tcl_Value *resultPtr) { Tcl_Value *op1Ptr, *op2Ptr; op1Ptr = argsPtr, op2Ptr = argsPtr + 1; if ((op1Ptr->type == TCL_INT) && (op2Ptr->type == TCL_INT)) { resultPtr->intValue = MAX(op1Ptr->intValue, op2Ptr->intValue); resultPtr->type = TCL_INT; } else { double a, b; a = (op1Ptr->type == TCL_INT) ? (double)op1Ptr->intValue : op1Ptr->doubleValue; b = (op2Ptr->type == TCL_INT) ? (double)op2Ptr->intValue : op2Ptr->doubleValue; resultPtr->doubleValue = MAX(a, b); resultPtr->type = TCL_DOUBLE; } return TCL_OK; } static int SetLibraryPath(Tcl_Interp *interp) { Tcl_DString dString; const char *value; Tcl_DStringInit(&dString); Tcl_DStringAppend(&dString, libPath, -1); #ifdef WIN32 { HKEY key; DWORD result; # ifndef BLT_REGISTRY_KEY # define BLT_REGISTRY_KEY "Software\\BLT\\" BLT_VERSION "\\" TCL_VERSION # endif result = RegOpenKeyEx( HKEY_LOCAL_MACHINE, /* Parent key. */ BLT_REGISTRY_KEY, /* Path to sub-key. */ 0, /* Reserved. */ KEY_READ, /* Security access mask. */ &key); /* Resulting key.*/ if (result == ERROR_SUCCESS) { DWORD size; /* Query once to get the size of the string needed */ result = RegQueryValueEx(key, "BLT_LIBRARY", NULL, NULL, NULL, &size); if (result == ERROR_SUCCESS) { Tcl_DStringSetLength(&dString, size); /* And again to collect the string. */ RegQueryValueEx(key, "BLT_LIBRARY", NULL, NULL, (LPBYTE)Tcl_DStringValue(&dString), &size); RegCloseKey(key); } } } #endif /* WIN32 */ value = Tcl_SetVar(interp, "blt_libPath", Tcl_DStringValue(&dString), TCL_GLOBAL_ONLY | TCL_LEAVE_ERR_MSG); Tcl_DStringFree(&dString); if (value == NULL) { return TCL_ERROR; } return TCL_OK; } /*LINTLIBRARY*/ int Blt_core_Init(Tcl_Interp *interp) /* Interpreter to add extra commands */ { Tcl_AppInitProc **p; Tcl_Namespace *nsPtr; Tcl_ValueType args[2]; const char *result; const int isExact = 1; if( #ifdef USE_TCL_STUBS Tcl_InitStubs(interp, TCL_VERSION_LOADED, isExact) #else Tcl_PkgRequire(interp, "Tcl", TCL_VERSION_LOADED, isExact) #endif == NULL) { return TCL_ERROR; } /* Set the "blt_version", "blt_patchLevel", and "blt_libPath" Tcl * variables. We'll use them in the following script. */ result = Tcl_SetVar(interp, "blt_version", BLT_VERSION, TCL_GLOBAL_ONLY); if (result == NULL) { return TCL_ERROR; } result = Tcl_SetVar(interp, "blt_patchLevel", BLT_PATCH_LEVEL, TCL_GLOBAL_ONLY); if (result == NULL) { return TCL_ERROR; } if (SetLibraryPath(interp) != TCL_OK) { return TCL_ERROR; } if (Tcl_Eval(interp, initScript) != TCL_OK) { return TCL_ERROR; } nsPtr = Tcl_FindNamespace(interp, "::blt", (Tcl_Namespace *)NULL, 0); if (nsPtr == NULL) { nsPtr = Tcl_CreateNamespace(interp, "::blt", NULL, NULL); if (nsPtr == NULL) { return TCL_ERROR; } } /* Initialize the BLT commands that only require Tcl. */ for (p = cmdProcs; *p != NULL; p++) { if ((**p) (interp) != TCL_OK) { Tcl_DeleteNamespace(nsPtr); return TCL_ERROR; } } args[0] = args[1] = TCL_EITHER; Tcl_CreateMathFunc(interp, "min", 2, args, MinMathProc, (ClientData)0); Tcl_CreateMathFunc(interp, "max", 2, args, MaxMathProc, (ClientData)0); Blt_RegisterArrayObj(); bltNaN = MakeNaN(); if (Tcl_PkgProvide(interp, "blt_core", BLT_VERSION) != TCL_OK) { return TCL_ERROR; } return TCL_OK; } /*LINTLIBRARY*/ int Blt_core_SafeInit(Tcl_Interp *interp) /* Interpreter to add extra commands */ { return Blt_core_Init(interp); } <commit_msg>*** empty log message ***<commit_after> /* * bltCoreInit.c -- * * This module initials the non-Tk command of the BLT toolkit, registering the * commands with the TCL interpreter. * * Copyright 1991-2004 George A Howlett. * * 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 "bltInt.h" #include "bltNsUtil.h" #include "bltArrayObj.h" #include "bltMath.h" #ifndef BLT_LIBRARY # ifdef WIN32 # define BLT_LIBRARY "c:/Program Files/Tcl/lib/blt"##BLT_VERSION # else # define BLT_LIBRARY "unknown" # endif #endif #if (_TCL_VERSION >= _VERSION(8,5,0)) #define TCL_VERSION_LOADED TCL_PATCH_LEVEL #else #define TCL_VERSION_LOADED TCL_VERSION #endif static double bltNaN; BLT_EXTERN Tcl_AppInitProc Blt_core_Init; BLT_EXTERN Tcl_AppInitProc Blt_core_SafeInit; static Tcl_MathProc MinMathProc, MaxMathProc; static char libPath[1024] = { BLT_LIBRARY }; /* * Script to set the BLT library path in the variable global "blt_library" * * Checks the usual locations for a file (bltGraph.pro) from the BLT library. * The places searched in order are * * $BLT_LIBRARY * $BLT_LIBRARY/blt2.4 * $BLT_LIBRARY/.. * $BLT_LIBRARY/../blt2.4 * $blt_libPath * $blt_libPath/blt2.4 * $blt_libPath/.. * $blt_libPath/../blt2.4 * $tcl_library * $tcl_library/blt2.4 * $tcl_library/.. * $tcl_library/../blt2.4 * $env(TCL_LIBRARY) * $env(TCL_LIBRARY)/blt2.4 * $env(TCL_LIBRARY)/.. * $env(TCL_LIBRARY)/../blt2.4 * * The TCL variable "blt_library" is set to the discovered path. If the file * wasn't found, no error is returned. The actual usage of $blt_library is * purposely deferred so that it can be set from within a script. */ /* FIXME: Change this to a namespace procedure in 3.0 */ static char initScript[] = {"\n\ global blt_library blt_libPath blt_version tcl_library env\n\ set blt_library {}\n\ set path {}\n\ foreach var { env(BLT_LIBRARY) blt_libPath tcl_library env(TCL_LIBRARY) } { \n\ if { ![info exists $var] } { \n\ continue \n\ } \n\ set path [set $var] \n\ if { [file readable [file join $path bltGraph.pro]] } { \n\ set blt_library $path\n\ break \n\ } \n\ set path [file join $path blt$blt_version ] \n\ if { [file readable [file join $path bltGraph.pro]] } { \n\ set blt_library $path\n\ break \n\ } \n\ set path [file dirname [set $var]] \n\ if { [file readable [file join $path bltGraph.pro]] } { \n\ set blt_library $path\n\ break \n\ } \n\ set path [file join $path blt$blt_version ] \n\ if { [file readable [file join $path bltGraph.pro]] } { \n\ set blt_library $path\n\ break \n\ } \n\ } \n\ if { $blt_library != \"\" } { \n\ global auto_path \n\ lappend auto_path $blt_library \n\ }\n\ unset var path\n\ \n" }; double Blt_NaN(void) { return bltNaN; } static double MakeNaN(void) { union DoubleValue { unsigned int words[2]; double value; } result; #ifdef WORDS_BIGENDIAN result.words[0] = 0x7ff80000; result.words[1] = 0x00000000; #else result.words[0] = 0x00000000; result.words[1] = 0x7ff80000; #endif return result.value; } /* ARGSUSED */ static int MinMathProc( ClientData clientData, /* Not used. */ Tcl_Interp *interp, /* Not used. */ Tcl_Value *argsPtr, Tcl_Value *resultPtr) { Tcl_Value *op1Ptr, *op2Ptr; op1Ptr = argsPtr, op2Ptr = argsPtr + 1; if ((op1Ptr->type == TCL_INT) && (op2Ptr->type == TCL_INT)) { resultPtr->intValue = MIN(op1Ptr->intValue, op2Ptr->intValue); resultPtr->type = TCL_INT; } else { double a, b; a = (op1Ptr->type == TCL_INT) ? (double)op1Ptr->intValue : op1Ptr->doubleValue; b = (op2Ptr->type == TCL_INT) ? (double)op2Ptr->intValue : op2Ptr->doubleValue; resultPtr->doubleValue = MIN(a, b); resultPtr->type = TCL_DOUBLE; } return TCL_OK; } /*ARGSUSED*/ static int MaxMathProc( ClientData clientData, /* Not used. */ Tcl_Interp *interp, /* Not used. */ Tcl_Value *argsPtr, Tcl_Value *resultPtr) { Tcl_Value *op1Ptr, *op2Ptr; op1Ptr = argsPtr, op2Ptr = argsPtr + 1; if ((op1Ptr->type == TCL_INT) && (op2Ptr->type == TCL_INT)) { resultPtr->intValue = MAX(op1Ptr->intValue, op2Ptr->intValue); resultPtr->type = TCL_INT; } else { double a, b; a = (op1Ptr->type == TCL_INT) ? (double)op1Ptr->intValue : op1Ptr->doubleValue; b = (op2Ptr->type == TCL_INT) ? (double)op2Ptr->intValue : op2Ptr->doubleValue; resultPtr->doubleValue = MAX(a, b); resultPtr->type = TCL_DOUBLE; } return TCL_OK; } static int SetLibraryPath(Tcl_Interp *interp) { Tcl_DString dString; const char *value; Tcl_DStringInit(&dString); Tcl_DStringAppend(&dString, libPath, -1); #ifdef WIN32 { HKEY key; DWORD result; # ifndef BLT_REGISTRY_KEY # define BLT_REGISTRY_KEY "Software\\BLT\\" BLT_VERSION "\\" TCL_VERSION # endif result = RegOpenKeyEx( HKEY_LOCAL_MACHINE, /* Parent key. */ BLT_REGISTRY_KEY, /* Path to sub-key. */ 0, /* Reserved. */ KEY_READ, /* Security access mask. */ &key); /* Resulting key.*/ if (result == ERROR_SUCCESS) { DWORD size; /* Query once to get the size of the string needed */ result = RegQueryValueEx(key, "BLT_LIBRARY", NULL, NULL, NULL, &size); if (result == ERROR_SUCCESS) { Tcl_DStringSetLength(&dString, size); /* And again to collect the string. */ RegQueryValueEx(key, "BLT_LIBRARY", NULL, NULL, (LPBYTE)Tcl_DStringValue(&dString), &size); RegCloseKey(key); } } } #endif /* WIN32 */ value = Tcl_SetVar(interp, "blt_libPath", Tcl_DStringValue(&dString), TCL_GLOBAL_ONLY | TCL_LEAVE_ERR_MSG); Tcl_DStringFree(&dString); if (value == NULL) { return TCL_ERROR; } return TCL_OK; } /*LINTLIBRARY*/ int Blt_core_Init(Tcl_Interp *interp) /* Interpreter to add extra commands */ { Tcl_AppInitProc **p; Tcl_Namespace *nsPtr; Tcl_ValueType args[2]; const char *result; const int isExact = 1; if( #ifdef USE_TCL_STUBS Tcl_InitStubs(interp, TCL_VERSION_LOADED, isExact) #else Tcl_PkgRequire(interp, "Tcl", TCL_VERSION_LOADED, isExact) #endif == NULL) { return TCL_ERROR; } /* Set the "blt_version", "blt_patchLevel", and "blt_libPath" Tcl * variables. We'll use them in the following script. */ result = Tcl_SetVar(interp, "blt_version", BLT_VERSION, TCL_GLOBAL_ONLY); if (result == NULL) { return TCL_ERROR; } result = Tcl_SetVar(interp, "blt_patchLevel", BLT_PATCH_LEVEL, TCL_GLOBAL_ONLY); if (result == NULL) { return TCL_ERROR; } if (SetLibraryPath(interp) != TCL_OK) { return TCL_ERROR; } if (Tcl_Eval(interp, initScript) != TCL_OK) { return TCL_ERROR; } nsPtr = Tcl_FindNamespace(interp, "::blt", (Tcl_Namespace *)NULL, 0); if (nsPtr == NULL) { nsPtr = Tcl_CreateNamespace(interp, "::blt", NULL, NULL); if (nsPtr == NULL) { return TCL_ERROR; } } if (Blt_VectorCmdInitProc(interp) != TCL_OK) return TCL_ERROR; args[0] = args[1] = TCL_EITHER; Tcl_CreateMathFunc(interp, "min", 2, args, MinMathProc, (ClientData)0); Tcl_CreateMathFunc(interp, "max", 2, args, MaxMathProc, (ClientData)0); Blt_RegisterArrayObj(); bltNaN = MakeNaN(); if (Tcl_PkgProvide(interp, "blt_core", BLT_VERSION) != TCL_OK) { return TCL_ERROR; } return TCL_OK; } /*LINTLIBRARY*/ int Blt_core_SafeInit(Tcl_Interp *interp) /* Interpreter to add extra commands */ { return Blt_core_Init(interp); } <|endoftext|>
<commit_before>//requirements: x64 and C++14 #define USE_THREAD 1 #include<fstream> #include<memory> //make_unique #if USE_THREAD #include<mutex> #include<thread> //thread::hardware_concurrency() #endif #include<utility> //declval #include<type_traits> //remove_reference #include<vector> #include"../../lib/header/tool/CChrono_timer.hpp" #include"../../lib/header/tool/show.hpp" #if USE_THREAD #include"../../ThreadPool/header/CThreadPool.hpp" #endif #include"../header/CQCircuit.hpp" #include"../header/QCFwd.hpp" #include"../header/CTsaiAlgorithm.hpp" namespace { std::vector<std::remove_reference<decltype(std::declval<ICircuitAlgorithm>().get())>::type::size_type> accu; std::ofstream ofs{"output.txt"}; #if USE_THREAD std::mutex accu_mut; std::mutex ofs_mut; #endif void call_and_output(const Func_t &func) { using namespace std; unique_ptr<ICircuitAlgorithm> algorithm{make_unique<nTsaiAlgorithm::CTsaiAlgorithm>()}; algorithm->setFunc(func); algorithm->create(); auto size{algorithm->get().size()}; if(size) size=algorithm->get().front().size(); { #if USE_THREAD lock_guard<mutex> lock{ofs_mut}; #endif nTool::show(func.begin(),func.end(),ofs); ofs<<"gate : "<<size<<endl<<endl; } #if USE_THREAD lock_guard<mutex> lock{accu_mut}; #endif if(accu.size()<=size) accu.resize(size+1); ++accu[size]; } } int main() { using namespace std; nTool::CChrono_timer timer; { #if USE_THREAD nThread::CThreadPool tp{max<unsigned>(4,thread::hardware_concurrency())}; #endif Func_t func{0,1,2,3,4,5,6,7}; timer.start(); do #if USE_THREAD tp.add_and_detach(call_and_output,func); //copy func, not reference #else call_and_output(func); #endif while(next_permutation(func.begin(),func.end())); } timer.stop(); ofs<<timer.duration_minutes()<<"\tminutes"<<endl <<timer.duration_seconds()%60<<"\tseconds"<<endl <<timer.duration_milliseconds()%1000<<"\tmilliseconds"<<endl; nTool::show(accu.begin(),accu.end(),ofs); system("PAUSE"); }<commit_msg>update macro<commit_after>//requirements: x64 and C++14 #define USE_THREAD #include<fstream> #include<memory> //make_unique #ifdef USE_THREAD #include<mutex> #include<thread> //thread::hardware_concurrency() #endif #include<utility> //declval #include<type_traits> //remove_reference #include<vector> #include"../../lib/header/tool/CChrono_timer.hpp" #include"../../lib/header/tool/show.hpp" #ifdef USE_THREAD #include"../../ThreadPool/header/CThreadPool.hpp" #endif #include"../header/CQCircuit.hpp" #include"../header/QCFwd.hpp" #include"../header/CTsaiAlgorithm.hpp" namespace { std::vector<std::remove_reference<decltype(std::declval<ICircuitAlgorithm>().get())>::type::size_type> accu; std::ofstream ofs{"output.txt"}; #ifdef USE_THREAD std::mutex accu_mut; std::mutex ofs_mut; #endif void call_and_output(const Func_t &func) { using namespace std; unique_ptr<ICircuitAlgorithm> algorithm{make_unique<nTsaiAlgorithm::CTsaiAlgorithm>()}; algorithm->setFunc(func); algorithm->create(); auto size{algorithm->get().size()}; if(size) size=algorithm->get().front().size(); { #ifdef USE_THREAD lock_guard<mutex> lock{ofs_mut}; #endif nTool::show(func.begin(),func.end(),ofs); ofs<<"gate : "<<size<<endl<<endl; } #ifdef USE_THREAD lock_guard<mutex> lock{accu_mut}; #endif if(accu.size()<=size) accu.resize(size+1); ++accu[size]; } } int main() { using namespace std; nTool::CChrono_timer timer; { #ifdef USE_THREAD nThread::CThreadPool tp{max<unsigned>(4,thread::hardware_concurrency())}; #endif Func_t func{0,1,2,3,4,5,6,7}; timer.start(); do #ifdef USE_THREAD tp.add_and_detach(call_and_output,func); //copy func, not reference #else call_and_output(func); #endif while(next_permutation(func.begin(),func.end())); } timer.stop(); ofs<<timer.duration_minutes()<<"\tminutes"<<endl <<timer.duration_seconds()%60<<"\tseconds"<<endl <<timer.duration_milliseconds()%1000<<"\tmilliseconds"<<endl; nTool::show(accu.begin(),accu.end(),ofs); system("PAUSE"); }<|endoftext|>
<commit_before>// Copyright (c) Sandeep Mistry. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <LoRa.h> // registers #define REG_FIFO 0x00 #define REG_OP_MODE 0x01 #define REG_FRF_MSB 0x06 #define REG_FRF_MID 0x07 #define REG_FRF_LSB 0x08 #define REG_PA_CONFIG 0x09 #define REG_LNA 0x0c #define REG_FIFO_ADDR_PTR 0x0d #define REG_FIFO_TX_BASE_ADDR 0x0e #define REG_FIFO_RX_BASE_ADDR 0x0f #define REG_FIFO_RX_CURRENT_ADDR 0x10 #define REG_IRQ_FLAGS 0x12 #define REG_RX_NB_BYTES 0x13 #define REG_PKT_RSSI_VALUE 0x1a #define REG_PKT_SNR_VALUE 0x1b #define REG_MODEM_CONFIG_1 0x1d #define REG_MODEM_CONFIG_2 0x1e #define REG_PREAMBLE_MSB 0x20 #define REG_PREAMBLE_LSB 0x21 #define REG_PAYLOAD_LENGTH 0x22 #define REG_MODEM_CONFIG_3 0x26 #define REG_RSSI_WIDEBAND 0x2c #define REG_DETECTION_OPTIMIZE 0x31 #define REG_DETECTION_THRESHOLD 0x37 #define REG_SYNC_WORD 0x39 #define REG_DIO_MAPPING_1 0x40 #define REG_VERSION 0x42 // modes #define MODE_LONG_RANGE_MODE 0x80 #define MODE_SLEEP 0x00 #define MODE_STDBY 0x01 #define MODE_TX 0x03 #define MODE_RX_CONTINUOUS 0x05 #define MODE_RX_SINGLE 0x06 // PA config #define PA_BOOST 0x80 // IRQ masks #define IRQ_TX_DONE_MASK 0x08 #define IRQ_PAYLOAD_CRC_ERROR_MASK 0x20 #define IRQ_RX_DONE_MASK 0x40 #define MAX_PKT_LENGTH 255 LoRaClass::LoRaClass() : _spiSettings(8E6, MSBFIRST, SPI_MODE0), _ss(LORA_DEFAULT_SS_PIN), _reset(LORA_DEFAULT_RESET_PIN), _dio0(LORA_DEFAULT_DIO0_PIN), _frequency(0), _packetIndex(0), _implicitHeaderMode(0), _onReceive(NULL) { // overide Stream timeout value setTimeout(0); } int LoRaClass::begin(long frequency) { // setup pins pinMode(_ss, OUTPUT); pinMode(_reset, OUTPUT); // perform reset digitalWrite(_reset, LOW); delay(10); digitalWrite(_reset, HIGH); delay(10); // set SS high digitalWrite(_ss, HIGH); // start SPI SPI.begin(); // check version uint8_t version = readRegister(REG_VERSION); if (version != 0x12) { return 0; } // put in sleep mode sleep(); // set frequency setFrequency(frequency); // set base addresses writeRegister(REG_FIFO_TX_BASE_ADDR, 0); writeRegister(REG_FIFO_RX_BASE_ADDR, 0); // set LNA boost writeRegister(REG_LNA, readRegister(REG_LNA) | 0x03); // set auto AGC writeRegister(REG_MODEM_CONFIG_3, 0x04); // set output power to 17 dBm setTxPower(17); // put in standby mode idle(); return 1; } void LoRaClass::end() { // put in sleep mode sleep(); // stop SPI SPI.end(); } int LoRaClass::beginPacket(int implicitHeader) { // put in standby mode idle(); if (implicitHeader) { implicitHeaderMode(); } else { explicitHeaderMode(); } // reset FIFO address and paload length writeRegister(REG_FIFO_ADDR_PTR, 0); writeRegister(REG_PAYLOAD_LENGTH, 0); return 1; } int LoRaClass::endPacket() { // put in TX mode writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_TX); // wait for TX done while((readRegister(REG_IRQ_FLAGS) & IRQ_TX_DONE_MASK) == 0); // clear IRQ's writeRegister(REG_IRQ_FLAGS, IRQ_TX_DONE_MASK); return 1; } int LoRaClass::parsePacket(int size) { int packetLength = 0; int irqFlags = readRegister(REG_IRQ_FLAGS); if (size > 0) { implicitHeaderMode(); writeRegister(REG_PAYLOAD_LENGTH, size & 0xff); } else { explicitHeaderMode(); } // clear IRQ's writeRegister(REG_IRQ_FLAGS, irqFlags); if ((irqFlags & IRQ_RX_DONE_MASK) && (irqFlags & IRQ_PAYLOAD_CRC_ERROR_MASK) == 0) { // received a packet _packetIndex = 0; // read packet length if (_implicitHeaderMode) { packetLength = readRegister(REG_PAYLOAD_LENGTH); } else { packetLength = readRegister(REG_RX_NB_BYTES); } // set FIFO address to current RX address writeRegister(REG_FIFO_ADDR_PTR, readRegister(REG_FIFO_RX_CURRENT_ADDR)); // put in standby mode idle(); } else if (readRegister(REG_OP_MODE) != (MODE_LONG_RANGE_MODE | MODE_RX_SINGLE)) { // not currently in RX mode // reset FIFO address writeRegister(REG_FIFO_ADDR_PTR, 0); // put in single RX mode writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_RX_SINGLE); } return packetLength; } int LoRaClass::packetRssi() { return (readRegister(REG_PKT_RSSI_VALUE) - (_frequency < 868E6 ? 164 : 157)); } float LoRaClass::packetSnr() { return ((int8_t)readRegister(REG_PKT_SNR_VALUE)) * 0.25; } size_t LoRaClass::write(uint8_t byte) { return write(&byte, sizeof(byte)); } size_t LoRaClass::write(const uint8_t *buffer, size_t size) { int currentLength = readRegister(REG_PAYLOAD_LENGTH); // check size if ((currentLength + size) > MAX_PKT_LENGTH) { size = MAX_PKT_LENGTH - currentLength; } // write data for (size_t i = 0; i < size; i++) { writeRegister(REG_FIFO, buffer[i]); } // update length writeRegister(REG_PAYLOAD_LENGTH, currentLength + size); return size; } int LoRaClass::available() { return (readRegister(REG_RX_NB_BYTES) - _packetIndex); } int LoRaClass::read() { if (!available()) { return -1; } _packetIndex++; return readRegister(REG_FIFO); } int LoRaClass::peek() { if (!available()) { return -1; } // store current FIFO address int currentAddress = readRegister(REG_FIFO_ADDR_PTR); // read uint8_t b = readRegister(REG_FIFO); // restore FIFO address writeRegister(REG_FIFO_ADDR_PTR, currentAddress); return b; } void LoRaClass::flush() { } void LoRaClass::onReceive(void(*callback)(int)) { _onReceive = callback; if (callback) { writeRegister(REG_DIO_MAPPING_1, 0x00); attachInterrupt(digitalPinToInterrupt(_dio0), LoRaClass::onDio0Rise, RISING); } else { detachInterrupt(digitalPinToInterrupt(_dio0)); } } void LoRaClass::receive(int size) { if (size > 0) { implicitHeaderMode(); writeRegister(REG_PAYLOAD_LENGTH, size & 0xff); } else { explicitHeaderMode(); } writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_RX_CONTINUOUS); } void LoRaClass::idle() { writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_STDBY); } void LoRaClass::sleep() { writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_SLEEP); } void LoRaClass::setTxPower(int level, int outputPin) { if (PA_OUTPUT_RFO_PIN == outputPin) { // RFO if (level < 0) { level = 0; } else if (level > 14) { level = 14; } writeRegister(REG_PA_CONFIG, 0x70 | level); } else { // PA BOOST if (level < 2) { level = 2; } else if (level > 17) { level = 17; } writeRegister(REG_PA_CONFIG, PA_BOOST | (level - 2)); } } void LoRaClass::setFrequency(long frequency) { _frequency = frequency; uint64_t frf = ((uint64_t)frequency << 19) / 32000000; writeRegister(REG_FRF_MSB, (uint8_t)(frf >> 16)); writeRegister(REG_FRF_MID, (uint8_t)(frf >> 8)); writeRegister(REG_FRF_LSB, (uint8_t)(frf >> 0)); } void LoRaClass::setSpreadingFactor(int sf) { if (sf < 6) { sf = 6; } else if (sf > 12) { sf = 12; } if (sf == 6) { writeRegister(REG_DETECTION_OPTIMIZE, 0xc5); writeRegister(REG_DETECTION_THRESHOLD, 0x0c); } else { writeRegister(REG_DETECTION_OPTIMIZE, 0xc3); writeRegister(REG_DETECTION_THRESHOLD, 0x0a); } writeRegister(REG_MODEM_CONFIG_2, (readRegister(REG_MODEM_CONFIG_2) & 0x0f) | ((sf << 4) & 0xf0)); } void LoRaClass::setSignalBandwidth(long sbw) { int bw; if (sbw <= 7.8E3) { bw = 0; } else if (sbw <= 10.4E3) { bw = 1; } else if (sbw <= 15.6E3) { bw = 2; } else if (sbw <= 20.8E3) { bw = 3; } else if (sbw <= 31.25E3) { bw = 4; } else if (sbw <= 41.7E3) { bw = 5; } else if (sbw <= 62.5E3) { bw = 6; } else if (sbw <= 125E3) { bw = 7; } else if (sbw <= 250E3) { bw = 8; } else /*if (sbw <= 250E3)*/ { bw = 9; } writeRegister(REG_MODEM_CONFIG_1, (readRegister(REG_MODEM_CONFIG_1) & 0x0f) | (bw << 4)); } void LoRaClass::setCodingRate4(int denominator) { if (denominator < 5) { denominator = 5; } else if (denominator > 8) { denominator = 8; } int cr = denominator - 4; writeRegister(REG_MODEM_CONFIG_1, (readRegister(REG_MODEM_CONFIG_1) & 0xf1) | (cr << 1)); } void LoRaClass::setPreambleLength(long length) { writeRegister(REG_PREAMBLE_MSB, (uint8_t)(length >> 8)); writeRegister(REG_PREAMBLE_LSB, (uint8_t)(length >> 0)); } void LoRaClass::setSyncWord(int sw) { writeRegister(REG_SYNC_WORD, sw); } void LoRaClass::enableCrc() { writeRegister(REG_MODEM_CONFIG_2, readRegister(REG_MODEM_CONFIG_2) | 0x04); } void LoRaClass::disableCrc() { writeRegister(REG_MODEM_CONFIG_2, readRegister(REG_MODEM_CONFIG_2) & 0xfb); } byte LoRaClass::random() { return readRegister(REG_RSSI_WIDEBAND); } void LoRaClass::setPins(int ss, int reset, int dio0) { _ss = ss; _reset = reset; _dio0 = dio0; } void LoRaClass::setSPIFrequency(uint32_t frequency) { _spiSettings = SPISettings(frequency, MSBFIRST, SPI_MODE0); } void LoRaClass::dumpRegisters(Stream& out) { for (int i = 0; i < 128; i++) { out.print("0x"); out.print(i, HEX); out.print(": 0x"); out.println(readRegister(i), HEX); } } void LoRaClass::explicitHeaderMode() { _implicitHeaderMode = 0; writeRegister(REG_MODEM_CONFIG_1, readRegister(REG_MODEM_CONFIG_1) & 0xfe); } void LoRaClass::implicitHeaderMode() { _implicitHeaderMode = 1; writeRegister(REG_MODEM_CONFIG_1, readRegister(REG_MODEM_CONFIG_1) | 0x01); } void LoRaClass::handleDio0Rise() { int irqFlags = readRegister(REG_IRQ_FLAGS); // clear IRQ's writeRegister(REG_IRQ_FLAGS, irqFlags); if ((irqFlags & IRQ_PAYLOAD_CRC_ERROR_MASK) == 0) { // received a packet _packetIndex = 0; // read packet length int packetLength = _implicitHeaderMode ? readRegister(REG_PAYLOAD_LENGTH) : readRegister(REG_RX_NB_BYTES); // set FIFO address to current RX address writeRegister(REG_FIFO_ADDR_PTR, readRegister(REG_FIFO_RX_CURRENT_ADDR)); if (_onReceive) { _onReceive(packetLength); } // reset FIFO address writeRegister(REG_FIFO_ADDR_PTR, 0); } } uint8_t LoRaClass::readRegister(uint8_t address) { return singleTransfer(address & 0x7f, 0x00); } void LoRaClass::writeRegister(uint8_t address, uint8_t value) { singleTransfer(address | 0x80, value); } uint8_t LoRaClass::singleTransfer(uint8_t address, uint8_t value) { uint8_t response; digitalWrite(_ss, LOW); SPI.beginTransaction(_spiSettings); SPI.transfer(address); response = SPI.transfer(value); SPI.endTransaction(); digitalWrite(_ss, HIGH); return response; } void LoRaClass::onDio0Rise() { LoRa.handleDio0Rise(); } LoRaClass LoRa; <commit_msg>fix SNR register<commit_after>// Copyright (c) Sandeep Mistry. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <LoRa.h> // registers #define REG_FIFO 0x00 #define REG_OP_MODE 0x01 #define REG_FRF_MSB 0x06 #define REG_FRF_MID 0x07 #define REG_FRF_LSB 0x08 #define REG_PA_CONFIG 0x09 #define REG_LNA 0x0c #define REG_FIFO_ADDR_PTR 0x0d #define REG_FIFO_TX_BASE_ADDR 0x0e #define REG_FIFO_RX_BASE_ADDR 0x0f #define REG_FIFO_RX_CURRENT_ADDR 0x10 #define REG_IRQ_FLAGS 0x12 #define REG_RX_NB_BYTES 0x13 #define REG_PKT_SNR_VALUE 0x19 #define REG_PKT_RSSI_VALUE 0x1a #define REG_MODEM_CONFIG_1 0x1d #define REG_MODEM_CONFIG_2 0x1e #define REG_PREAMBLE_MSB 0x20 #define REG_PREAMBLE_LSB 0x21 #define REG_PAYLOAD_LENGTH 0x22 #define REG_MODEM_CONFIG_3 0x26 #define REG_RSSI_WIDEBAND 0x2c #define REG_DETECTION_OPTIMIZE 0x31 #define REG_DETECTION_THRESHOLD 0x37 #define REG_SYNC_WORD 0x39 #define REG_DIO_MAPPING_1 0x40 #define REG_VERSION 0x42 // modes #define MODE_LONG_RANGE_MODE 0x80 #define MODE_SLEEP 0x00 #define MODE_STDBY 0x01 #define MODE_TX 0x03 #define MODE_RX_CONTINUOUS 0x05 #define MODE_RX_SINGLE 0x06 // PA config #define PA_BOOST 0x80 // IRQ masks #define IRQ_TX_DONE_MASK 0x08 #define IRQ_PAYLOAD_CRC_ERROR_MASK 0x20 #define IRQ_RX_DONE_MASK 0x40 #define MAX_PKT_LENGTH 255 LoRaClass::LoRaClass() : _spiSettings(8E6, MSBFIRST, SPI_MODE0), _ss(LORA_DEFAULT_SS_PIN), _reset(LORA_DEFAULT_RESET_PIN), _dio0(LORA_DEFAULT_DIO0_PIN), _frequency(0), _packetIndex(0), _implicitHeaderMode(0), _onReceive(NULL) { // overide Stream timeout value setTimeout(0); } int LoRaClass::begin(long frequency) { // setup pins pinMode(_ss, OUTPUT); pinMode(_reset, OUTPUT); // perform reset digitalWrite(_reset, LOW); delay(10); digitalWrite(_reset, HIGH); delay(10); // set SS high digitalWrite(_ss, HIGH); // start SPI SPI.begin(); // check version uint8_t version = readRegister(REG_VERSION); if (version != 0x12) { return 0; } // put in sleep mode sleep(); // set frequency setFrequency(frequency); // set base addresses writeRegister(REG_FIFO_TX_BASE_ADDR, 0); writeRegister(REG_FIFO_RX_BASE_ADDR, 0); // set LNA boost writeRegister(REG_LNA, readRegister(REG_LNA) | 0x03); // set auto AGC writeRegister(REG_MODEM_CONFIG_3, 0x04); // set output power to 17 dBm setTxPower(17); // put in standby mode idle(); return 1; } void LoRaClass::end() { // put in sleep mode sleep(); // stop SPI SPI.end(); } int LoRaClass::beginPacket(int implicitHeader) { // put in standby mode idle(); if (implicitHeader) { implicitHeaderMode(); } else { explicitHeaderMode(); } // reset FIFO address and paload length writeRegister(REG_FIFO_ADDR_PTR, 0); writeRegister(REG_PAYLOAD_LENGTH, 0); return 1; } int LoRaClass::endPacket() { // put in TX mode writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_TX); // wait for TX done while((readRegister(REG_IRQ_FLAGS) & IRQ_TX_DONE_MASK) == 0); // clear IRQ's writeRegister(REG_IRQ_FLAGS, IRQ_TX_DONE_MASK); return 1; } int LoRaClass::parsePacket(int size) { int packetLength = 0; int irqFlags = readRegister(REG_IRQ_FLAGS); if (size > 0) { implicitHeaderMode(); writeRegister(REG_PAYLOAD_LENGTH, size & 0xff); } else { explicitHeaderMode(); } // clear IRQ's writeRegister(REG_IRQ_FLAGS, irqFlags); if ((irqFlags & IRQ_RX_DONE_MASK) && (irqFlags & IRQ_PAYLOAD_CRC_ERROR_MASK) == 0) { // received a packet _packetIndex = 0; // read packet length if (_implicitHeaderMode) { packetLength = readRegister(REG_PAYLOAD_LENGTH); } else { packetLength = readRegister(REG_RX_NB_BYTES); } // set FIFO address to current RX address writeRegister(REG_FIFO_ADDR_PTR, readRegister(REG_FIFO_RX_CURRENT_ADDR)); // put in standby mode idle(); } else if (readRegister(REG_OP_MODE) != (MODE_LONG_RANGE_MODE | MODE_RX_SINGLE)) { // not currently in RX mode // reset FIFO address writeRegister(REG_FIFO_ADDR_PTR, 0); // put in single RX mode writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_RX_SINGLE); } return packetLength; } int LoRaClass::packetRssi() { return (readRegister(REG_PKT_RSSI_VALUE) - (_frequency < 868E6 ? 164 : 157)); } float LoRaClass::packetSnr() { return ((int8_t)readRegister(REG_PKT_SNR_VALUE)) * 0.25; } size_t LoRaClass::write(uint8_t byte) { return write(&byte, sizeof(byte)); } size_t LoRaClass::write(const uint8_t *buffer, size_t size) { int currentLength = readRegister(REG_PAYLOAD_LENGTH); // check size if ((currentLength + size) > MAX_PKT_LENGTH) { size = MAX_PKT_LENGTH - currentLength; } // write data for (size_t i = 0; i < size; i++) { writeRegister(REG_FIFO, buffer[i]); } // update length writeRegister(REG_PAYLOAD_LENGTH, currentLength + size); return size; } int LoRaClass::available() { return (readRegister(REG_RX_NB_BYTES) - _packetIndex); } int LoRaClass::read() { if (!available()) { return -1; } _packetIndex++; return readRegister(REG_FIFO); } int LoRaClass::peek() { if (!available()) { return -1; } // store current FIFO address int currentAddress = readRegister(REG_FIFO_ADDR_PTR); // read uint8_t b = readRegister(REG_FIFO); // restore FIFO address writeRegister(REG_FIFO_ADDR_PTR, currentAddress); return b; } void LoRaClass::flush() { } void LoRaClass::onReceive(void(*callback)(int)) { _onReceive = callback; if (callback) { writeRegister(REG_DIO_MAPPING_1, 0x00); attachInterrupt(digitalPinToInterrupt(_dio0), LoRaClass::onDio0Rise, RISING); } else { detachInterrupt(digitalPinToInterrupt(_dio0)); } } void LoRaClass::receive(int size) { if (size > 0) { implicitHeaderMode(); writeRegister(REG_PAYLOAD_LENGTH, size & 0xff); } else { explicitHeaderMode(); } writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_RX_CONTINUOUS); } void LoRaClass::idle() { writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_STDBY); } void LoRaClass::sleep() { writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_SLEEP); } void LoRaClass::setTxPower(int level, int outputPin) { if (PA_OUTPUT_RFO_PIN == outputPin) { // RFO if (level < 0) { level = 0; } else if (level > 14) { level = 14; } writeRegister(REG_PA_CONFIG, 0x70 | level); } else { // PA BOOST if (level < 2) { level = 2; } else if (level > 17) { level = 17; } writeRegister(REG_PA_CONFIG, PA_BOOST | (level - 2)); } } void LoRaClass::setFrequency(long frequency) { _frequency = frequency; uint64_t frf = ((uint64_t)frequency << 19) / 32000000; writeRegister(REG_FRF_MSB, (uint8_t)(frf >> 16)); writeRegister(REG_FRF_MID, (uint8_t)(frf >> 8)); writeRegister(REG_FRF_LSB, (uint8_t)(frf >> 0)); } void LoRaClass::setSpreadingFactor(int sf) { if (sf < 6) { sf = 6; } else if (sf > 12) { sf = 12; } if (sf == 6) { writeRegister(REG_DETECTION_OPTIMIZE, 0xc5); writeRegister(REG_DETECTION_THRESHOLD, 0x0c); } else { writeRegister(REG_DETECTION_OPTIMIZE, 0xc3); writeRegister(REG_DETECTION_THRESHOLD, 0x0a); } writeRegister(REG_MODEM_CONFIG_2, (readRegister(REG_MODEM_CONFIG_2) & 0x0f) | ((sf << 4) & 0xf0)); } void LoRaClass::setSignalBandwidth(long sbw) { int bw; if (sbw <= 7.8E3) { bw = 0; } else if (sbw <= 10.4E3) { bw = 1; } else if (sbw <= 15.6E3) { bw = 2; } else if (sbw <= 20.8E3) { bw = 3; } else if (sbw <= 31.25E3) { bw = 4; } else if (sbw <= 41.7E3) { bw = 5; } else if (sbw <= 62.5E3) { bw = 6; } else if (sbw <= 125E3) { bw = 7; } else if (sbw <= 250E3) { bw = 8; } else /*if (sbw <= 250E3)*/ { bw = 9; } writeRegister(REG_MODEM_CONFIG_1, (readRegister(REG_MODEM_CONFIG_1) & 0x0f) | (bw << 4)); } void LoRaClass::setCodingRate4(int denominator) { if (denominator < 5) { denominator = 5; } else if (denominator > 8) { denominator = 8; } int cr = denominator - 4; writeRegister(REG_MODEM_CONFIG_1, (readRegister(REG_MODEM_CONFIG_1) & 0xf1) | (cr << 1)); } void LoRaClass::setPreambleLength(long length) { writeRegister(REG_PREAMBLE_MSB, (uint8_t)(length >> 8)); writeRegister(REG_PREAMBLE_LSB, (uint8_t)(length >> 0)); } void LoRaClass::setSyncWord(int sw) { writeRegister(REG_SYNC_WORD, sw); } void LoRaClass::enableCrc() { writeRegister(REG_MODEM_CONFIG_2, readRegister(REG_MODEM_CONFIG_2) | 0x04); } void LoRaClass::disableCrc() { writeRegister(REG_MODEM_CONFIG_2, readRegister(REG_MODEM_CONFIG_2) & 0xfb); } byte LoRaClass::random() { return readRegister(REG_RSSI_WIDEBAND); } void LoRaClass::setPins(int ss, int reset, int dio0) { _ss = ss; _reset = reset; _dio0 = dio0; } void LoRaClass::setSPIFrequency(uint32_t frequency) { _spiSettings = SPISettings(frequency, MSBFIRST, SPI_MODE0); } void LoRaClass::dumpRegisters(Stream& out) { for (int i = 0; i < 128; i++) { out.print("0x"); out.print(i, HEX); out.print(": 0x"); out.println(readRegister(i), HEX); } } void LoRaClass::explicitHeaderMode() { _implicitHeaderMode = 0; writeRegister(REG_MODEM_CONFIG_1, readRegister(REG_MODEM_CONFIG_1) & 0xfe); } void LoRaClass::implicitHeaderMode() { _implicitHeaderMode = 1; writeRegister(REG_MODEM_CONFIG_1, readRegister(REG_MODEM_CONFIG_1) | 0x01); } void LoRaClass::handleDio0Rise() { int irqFlags = readRegister(REG_IRQ_FLAGS); // clear IRQ's writeRegister(REG_IRQ_FLAGS, irqFlags); if ((irqFlags & IRQ_PAYLOAD_CRC_ERROR_MASK) == 0) { // received a packet _packetIndex = 0; // read packet length int packetLength = _implicitHeaderMode ? readRegister(REG_PAYLOAD_LENGTH) : readRegister(REG_RX_NB_BYTES); // set FIFO address to current RX address writeRegister(REG_FIFO_ADDR_PTR, readRegister(REG_FIFO_RX_CURRENT_ADDR)); if (_onReceive) { _onReceive(packetLength); } // reset FIFO address writeRegister(REG_FIFO_ADDR_PTR, 0); } } uint8_t LoRaClass::readRegister(uint8_t address) { return singleTransfer(address & 0x7f, 0x00); } void LoRaClass::writeRegister(uint8_t address, uint8_t value) { singleTransfer(address | 0x80, value); } uint8_t LoRaClass::singleTransfer(uint8_t address, uint8_t value) { uint8_t response; digitalWrite(_ss, LOW); SPI.beginTransaction(_spiSettings); SPI.transfer(address); response = SPI.transfer(value); SPI.endTransaction(); digitalWrite(_ss, HIGH); return response; } void LoRaClass::onDio0Rise() { LoRa.handleDio0Rise(); } LoRaClass LoRa; <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <set> #include <algorithm> #include <queue> #include <boost/asio.hpp> #include <boost/thread.hpp> #include <google/protobuf/io/coded_stream.h> #include "message.pb.h" using namespace boost::asio; using ru::spbau::chat::commons::protocol::Message; using google::protobuf::io::CodedInputStream; using google::protobuf::io::CodedOutputStream; using google::protobuf::uint8; using google::protobuf::uint32; class chat_user { public: virtual void accept_message_size() = 0; virtual void deliver_message(std::shared_ptr<Message> const &message) = 0; }; typedef std::shared_ptr<chat_user> user_ptr; class chat_room { public: chat_room() { } void add_new_user(user_ptr user) { rw_mutex.lock(); users.push_back(user); rw_mutex.unlock(); #ifdef DEBUG std::cout << "User connected" << std::endl; #endif user->accept_message_size(); } void on_user_leave(user_ptr user) { rw_mutex.lock(); auto pos = std::find_if(users.begin(), users.end(), [user](user_ptr &ptr) { return ptr.get() == user.get(); }); if (pos != users.end()) { users.erase(pos); } rw_mutex.unlock(); #ifdef DEBUG std::cout << "User leaved" << std::endl; #endif } void deliver_message_to_all(std::shared_ptr<Message> const &message) { rw_mutex.lock_shared(); for(auto &user_p: users) { user_p->deliver_message(message); } rw_mutex.unlock_shared(); } private: std::vector<user_ptr> users; boost::shared_mutex rw_mutex; }; #ifdef DEBUG static size_t const INITIAL_BUFFER_SIZE = 1 << 2; // 4 b #else static size_t const INITIAL_BUFFER_SIZE = 1 << 12; // 4 Kb #endif static size_t const MAX_VARINT_BYTES = 10; class user : public chat_user, public std::enable_shared_from_this<user> { public: user(ip::tcp::socket sock, chat_room &chat, io_service &service) : socket(std::move(sock)), chat(chat), service(service), message_buffer(std::max(INITIAL_BUFFER_SIZE, MAX_VARINT_BYTES)), buffer_offset(0), buffer_red(0), write_buffer(std::max(INITIAL_BUFFER_SIZE, MAX_VARINT_BYTES)), write_in_progress(false) { assert(socket.is_open()); } void accept_message_size() { check_enougth_space(MAX_VARINT_BYTES); if (buffer_red) { bool read_succ; size_t read_bytes_count; uint32 message_size; { CodedInputStream input(message_buffer.data() + buffer_offset, buffer_red); read_succ = input.ReadVarint32(&message_size); read_bytes_count = input.CurrentPosition(); } if (read_succ) { buffer_offset += read_bytes_count; buffer_red -= read_bytes_count; accept_message(message_size); return; } if (buffer_red > MAX_VARINT_BYTES) { #ifdef DEBUG std::cout << "invalid varint: " << std::endl; #endif chat.on_user_leave(shared_from_this()); return; } } auto ancor(shared_from_this()); async_read(socket, buffer(message_buffer.data() + buffer_offset + buffer_red, message_buffer.size() - buffer_offset - buffer_red), transfer_at_least(1), [this, ancor](boost::system::error_code ec, std::size_t bytes_red) { #ifdef DEBUG std::cout << "Reading message size: bytes red " << buffer_red + bytes_red << std::endl; #endif if (ec) { #ifdef DEBUG std::cout << "error on reading message_size: " << ec.message() << std::endl; #endif chat.on_user_leave(shared_from_this()); return; } else { buffer_red += bytes_red; accept_message_size(); } }); } void accept_message(uint32 message_size) { check_enougth_space(message_size); if (buffer_red >= message_size) { { std::shared_ptr<Message> message(new Message()); try { message->ParseFromArray(message_buffer.data() + buffer_offset, message_size); } catch (std::exception &) { #ifdef DEBUG std::cout << "Failed to parse protobuf message" << std::endl; #endif chat.on_user_leave(shared_from_this()); return; } buffer_offset += message_size; buffer_red -= message_size; #ifdef DEBUG std::cout << "message red [" << (message->has_type() ? message->type() : -1) << ", " << (message->has_author() ? message->author() : "no author") << ", " << (message->text_size() ? message->text(0) : "no text") << "]" << std::endl; #endif chat.deliver_message_to_all(message); } accept_message_size(); return; } auto ancor(shared_from_this()); async_read(socket, buffer(message_buffer.data() + buffer_offset + buffer_red, message_buffer.size() - buffer_offset - buffer_red), transfer_at_least(message_size - buffer_red), [this, ancor, message_size](boost::system::error_code ec, std::size_t bytes_red) { #ifdef DEBUG std::cout << "Reading message: bytes red " << buffer_red + bytes_red << " from " << message_size << std::endl; #endif if (ec) { #ifdef DEBUG std::cout << "error: " << ec.message() << std::endl; #endif chat.on_user_leave(shared_from_this()); return; } else { buffer_red += bytes_red; accept_message(message_size); } }); } void deliver_message(std::shared_ptr<Message> const &message) { boost::lock_guard<boost::mutex> guard(deliver_queue_mutex); messages_to_deliver.push(message); if (write_in_progress) { return; } write_in_progress = true; auto ancor(shared_from_this()); service.post([this, ancor](){do_write();}); } ~user() { #ifdef DEBUG std::cout << "user destroyed" << std::endl; #endif } private: void check_enougth_space(size_t space_needed) { assert(buffer_offset + buffer_red <= message_buffer.size()); if (!buffer_red) { buffer_offset = 0; } if (buffer_offset + space_needed <= message_buffer.size()) { return; } memmove(message_buffer.data(), message_buffer.data() + buffer_offset, buffer_red); buffer_offset = 0; if (space_needed > message_buffer.size()) { message_buffer.resize(space_needed); } } void do_write() { boost::lock_guard<boost::mutex> guard(deliver_queue_mutex); size_t min_size = messages_to_deliver.front()->ByteSize() + MAX_VARINT_BYTES; if (write_buffer.size() < min_size) { write_buffer.resize(min_size); } size_t write_buffer_offset = 0; while (!messages_to_deliver.empty()) { std::shared_ptr<Message> const &message = messages_to_deliver.front(); if (message->ByteSize() + MAX_VARINT_BYTES > write_buffer.size() - write_buffer_offset) { break; } #ifdef DEBUG std::cout << "message written" << std::endl; #endif size_t byte_size = message->ByteSize(); auto it = CodedOutputStream::WriteVarint32ToArray(byte_size, write_buffer.data() + write_buffer_offset); write_buffer_offset = it - write_buffer.data(); bool written = message->SerializeToArray(write_buffer.data() + write_buffer_offset, byte_size); write_buffer_offset += byte_size; assert(written); messages_to_deliver.pop(); } auto ancor(shared_from_this()); async_write(socket, buffer(write_buffer.data(), write_buffer_offset), [this, ancor](boost::system::error_code ec, std::size_t) { if (ec) { #ifdef DEBUG std::cout << "error writing: " << ec.message() << std::endl; #endif chat.on_user_leave(shared_from_this()); return; } else { boost::lock_guard<boost::mutex> guard(deliver_queue_mutex); if (!messages_to_deliver.empty()) { service.post([this, ancor](){do_write();}); } else { write_in_progress = false; } } }); } private: ip::tcp::socket socket; chat_room &chat; io_service &service; std::vector<uint8> message_buffer; size_t buffer_offset; size_t buffer_red; std::vector<uint8> write_buffer; std::queue<std::shared_ptr<Message>> messages_to_deliver; boost::mutex deliver_queue_mutex; bool write_in_progress; }; class connection_handler { public: connection_handler(io_service &service, int port, chat_room &chat) : sock(service), service(service), acc(service, ip::tcp::endpoint(ip::tcp::v4(), port)), chat(chat) { } public: void accept_new_connection() { acc.async_accept(sock, [this](boost::system::error_code) { assert(sock.is_open()); chat.add_new_user(std::make_shared<user>(std::move(sock), chat, service)); accept_new_connection(); }); } private: ip::tcp::socket sock; io_service &service; ip::tcp::acceptor acc; chat_room &chat; }; int main(int argc, char *argv[]) { if (argc < 3) { std::cout << "Usage: ./chat_server $PORT_NUMBER$ $CONCURRENCY_LEVEL$" << std::endl << "Where $CONCURRENCY_LEVEL$ - number of the worker threads" << std::endl; return -1; } size_t port = std::atoi(argv[1]); size_t concurrency_level = std::atoi(argv[2]); try { std::cout << "Starting chat server on port " << port << " with concurrency level " << concurrency_level << " ..." << std::endl; chat_room chat; io_service service(concurrency_level); connection_handler handler(service, port, chat); handler.accept_new_connection(); boost::thread_group workers; auto const worker = boost::bind(&io_service::run, &service); for (size_t idx = 0; idx < concurrency_level; ++idx) { workers.create_thread(worker); } std::cout << "The server is started" << std::endl; std::cout << "Press 'enter' to stop the server" << std::endl; std::cin.get(); std::cout << "Stopping the server..." << std::endl; service.stop(); workers.join_all(); std::cout << "The server is stopped" << std::endl; } catch(std::exception &e) { std::cerr << "An exception occured with "; if (e.what()) { std::cerr << "message: \"" << e.what() << '"'; } else { std::cerr << "no message"; } std::cerr << std::endl; google::protobuf::ShutdownProtobufLibrary(); return -1; } google::protobuf::ShutdownProtobufLibrary(); return 0; } <commit_msg>Minor performance fixes<commit_after>#include <iostream> #include <vector> #include <set> #include <algorithm> #include <queue> #include <boost/asio.hpp> #include <boost/thread.hpp> #include <google/protobuf/io/coded_stream.h> #include "message.pb.h" using namespace boost::asio; using ru::spbau::chat::commons::protocol::Message; using google::protobuf::io::CodedInputStream; using google::protobuf::io::CodedOutputStream; using google::protobuf::uint8; using google::protobuf::uint32; class chat_user { public: virtual void accept_message_size() = 0; virtual void deliver_message(std::shared_ptr<Message> const &message) = 0; }; typedef std::shared_ptr<chat_user> user_ptr; class chat_room { public: chat_room() { } void add_new_user(user_ptr user) { rw_mutex.lock(); users.push_back(user); rw_mutex.unlock(); #ifdef DEBUG std::cout << "User connected" << std::endl; #endif user->accept_message_size(); } void on_user_leave(user_ptr user) { rw_mutex.lock(); auto pos = std::find_if(users.begin(), users.end(), [user](user_ptr &ptr) { return ptr.get() == user.get(); }); if (pos != users.end()) { users.erase(pos); } rw_mutex.unlock(); #ifdef DEBUG std::cout << "User leaved" << std::endl; #endif } void deliver_message_to_all(std::shared_ptr<Message> const &message) { rw_mutex.lock_shared(); for(auto &user_p: users) { user_p->deliver_message(message); } rw_mutex.unlock_shared(); } private: std::vector<user_ptr> users; boost::shared_mutex rw_mutex; }; #ifdef DEBUG static size_t const INITIAL_BUFFER_SIZE = 1 << 2; // 4 b #else static size_t const INITIAL_BUFFER_SIZE = 1 << 12; // 4 Kb #endif static size_t const MAX_VARINT_BYTES = 10; class user : public chat_user, public std::enable_shared_from_this<user> { public: user(ip::tcp::socket sock, chat_room &chat, io_service &service) : socket(std::move(sock)), chat(chat), service(service), message_buffer(std::max(INITIAL_BUFFER_SIZE, MAX_VARINT_BYTES)), buffer_offset(0), buffer_red(0), write_buffer(std::max(INITIAL_BUFFER_SIZE, MAX_VARINT_BYTES)), write_in_progress(false) { } void accept_message_size() { check_enougth_space(MAX_VARINT_BYTES); if (buffer_red) { bool read_succ; size_t read_bytes_count; uint32 message_size; { CodedInputStream input(message_buffer.data() + buffer_offset, buffer_red); read_succ = input.ReadVarint32(&message_size); read_bytes_count = input.CurrentPosition(); } if (read_succ) { buffer_offset += read_bytes_count; buffer_red -= read_bytes_count; accept_message(message_size); return; } if (buffer_red > MAX_VARINT_BYTES) { #ifdef DEBUG std::cout << "invalid varint: " << std::endl; #endif chat.on_user_leave(shared_from_this()); return; } } auto ancor(shared_from_this()); async_read(socket, buffer(message_buffer.data() + buffer_offset + buffer_red, message_buffer.size() - buffer_offset - buffer_red), transfer_at_least(1), [this, ancor](boost::system::error_code ec, std::size_t bytes_red) { #ifdef DEBUG std::cout << "Reading message size: bytes red " << buffer_red + bytes_red << std::endl; #endif if (ec) { #ifdef DEBUG std::cout << "error on reading message_size: " << ec.message() << std::endl; #endif chat.on_user_leave(shared_from_this()); return; } else { buffer_red += bytes_red; accept_message_size(); } }); } void accept_message(uint32 message_size) { check_enougth_space(message_size); if (buffer_red >= message_size) { { std::shared_ptr<Message> message(new Message()); try { message->ParseFromArray(message_buffer.data() + buffer_offset, message_size); } catch (std::exception &) { #ifdef DEBUG std::cout << "Failed to parse protobuf message" << std::endl; #endif chat.on_user_leave(shared_from_this()); return; } buffer_offset += message_size; buffer_red -= message_size; #ifdef DEBUG std::cout << "message red [" << (message->has_type() ? message->type() : -1) << ", " << (message->has_author() ? message->author() : "no author") << ", " << (message->text_size() ? message->text(0) : "no text") << "]" << std::endl; #endif chat.deliver_message_to_all(message); } accept_message_size(); return; } auto ancor(shared_from_this()); async_read(socket, buffer(message_buffer.data() + buffer_offset + buffer_red, message_buffer.size() - buffer_offset - buffer_red), transfer_at_least(message_size - buffer_red), [this, ancor, message_size](boost::system::error_code ec, std::size_t bytes_red) { #ifdef DEBUG std::cout << "Reading message: bytes red " << buffer_red + bytes_red << " from " << message_size << std::endl; #endif if (ec) { #ifdef DEBUG std::cout << "error: " << ec.message() << std::endl; #endif chat.on_user_leave(shared_from_this()); return; } else { buffer_red += bytes_red; accept_message(message_size); } }); } void deliver_message(std::shared_ptr<Message> const &message) { boost::lock_guard<boost::mutex> guard(deliver_queue_mutex); messages_to_deliver.push(message); if (write_in_progress) { return; } write_in_progress = true; auto ancor(shared_from_this()); service.post([this, ancor](){do_write();}); } ~user() { #ifdef DEBUG std::cout << "user destroyed" << std::endl; #endif } private: void check_enougth_space(size_t space_needed) { assert(buffer_offset + buffer_red <= message_buffer.size()); if (!buffer_red) { buffer_offset = 0; } if (buffer_offset + space_needed <= message_buffer.size()) { return; } memmove(message_buffer.data(), message_buffer.data() + buffer_offset, buffer_red); buffer_offset = 0; if (space_needed > message_buffer.size()) { message_buffer.resize(space_needed); } } void do_write() { boost::lock_guard<boost::mutex> guard(deliver_queue_mutex); size_t min_size = messages_to_deliver.front()->ByteSize() + MAX_VARINT_BYTES; if (write_buffer.size() < min_size) { write_buffer.resize(min_size); } size_t write_buffer_offset = 0; while (!messages_to_deliver.empty()) { std::shared_ptr<Message> const &message = messages_to_deliver.front(); size_t byte_size = message->ByteSize(); if (byte_size + MAX_VARINT_BYTES > write_buffer.size() - write_buffer_offset) { break; } #ifdef DEBUG std::cout << "message written" << std::endl; #endif auto it = CodedOutputStream::WriteVarint32ToArray(byte_size, write_buffer.data() + write_buffer_offset); write_buffer_offset = it - write_buffer.data(); bool written = message->SerializeToArray(write_buffer.data() + write_buffer_offset, byte_size); write_buffer_offset += byte_size; assert(written); messages_to_deliver.pop(); } auto ancor(shared_from_this()); async_write(socket, buffer(write_buffer.data(), write_buffer_offset), [this, ancor](boost::system::error_code ec, std::size_t) { if (ec) { #ifdef DEBUG std::cout << "error writing: " << ec.message() << std::endl; #endif chat.on_user_leave(shared_from_this()); return; } else { { boost::lock_guard<boost::mutex> guard(deliver_queue_mutex); if (messages_to_deliver.empty()) { write_in_progress = false; return; } } do_write(); } }); } private: ip::tcp::socket socket; chat_room &chat; io_service &service; std::vector<uint8> message_buffer; size_t buffer_offset; size_t buffer_red; std::vector<uint8> write_buffer; std::queue<std::shared_ptr<Message>> messages_to_deliver; boost::mutex deliver_queue_mutex; bool write_in_progress; }; class connection_handler { public: connection_handler(io_service &service, int port, chat_room &chat) : sock(service), service(service), acc(service, ip::tcp::endpoint(ip::tcp::v4(), port)), chat(chat) { } public: void accept_new_connection() { acc.async_accept(sock, [this](boost::system::error_code) { assert(sock.is_open()); chat.add_new_user(std::make_shared<user>(std::move(sock), chat, service)); accept_new_connection(); }); } private: ip::tcp::socket sock; io_service &service; ip::tcp::acceptor acc; chat_room &chat; }; int main(int argc, char *argv[]) { if (argc < 3) { std::cout << "Usage: ./chat_server $PORT_NUMBER$ $CONCURRENCY_LEVEL$" << std::endl << "Where $CONCURRENCY_LEVEL$ - number of the worker threads" << std::endl; return -1; } size_t port = std::atoi(argv[1]); size_t concurrency_level = std::atoi(argv[2]); try { std::cout << "Starting chat server on port " << port << " with concurrency level " << concurrency_level << " ..." << std::endl; io_service service(concurrency_level); chat_room chat; connection_handler handler(service, port, chat); handler.accept_new_connection(); boost::thread_group workers; auto const worker = boost::bind(&io_service::run, &service); for (size_t idx = 0; idx < concurrency_level; ++idx) { workers.create_thread(worker); } std::cout << "The server is started" << std::endl; std::cout << "Press 'enter' to stop the server" << std::endl; std::cin.get(); std::cout << "Stopping the server..." << std::endl; service.stop(); workers.join_all(); std::cout << "The server is stopped" << std::endl; } catch(std::exception &e) { std::cerr << "An exception occured with "; if (e.what()) { std::cerr << "message: \"" << e.what() << '"'; } else { std::cerr << "no message"; } std::cerr << std::endl; google::protobuf::ShutdownProtobufLibrary(); return -1; } google::protobuf::ShutdownProtobufLibrary(); return 0; } <|endoftext|>
<commit_before>#include "config.h" #include "object/Cube.hpp" #include <Corrade/PluginManager/Manager.h> #include <Corrade/Utility/Resource.h> #include <Magnum/Buffer.h> #include <Magnum/Context.h> #include <Magnum/DefaultFramebuffer.h> #include <Magnum/Math/Angle.h> #include <Magnum/Math/Complex.h> #include <Magnum/Mesh.h> #include <Magnum/Platform/Sdl2Application.h> #include <Magnum/Primitives/Cube.h> #include <Magnum/Renderer.h> #include <Magnum/SceneGraph/Camera.h> #include <Magnum/SceneGraph/Drawable.h> #include <Magnum/SceneGraph/MatrixTransformation3D.h> #include <Magnum/SceneGraph/Scene.h> #include <Magnum/Shaders/DistanceFieldVector.h> #include <Magnum/Shaders/Phong.h> #include <Magnum/Text/AbstractFont.h> #include <Magnum/Text/DistanceFieldGlyphCache.h> #include <Magnum/Text/Renderer.h> #include <Magnum/Timeline.h> #include <Magnum/Trade/MeshData3D.h> #include <Magnum/Version.h> #include <cstdlib> #include <functional> #include <memory> #include <tuple> using Magnum::Math::operator""_degf; using Magnum::Matrix3; using Magnum::Matrix4; using Magnum::Renderer; using BlendFunction = Magnum::Renderer::BlendFunction; using BlendEquation = Magnum::Renderer::BlendEquation; namespace SceneGraph = Magnum::SceneGraph; namespace Text = Magnum::Text; using Magnum::Vector2; using Magnum::Vector2i; using Magnum::Vector3; struct SimplePlatformer final : Magnum::Platform::Application { explicit SimplePlatformer(Arguments const &arguments) : Magnum::Platform::Application { arguments, Configuration() .setTitle("Simple Platformer") .setSize({1280, 720}) } , font_plugins{MAGNUM_PLUGINS_FONT_DIR} , glyph_cache{Vector2i{2048}, Vector2i{512}, 22} , text_mesh{Magnum::NoCreate} { Magnum::Debug() << "This application is running on" << Magnum::Context::current().version() << "using" << Magnum::Context::current().rendererString(); camera_object.translate(Vector3::zAxis(5.0f)); camera .setAspectRatioPolicy(SceneGraph::AspectRatioPolicy::Extend) .setProjectionMatrix(Matrix4::perspectiveProjection ( 35.0_degf, 4.0f/3.0f, 0.001f, 100.0f )) .setViewport(Magnum::defaultFramebuffer.viewport().size()); font = font_plugins.loadAndInstantiate("FreeTypeFont"); if(!font) { std::exit(EXIT_FAILURE); } Corrade::Utility::Resource res {"data"}; if(!font->openSingleData(res.getRaw("data/OpenSans/OpenSans-Regular.ttf"), 110.0f)) { Magnum::Error() << "Cannot open font file"; std::exit(EXIT_FAILURE); } font->fillGlyphCache(glyph_cache, " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:-+,.!'\"\\/[]{}<>()|"); std::tie(text_mesh, std::ignore) = Text::Renderer2D::render ( *font, glyph_cache, 0.1295f, "Hello, world!", vertexBuffer, indexBuffer, Magnum::BufferUsage::StaticDraw, Text::Alignment::MiddleCenter ); text_renderer = std::make_unique<Text::Renderer2D> ( *font, glyph_cache, 0.035f, Text::Alignment::TopRight ); text_renderer->reserve ( 40, Magnum::BufferUsage::DynamicDraw, Magnum::BufferUsage::StaticDraw ); Renderer::enable(Renderer::Feature::DepthTest); Renderer::enable(Renderer::Feature::FaceCulling); Renderer::enable(Renderer::Feature::Blending); Renderer::setBlendFunction(BlendFunction::One, BlendFunction::OneMinusSourceAlpha); Renderer::setBlendEquation(BlendEquation::Add, BlendEquation::Add); text_transform = Matrix3::rotation(Magnum::Deg(-10.0f)); text_project = Matrix3::scaling(Vector2::yScale(Vector2{Magnum::defaultFramebuffer.viewport().size()}.aspectRatio())); text_renderer->render("Simple Platformer"); transformation = Matrix4::rotationX(Magnum::Deg(30.0f)) * Matrix4::rotationY(Magnum::Deg(40.0f)); projection = Matrix4::perspectiveProjection ( Magnum::Deg(35.0f), Vector2(Magnum::defaultFramebuffer.viewport().size()).aspectRatio(), 0.01f, 100.0f ) * Matrix4::translation(Vector3::zAxis(-10.0f)); setSwapInterval(1); //enable VSync timeline.start(); } private: virtual void drawEvent() override { Magnum::defaultFramebuffer.clear(Magnum::FramebufferClear::Color|Magnum::FramebufferClear::Depth); camera.draw(drawables); text_shader.setVectorTexture(glyph_cache.texture()); text_shader .setTransformationProjectionMatrix(text_project * text_transform) .setColor(Magnum::Color3{1.0f}) .setOutlineColor(Magnum::Color3{0.0f, 0.7f, 0.0f}) .setOutlineRange(0.45f, 0.35f) .setSmoothness(0.025f); text_mesh.draw(text_shader); text_shader .setTransformationProjectionMatrix(text_project * Matrix3::translation(1.0f/text_project.rotationScaling().diagonal())) .setColor(Magnum::Color4{1.0f, 0.0f}) .setOutlineRange(0.5f, 1.0f) .setSmoothness(0.075f); text_renderer->mesh().draw(text_shader); swapBuffers(); redraw(); timeline.nextFrame(); } virtual void mousePressEvent(MouseEvent &e) override { if(e.button() != MouseEvent::Button::Left) return; previousMousePosition = e.position(); e.setAccepted(); } virtual void mouseMoveEvent(MouseMoveEvent &e) override { if(!(e.buttons() & MouseMoveEvent::Button::Left)) return; Vector2 delta = 3.0f * Vector2(e.position() - previousMousePosition) / Vector2(Magnum::defaultFramebuffer.viewport().size()); transformation = Matrix4::rotationX(Magnum::Rad(delta.y())) * transformation * Matrix4::rotationY(Magnum::Rad(delta.x())); previousMousePosition = e.position(); e.setAccepted(); redraw(); } Magnum::Timeline timeline; Magnum::Buffer indexBuffer, vertexBuffer; using Object3D = SceneGraph::Object<SceneGraph::MatrixTransformation3D>; using Scene3D = SceneGraph::Scene <SceneGraph::MatrixTransformation3D>; Scene3D scene; Object3D &camera_object {scene.addChild<Object3D>()}; SceneGraph::Camera3D &camera {camera_object.addFeature<SceneGraph::Camera3D>()}; SceneGraph::DrawableGroup3D drawables; simplat::object::Cube &cube {scene.addChild<simplat::object::Cube>(std::ref(drawables), std::cref(timeline))}; Corrade::PluginManager::Manager<Text::AbstractFont> font_plugins; std::unique_ptr<Text::AbstractFont> font; Text::DistanceFieldGlyphCache glyph_cache; Magnum::Mesh text_mesh; std::unique_ptr<Text::Renderer2D> text_renderer; Magnum::Shaders::DistanceFieldVector2D text_shader; Matrix3 text_transform, text_project; Matrix4 transformation, projection; Vector2i previousMousePosition; }; MAGNUM_APPLICATION_MAIN(SimplePlatformer); <commit_msg>Restore ability to rotate the cube<commit_after>#include "config.h" #include "object/Cube.hpp" #include <Corrade/PluginManager/Manager.h> #include <Corrade/Utility/Resource.h> #include <Magnum/Buffer.h> #include <Magnum/Context.h> #include <Magnum/DefaultFramebuffer.h> #include <Magnum/Math/Angle.h> #include <Magnum/Math/Complex.h> #include <Magnum/Mesh.h> #include <Magnum/Platform/Sdl2Application.h> #include <Magnum/Primitives/Cube.h> #include <Magnum/Renderer.h> #include <Magnum/SceneGraph/Camera.h> #include <Magnum/SceneGraph/Drawable.h> #include <Magnum/SceneGraph/MatrixTransformation3D.h> #include <Magnum/SceneGraph/Scene.h> #include <Magnum/Shaders/DistanceFieldVector.h> #include <Magnum/Shaders/Phong.h> #include <Magnum/Text/AbstractFont.h> #include <Magnum/Text/DistanceFieldGlyphCache.h> #include <Magnum/Text/Renderer.h> #include <Magnum/Timeline.h> #include <Magnum/Trade/MeshData3D.h> #include <Magnum/Version.h> #include <cstdlib> #include <functional> #include <memory> #include <tuple> using Magnum::Math::operator""_degf; using Magnum::Matrix3; using Magnum::Matrix4; using Magnum::Renderer; using BlendFunction = Magnum::Renderer::BlendFunction; using BlendEquation = Magnum::Renderer::BlendEquation; namespace SceneGraph = Magnum::SceneGraph; namespace Text = Magnum::Text; using Magnum::Vector2; using Magnum::Vector2i; using Magnum::Vector3; struct SimplePlatformer final : Magnum::Platform::Application { explicit SimplePlatformer(Arguments const &arguments) : Magnum::Platform::Application { arguments, Configuration() .setTitle("Simple Platformer") .setSize({1280, 720}) } , font_plugins{MAGNUM_PLUGINS_FONT_DIR} , glyph_cache{Vector2i{2048}, Vector2i{512}, 22} , text_mesh{Magnum::NoCreate} { Magnum::Debug() << "This application is running on" << Magnum::Context::current().version() << "using" << Magnum::Context::current().rendererString(); camera_object.translate(Vector3::zAxis(5.0f)); camera .setAspectRatioPolicy(SceneGraph::AspectRatioPolicy::Extend) .setViewport(Magnum::defaultFramebuffer.viewport().size()); font = font_plugins.loadAndInstantiate("FreeTypeFont"); if(!font) { std::exit(EXIT_FAILURE); } Corrade::Utility::Resource res {"data"}; if(!font->openSingleData(res.getRaw("data/OpenSans/OpenSans-Regular.ttf"), 110.0f)) { Magnum::Error() << "Cannot open font file"; std::exit(EXIT_FAILURE); } font->fillGlyphCache(glyph_cache, " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:-+,.!'\"\\/[]{}<>()|"); std::tie(text_mesh, std::ignore) = Text::Renderer2D::render ( *font, glyph_cache, 0.1295f, "Hello, world!", vertexBuffer, indexBuffer, Magnum::BufferUsage::StaticDraw, Text::Alignment::MiddleCenter ); text_renderer = std::make_unique<Text::Renderer2D> ( *font, glyph_cache, 0.035f, Text::Alignment::TopRight ); text_renderer->reserve ( 40, Magnum::BufferUsage::DynamicDraw, Magnum::BufferUsage::StaticDraw ); Renderer::enable(Renderer::Feature::DepthTest); Renderer::enable(Renderer::Feature::FaceCulling); Renderer::enable(Renderer::Feature::Blending); Renderer::setBlendFunction(BlendFunction::One, BlendFunction::OneMinusSourceAlpha); Renderer::setBlendEquation(BlendEquation::Add, BlendEquation::Add); text_transform = Matrix3::rotation(Magnum::Deg(-10.0f)); text_project = Matrix3::scaling(Vector2::yScale(Vector2{Magnum::defaultFramebuffer.viewport().size()}.aspectRatio())); text_renderer->render("Simple Platformer"); transformation = Matrix4::rotationX(Magnum::Deg(30.0f)) * Matrix4::rotationY(Magnum::Deg(40.0f)); cube.setTransformation(transformation); camera.setProjectionMatrix(Matrix4::perspectiveProjection ( Magnum::Deg(35.0f), Vector2(Magnum::defaultFramebuffer.viewport().size()).aspectRatio(), 0.01f, 100.0f ) * Matrix4::translation(Vector3::zAxis(-10.0f)) ); setSwapInterval(1); //enable VSync timeline.start(); } private: virtual void drawEvent() override { Magnum::defaultFramebuffer.clear(Magnum::FramebufferClear::Color|Magnum::FramebufferClear::Depth); camera.draw(drawables); text_shader.setVectorTexture(glyph_cache.texture()); text_shader .setTransformationProjectionMatrix(text_project * text_transform) .setColor(Magnum::Color3{1.0f}) .setOutlineColor(Magnum::Color3{0.0f, 0.7f, 0.0f}) .setOutlineRange(0.45f, 0.35f) .setSmoothness(0.025f); text_mesh.draw(text_shader); text_shader .setTransformationProjectionMatrix(text_project * Matrix3::translation(1.0f/text_project.rotationScaling().diagonal())) .setColor(Magnum::Color4{1.0f, 0.0f}) .setOutlineRange(0.5f, 1.0f) .setSmoothness(0.075f); text_renderer->mesh().draw(text_shader); swapBuffers(); redraw(); timeline.nextFrame(); } virtual void mousePressEvent(MouseEvent &e) override { if(e.button() != MouseEvent::Button::Left) return; previousMousePosition = e.position(); e.setAccepted(); } virtual void mouseMoveEvent(MouseMoveEvent &e) override { if(!(e.buttons() & MouseMoveEvent::Button::Left)) return; Vector2 delta = 3.0f * Vector2(e.position() - previousMousePosition) / Vector2(Magnum::defaultFramebuffer.viewport().size()); transformation = Matrix4::rotationX(Magnum::Rad(delta.y())) * transformation * Matrix4::rotationY(Magnum::Rad(delta.x())); cube.setTransformation(transformation); previousMousePosition = e.position(); e.setAccepted(); redraw(); } Magnum::Timeline timeline; Magnum::Buffer indexBuffer, vertexBuffer; using Object3D = SceneGraph::Object<SceneGraph::MatrixTransformation3D>; using Scene3D = SceneGraph::Scene <SceneGraph::MatrixTransformation3D>; Scene3D scene; Object3D &camera_object {scene.addChild<Object3D>()}; SceneGraph::Camera3D &camera {camera_object.addFeature<SceneGraph::Camera3D>()}; SceneGraph::DrawableGroup3D drawables; simplat::object::Cube &cube {scene.addChild<simplat::object::Cube>(std::ref(drawables), std::cref(timeline))}; Corrade::PluginManager::Manager<Text::AbstractFont> font_plugins; std::unique_ptr<Text::AbstractFont> font; Text::DistanceFieldGlyphCache glyph_cache; Magnum::Mesh text_mesh; std::unique_ptr<Text::Renderer2D> text_renderer; Magnum::Shaders::DistanceFieldVector2D text_shader; Matrix3 text_transform, text_project; Matrix4 transformation; Vector2i previousMousePosition; }; MAGNUM_APPLICATION_MAIN(SimplePlatformer); <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** $QT_END_LICENSE$ ** ****************************************************************************/ /**************************************************************************** ** ** Implementation of QInputContext class ** ** Copyright (C) 2003-2004 immodule for Qt Project. All rights reserved. ** ** This file is written to contribute to Nokia Corporation and/or its subsidiary(-ies) under their own ** license. You may use this file under your Qt license. Following ** description is copied from their original file headers. Contact ** [email protected] if any conditions of this licensing are ** not clear to you. ** ****************************************************************************/ //#define QT_NO_IM_PREEDIT_RELOCATION #include "qinputcontext.h" #include "qinputcontext_p.h" #ifndef QT_NO_IM #include "qplatformdefs.h" #include "qapplication.h" #include "qmenu.h" #include "qtextformat.h" #include "qpalette.h" #include <stdlib.h> #include <limits.h> QT_BEGIN_NAMESPACE /*! \class QInputContext \brief The QInputContext class abstracts the input method dependent data and composing state. \ingroup i18n An input method is responsible for inputting complex text that cannot be inputted via simple keymap. It converts a sequence of input events (typically key events) into a text string through the input method specific converting process. The class of the processes are widely ranging from simple finite state machine to complex text translator that pools a whole paragraph of a text with text editing capability to perform grammar and semantic analysis. To abstract such different input method specific intermediate information, Qt offers the QInputContext as base class. The concept is well known as 'input context' in the input method domain. An input context is created for a text widget in response to a demand. It is ensured that an input context is prepared for an input method before input to a text widget. Multiple input contexts that belong to a single input method may concurrently coexist. Suppose multi-window text editor. Each text widget of window A and B holds different QInputContext instance which contains different state information such as partially composed text. \section1 Groups of Functions \table \header \o Context \o Functions \row \o Receiving information \o x11FilterEvent(), filterEvent(), mouseHandler() \row \o Sending back composed text \o sendEvent() \row \o State change notification \o setFocusWidget(), reset() \row \o Context information \o identifierName(), language(), font(), isComposing() \endtable \legalese Copyright (C) 2003-2004 immodule for Qt Project. All rights reserved. This file is written to contribute to Nokia Corporation and/or its subsidiary(-ies) under their own license. You may use this file under your Qt license. Following description is copied from their original file headers. Contact [email protected] if any conditions of this licensing are not clear to you. \endlegalese \sa QInputContextPlugin, QInputContextFactory, QApplication::setInputContext() */ /*! Constructs an input context with the given \a parent. */ QInputContext::QInputContext(QObject* parent) : QObject(*new QInputContextPrivate, parent) { } /*! Destroys the input context. */ QInputContext::~QInputContext() { } /*! \internal Returns the widget that has an input focus for this input context. Ordinary input methods should not call this function directly to keep platform independence and flexible configuration possibility. The return value may differ from holderWidget() if the input context is shared between several text widgets. \sa setFocusWidget(), holderWidget() */ QWidget *QInputContext::focusWidget() const { Q_D(const QInputContext); return d->focusWidget; } /*! \internal Sets the widget that has an input focus for this input context. Ordinary input methods must not call this function directly. \sa focusWidget() */ void QInputContext::setFocusWidget(QWidget *widget) { Q_ASSERT(!widget || widget->testAttribute(Qt::WA_InputMethodEnabled)); Q_D(QInputContext); d->focusWidget = widget; } /*! \fn bool QInputContext::isComposing() const This function indicates whether InputMethodStart event had been sent to the current focus widget. It is ensured that an input context can send InputMethodCompose or InputMethodEnd event safely if this function returned true. The state is automatically being tracked through sendEvent(). \sa sendEvent() */ /*! This function can be reimplemented in a subclass to filter input events. Return true if the \a event has been consumed. Otherwise, the unfiltered \a event will be forwarded to widgets as ordinary way. Although the input events have accept() and ignore() methods, leave it untouched. \a event is currently restricted to events of these types: \list \i CloseSoftwareInputPanel \i KeyPress \i KeyRelease \i MouseButtonDblClick \i MouseButtonPress \i MouseButtonRelease \i MouseMove \i RequestSoftwareInputPanel \endlist But some input method related events such as QWheelEvent or QTabletEvent may be added in future. The filtering opportunity is always given to the input context as soon as possible. It has to be taken place before any other key event consumers such as eventfilters and accelerators because some input methods require quite various key combination and sequences. It often conflicts with accelerators and so on, so we must give the input context the filtering opportunity first to ensure all input methods work properly regardless of application design. Ordinary input methods require discrete key events to work properly, so Qt's key compression is always disabled for any input contexts. \sa QKeyEvent, x11FilterEvent() */ bool QInputContext::filterEvent(const QEvent * /*event*/) { return false; } /*! Sends an input method event specified by \a event to the current focus widget. Implementations of QInputContext should call this method to send the generated input method events and not QApplication::sendEvent(), as the events might have to get dispatched to a different application on some platforms. Some complex input methods route the handling to several child contexts (e.g. to enable language switching). To account for this, QInputContext will check if the parent object is a QInputContext. If yes, it will call the parents sendEvent() implementation instead of sending the event directly. \sa QInputMethodEvent */ void QInputContext::sendEvent(const QInputMethodEvent &event) { // route events over input context parents to make chaining possible. QInputContext *p = qobject_cast<QInputContext *>(parent()); if (p) { p->sendEvent(event); return; } QWidget *focus = focusWidget(); if (!focus) return; QInputMethodEvent e(event); QApplication::sendEvent(focus, &e); } /*! This function can be reimplemented in a subclass to handle mouse press, release, double-click, and move events within the preedit text. You can use the function to implement mouse-oriented user interface such as text selection or popup menu for candidate selection. The \a x parameter is the offset within the string that was sent with the InputMethodCompose event. The alteration boundary of \a x is ensured as character boundary of preedit string accurately. The \a event parameter is the event that was sent to the editor widget. The event type is QEvent::MouseButtonPress, QEvent::MouseButtonRelease, QEvent::MouseButtonDblClick or QEvent::MouseButtonMove. The event's button and state indicate the kind of operation that was performed. */ void QInputContext::mouseHandler(int /*x*/, QMouseEvent *event) { // Default behavior for simple ephemeral input contexts. Some // complex input contexts should not be reset here. if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonDblClick) reset(); } /*! Returns the font of the current input widget */ QFont QInputContext::font() const { Q_D(const QInputContext); if (!d->focusWidget) return QApplication::font(); return qvariant_cast<QFont>(d->focusWidget->inputMethodQuery(Qt::ImFont)); } /*! This virtual function is called when a state in the focus widget has changed. QInputContext can then use QWidget::inputMethodQuery() to query the new state of the widget. */ void QInputContext::update() { } /*! This virtual function is called when the specified \a widget is destroyed. The \a widget is a widget on which this input context is installed. */ void QInputContext::widgetDestroyed(QWidget *widget) { Q_D(QInputContext); if (widget == d->focusWidget) setFocusWidget(0); } /*! \fn void QInputContext::reset() This function can be reimplemented in a subclass to reset the state of the input method. This function is called by several widgets to reset input state. For example, a text widget call this function before inserting a text to make widget ready to accept a text. Default implementation is sufficient for simple input method. You can override this function to reset external input method engines in complex input method. In the case, call QInputContext::reset() to ensure proper termination of inputting. You must not send any QInputMethodEvent except empty InputMethodEnd event using QInputContext::reset() at reimplemented reset(). It will break input state consistency. */ /*! \fn QString QInputContext::identifierName() This function must be implemented in any subclasses to return the identifier name of the input method. Return value is the name to identify and specify input methods for the input method switching mechanism and so on. The name has to be consistent with QInputContextPlugin::keys(). The name has to consist of ASCII characters only. There are two different names with different responsibility in the input method domain. This function returns one of them. Another name is called 'display name' that stands for the name for endusers appeared in a menu and so on. \sa QInputContextPlugin::keys(), QInputContextPlugin::displayName() */ /*! \fn QString QInputContext::language() This function must be implemented in any subclasses to return a language code (e.g. "zh_CN", "zh_TW", "zh_HK", "ja", "ko", ...) of the input context. If the input context can handle multiple languages, return the currently used one. The name has to be consistent with QInputContextPlugin::language(). This information will be used by language tagging feature in QInputMethodEvent. It is required to distinguish unified han characters correctly. It enables proper font and character code handling. Suppose CJK-awared multilingual web browser (that automatically modifies fonts in CJK-mixed text) and XML editor (that automatically inserts lang attr). */ /*! This is a preliminary interface for Qt 4. */ QList<QAction *> QInputContext::actions() { return QList<QAction *>(); } /*! \enum QInputContext::StandardFormat \value PreeditFormat The preedit text. \value SelectionFormat The selection text. \sa standardFormat() */ /*! Returns a QTextFormat object that specifies the format for component \a s. */ QTextFormat QInputContext::standardFormat(StandardFormat s) const { QWidget *focus = focusWidget(); const QPalette &pal = focus ? focus->palette() : QApplication::palette(); QTextCharFormat fmt; QColor bg; switch (s) { case QInputContext::PreeditFormat: { fmt.setUnderlineStyle(QTextCharFormat::DashUnderline); break; } case QInputContext::SelectionFormat: { bg = pal.text().color(); fmt.setBackground(QBrush(bg)); fmt.setForeground(pal.background()); break; } } return fmt; } #ifdef Q_WS_X11 /*! This function may be overridden only if input method is depending on X11 and you need raw XEvent. Otherwise, this function must not. This function is designed to filter raw key events for XIM, but other input methods may use this to implement some special features such as distinguishing Shift_L and Shift_R. Return true if the \a event has been consumed. Otherwise, the unfiltered \a event will be translated into QEvent and forwarded to filterEvent(). Filtering at both x11FilterEvent() and filterEvent() in single input method is allowed. \a keywidget is a client widget into which a text is inputted. \a event is inputted XEvent. \sa filterEvent() */ bool QInputContext::x11FilterEvent(QWidget * /*keywidget*/, XEvent * /*event*/) { return false; } #endif // Q_WS_X11 #ifdef Q_WS_S60 /*! This function may be overridden only if input method is depending on Symbian and you need raw TWsEvent. Otherwise, this function must not. This function is designed to filter raw key events on S60, but other input methods may use this to implement some special features. Return true if the \a event has been consumed. Otherwise, the unfiltered \a event will be translated into QEvent and forwarded to filterEvent(). Filtering at both s60FilterEvent() and filterEvent() in single input method is allowed. \a keywidget is a client widget into which a text is inputted. \a event is inputted TWsEvent. \sa filterEvent() */ bool QInputContext::s60FilterEvent(QWidget * /*keywidget*/, TWsEvent * /*event*/) { return false; } #endif // Q_WS_S60 QT_END_NAMESPACE #endif //Q_NO_IM <commit_msg>Doc: Added a section to tidy things up. This document needs more work.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** $QT_END_LICENSE$ ** ****************************************************************************/ /**************************************************************************** ** ** Implementation of QInputContext class ** ** Copyright (C) 2003-2004 immodule for Qt Project. All rights reserved. ** ** This file is written to contribute to Nokia Corporation and/or its subsidiary(-ies) under their own ** license. You may use this file under your Qt license. Following ** description is copied from their original file headers. Contact ** [email protected] if any conditions of this licensing are ** not clear to you. ** ****************************************************************************/ //#define QT_NO_IM_PREEDIT_RELOCATION #include "qinputcontext.h" #include "qinputcontext_p.h" #ifndef QT_NO_IM #include "qplatformdefs.h" #include "qapplication.h" #include "qmenu.h" #include "qtextformat.h" #include "qpalette.h" #include <stdlib.h> #include <limits.h> QT_BEGIN_NAMESPACE /*! \class QInputContext \brief The QInputContext class abstracts the input method dependent data and composing state. \ingroup i18n An input method is responsible for inputting complex text that cannot be inputted via simple keymap. It converts a sequence of input events (typically key events) into a text string through the input method specific converting process. The class of the processes are widely ranging from simple finite state machine to complex text translator that pools a whole paragraph of a text with text editing capability to perform grammar and semantic analysis. To abstract such different input method specific intermediate information, Qt offers the QInputContext as base class. The concept is well known as 'input context' in the input method domain. An input context is created for a text widget in response to a demand. It is ensured that an input context is prepared for an input method before input to a text widget. Multiple input contexts that belong to a single input method may concurrently coexist. Suppose multi-window text editor. Each text widget of window A and B holds different QInputContext instance which contains different state information such as partially composed text. \section1 Groups of Functions \table \header \o Context \o Functions \row \o Receiving information \o x11FilterEvent(), filterEvent(), mouseHandler() \row \o Sending back composed text \o sendEvent() \row \o State change notification \o setFocusWidget(), reset() \row \o Context information \o identifierName(), language(), font(), isComposing() \endtable \section1 Licensing Information \legalese Copyright (C) 2003-2004 immodule for Qt Project. All rights reserved. This file is written to contribute to Nokia Corporation and/or its subsidiary(-ies) under their own license. You may use this file under your Qt license. Following description is copied from their original file headers. Contact [email protected] if any conditions of this licensing are not clear to you. \endlegalese \sa QInputContextPlugin, QInputContextFactory, QApplication::setInputContext() */ /*! Constructs an input context with the given \a parent. */ QInputContext::QInputContext(QObject* parent) : QObject(*new QInputContextPrivate, parent) { } /*! Destroys the input context. */ QInputContext::~QInputContext() { } /*! \internal Returns the widget that has an input focus for this input context. Ordinary input methods should not call this function directly to keep platform independence and flexible configuration possibility. The return value may differ from holderWidget() if the input context is shared between several text widgets. \sa setFocusWidget(), holderWidget() */ QWidget *QInputContext::focusWidget() const { Q_D(const QInputContext); return d->focusWidget; } /*! \internal Sets the widget that has an input focus for this input context. Ordinary input methods must not call this function directly. \sa focusWidget() */ void QInputContext::setFocusWidget(QWidget *widget) { Q_ASSERT(!widget || widget->testAttribute(Qt::WA_InputMethodEnabled)); Q_D(QInputContext); d->focusWidget = widget; } /*! \fn bool QInputContext::isComposing() const This function indicates whether InputMethodStart event had been sent to the current focus widget. It is ensured that an input context can send InputMethodCompose or InputMethodEnd event safely if this function returned true. The state is automatically being tracked through sendEvent(). \sa sendEvent() */ /*! This function can be reimplemented in a subclass to filter input events. Return true if the \a event has been consumed. Otherwise, the unfiltered \a event will be forwarded to widgets as ordinary way. Although the input events have accept() and ignore() methods, leave it untouched. \a event is currently restricted to events of these types: \list \i CloseSoftwareInputPanel \i KeyPress \i KeyRelease \i MouseButtonDblClick \i MouseButtonPress \i MouseButtonRelease \i MouseMove \i RequestSoftwareInputPanel \endlist But some input method related events such as QWheelEvent or QTabletEvent may be added in future. The filtering opportunity is always given to the input context as soon as possible. It has to be taken place before any other key event consumers such as eventfilters and accelerators because some input methods require quite various key combination and sequences. It often conflicts with accelerators and so on, so we must give the input context the filtering opportunity first to ensure all input methods work properly regardless of application design. Ordinary input methods require discrete key events to work properly, so Qt's key compression is always disabled for any input contexts. \sa QKeyEvent, x11FilterEvent() */ bool QInputContext::filterEvent(const QEvent * /*event*/) { return false; } /*! Sends an input method event specified by \a event to the current focus widget. Implementations of QInputContext should call this method to send the generated input method events and not QApplication::sendEvent(), as the events might have to get dispatched to a different application on some platforms. Some complex input methods route the handling to several child contexts (e.g. to enable language switching). To account for this, QInputContext will check if the parent object is a QInputContext. If yes, it will call the parents sendEvent() implementation instead of sending the event directly. \sa QInputMethodEvent */ void QInputContext::sendEvent(const QInputMethodEvent &event) { // route events over input context parents to make chaining possible. QInputContext *p = qobject_cast<QInputContext *>(parent()); if (p) { p->sendEvent(event); return; } QWidget *focus = focusWidget(); if (!focus) return; QInputMethodEvent e(event); QApplication::sendEvent(focus, &e); } /*! This function can be reimplemented in a subclass to handle mouse press, release, double-click, and move events within the preedit text. You can use the function to implement mouse-oriented user interface such as text selection or popup menu for candidate selection. The \a x parameter is the offset within the string that was sent with the InputMethodCompose event. The alteration boundary of \a x is ensured as character boundary of preedit string accurately. The \a event parameter is the event that was sent to the editor widget. The event type is QEvent::MouseButtonPress, QEvent::MouseButtonRelease, QEvent::MouseButtonDblClick or QEvent::MouseButtonMove. The event's button and state indicate the kind of operation that was performed. */ void QInputContext::mouseHandler(int /*x*/, QMouseEvent *event) { // Default behavior for simple ephemeral input contexts. Some // complex input contexts should not be reset here. if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonDblClick) reset(); } /*! Returns the font of the current input widget */ QFont QInputContext::font() const { Q_D(const QInputContext); if (!d->focusWidget) return QApplication::font(); return qvariant_cast<QFont>(d->focusWidget->inputMethodQuery(Qt::ImFont)); } /*! This virtual function is called when a state in the focus widget has changed. QInputContext can then use QWidget::inputMethodQuery() to query the new state of the widget. */ void QInputContext::update() { } /*! This virtual function is called when the specified \a widget is destroyed. The \a widget is a widget on which this input context is installed. */ void QInputContext::widgetDestroyed(QWidget *widget) { Q_D(QInputContext); if (widget == d->focusWidget) setFocusWidget(0); } /*! \fn void QInputContext::reset() This function can be reimplemented in a subclass to reset the state of the input method. This function is called by several widgets to reset input state. For example, a text widget call this function before inserting a text to make widget ready to accept a text. Default implementation is sufficient for simple input method. You can override this function to reset external input method engines in complex input method. In the case, call QInputContext::reset() to ensure proper termination of inputting. You must not send any QInputMethodEvent except empty InputMethodEnd event using QInputContext::reset() at reimplemented reset(). It will break input state consistency. */ /*! \fn QString QInputContext::identifierName() This function must be implemented in any subclasses to return the identifier name of the input method. Return value is the name to identify and specify input methods for the input method switching mechanism and so on. The name has to be consistent with QInputContextPlugin::keys(). The name has to consist of ASCII characters only. There are two different names with different responsibility in the input method domain. This function returns one of them. Another name is called 'display name' that stands for the name for endusers appeared in a menu and so on. \sa QInputContextPlugin::keys(), QInputContextPlugin::displayName() */ /*! \fn QString QInputContext::language() This function must be implemented in any subclasses to return a language code (e.g. "zh_CN", "zh_TW", "zh_HK", "ja", "ko", ...) of the input context. If the input context can handle multiple languages, return the currently used one. The name has to be consistent with QInputContextPlugin::language(). This information will be used by language tagging feature in QInputMethodEvent. It is required to distinguish unified han characters correctly. It enables proper font and character code handling. Suppose CJK-awared multilingual web browser (that automatically modifies fonts in CJK-mixed text) and XML editor (that automatically inserts lang attr). */ /*! This is a preliminary interface for Qt 4. */ QList<QAction *> QInputContext::actions() { return QList<QAction *>(); } /*! \enum QInputContext::StandardFormat \value PreeditFormat The preedit text. \value SelectionFormat The selection text. \sa standardFormat() */ /*! Returns a QTextFormat object that specifies the format for component \a s. */ QTextFormat QInputContext::standardFormat(StandardFormat s) const { QWidget *focus = focusWidget(); const QPalette &pal = focus ? focus->palette() : QApplication::palette(); QTextCharFormat fmt; QColor bg; switch (s) { case QInputContext::PreeditFormat: { fmt.setUnderlineStyle(QTextCharFormat::DashUnderline); break; } case QInputContext::SelectionFormat: { bg = pal.text().color(); fmt.setBackground(QBrush(bg)); fmt.setForeground(pal.background()); break; } } return fmt; } #ifdef Q_WS_X11 /*! This function may be overridden only if input method is depending on X11 and you need raw XEvent. Otherwise, this function must not. This function is designed to filter raw key events for XIM, but other input methods may use this to implement some special features such as distinguishing Shift_L and Shift_R. Return true if the \a event has been consumed. Otherwise, the unfiltered \a event will be translated into QEvent and forwarded to filterEvent(). Filtering at both x11FilterEvent() and filterEvent() in single input method is allowed. \a keywidget is a client widget into which a text is inputted. \a event is inputted XEvent. \sa filterEvent() */ bool QInputContext::x11FilterEvent(QWidget * /*keywidget*/, XEvent * /*event*/) { return false; } #endif // Q_WS_X11 #ifdef Q_WS_S60 /*! This function may be overridden only if input method is depending on Symbian and you need raw TWsEvent. Otherwise, this function must not. This function is designed to filter raw key events on S60, but other input methods may use this to implement some special features. Return true if the \a event has been consumed. Otherwise, the unfiltered \a event will be translated into QEvent and forwarded to filterEvent(). Filtering at both s60FilterEvent() and filterEvent() in single input method is allowed. \a keywidget is a client widget into which a text is inputted. \a event is inputted TWsEvent. \sa filterEvent() */ bool QInputContext::s60FilterEvent(QWidget * /*keywidget*/, TWsEvent * /*event*/) { return false; } #endif // Q_WS_S60 QT_END_NAMESPACE #endif //Q_NO_IM <|endoftext|>
<commit_before>#include "render/buffer2d.h" #include "core/assert.h" #include "core/bufferbuilder2d.h" #include "core/cint.h" #include "render/shaderattribute2d.h" namespace euphoria::render { Buffer2d::Buffer2d(const core::BufferBuilder2d& bb) : index_count(core::Csizet_to_int(bb.tris.size())) { PointLayout::Bind(&vao); VertexBuffer::Bind(&vbo); vbo.SetData(bb.data); IndexBuffer::Bind(&ebo); ebo.SetData(bb.tris); vao.BindData(attributes2d::Vertex(), sizeof(float) * 4, 0); PointLayout::Bind(nullptr); IndexBuffer::Bind(nullptr); VertexBuffer::Bind(nullptr); } void Buffer2d::Draw() const { PointLayout::Bind(&vao); ebo.Draw(RenderMode::Triangles, index_count); PointLayout::Bind(nullptr); } } <commit_msg>engine/shooter not asserting at boot anymore<commit_after>#include "render/buffer2d.h" #include "core/assert.h" #include "core/bufferbuilder2d.h" #include "core/cint.h" #include "render/shaderattribute2d.h" namespace euphoria::render { Buffer2d::Buffer2d(const core::BufferBuilder2d& bb) : index_count(core::Csizet_to_int(bb.tris.size())) { PointLayout::Bind(&vao); VertexBuffer::Bind(&vbo); vbo.SetData(bb.data); IndexBuffer::Bind(&ebo); ebo.SetData(bb.tris); vao.BindData(attributes2d::Vertex(), sizeof(float) * 4, 0); PointLayout::Bind(nullptr); IndexBuffer::Bind(nullptr); VertexBuffer::Bind(nullptr); } void Buffer2d::Draw() const { IndexBuffer::Bind(&ebo); PointLayout::Bind(&vao); ebo.Draw(RenderMode::Triangles, index_count); PointLayout::Bind(nullptr); IndexBuffer::Bind(nullptr); } } <|endoftext|>
<commit_before>#include "types.h" #include "query.h" #include "util.h" #include "version.h" #include "globals.h" #include "snmp.h" using namespace std; void help(); // Setup and initialization. // Display usage. void help() { cerr << "clpoll version " << CLPOLL_VERSION << endl; cerr << " -c <file> Specify configuration file [" << rtgconf << "]" << endl; cerr << " -D Don't detach, run in foreground" << endl; cerr << " -d Disable database inserts" << endl; cerr << " -t <file> Specify target file [" << targets << "]" << endl; cerr << " -v Increase verbosity" << endl; cerr << " -z Database zero delta inserts" << endl; cerr << " -ql <num> Maximum database queue length [" << max_queue_length << "]" << endl; cerr << " Copyright (c) 2009-2010 Jakob Borg" << endl; } // Parse command line, load caonfiguration and start threads. int main (int argc, char * const argv[]) { if (argc < 2) { help(); exit(0); } for (int i = 1; i < argc; i++) { string arg = string(argv[i]); if (arg == "-v") verbosity++; else if (arg == "-D") detach = 0; else if (arg == "-d") use_db = 0; else if (arg == "-z") allow_db_zero = 1; else if (arg == "-h") { help(); exit(0); } else if (arg == "-c") { i++; rtgconf = string(argv[i]); } else if (arg == "-t") { i++; targets = string(argv[i]); } else if (arg == "-ql") { i++; max_queue_length = atoi(argv[i]); } } if (detach) daemonize(); global_snmp_init(); // Read rtg.conf config = read_rtg_conf(rtgconf); // Read targets.cfg hosts = read_rtg_targets(targets, config); if (hosts.size() == 0) { cerr << "No hosts, so nothing to do." << endl; exit(-1); } // Calculate number of database writers needed. This is just a guess. unsigned num_dbthreads = config.threads / 8; num_dbthreads = num_dbthreads ? num_dbthreads : 1; // Allocate result cache for the number of hosts in targets.cfg cache = vector<ResultCache>(hosts.size()); // Allocate the number of threads specified in rtg.conf pthread_t threads[config.threads]; pthread_t dbthreads[num_dbthreads]; pthread_t monitor; if (verbosity >= 1) { cerr << "Polling every " << config.interval << " seconds." << endl; cerr << "Starting poll with " << config.threads << " threads." << endl; } // Start the pollers for (unsigned i = 0; i < config.threads; i++) { pthread_create(&threads[i], NULL, poller_thread, NULL); } // Let them start sleep(1); // Start the database writers for (unsigned i = 0; i < num_dbthreads; i++) { pthread_create(&dbthreads[i], NULL, database_thread, NULL); } // Let them start sleep(1); // Start the monitor pthread_create(&monitor, NULL, monitor_thread, NULL); // Wait for them (forever, currently) for (unsigned i = 0; i < config.threads; i++) { pthread_join(threads[i], NULL); } for (unsigned i = 0; i < num_dbthreads; i++) { pthread_join(dbthreads[i], NULL); } pthread_join(monitor, NULL); return 0; } <commit_msg>Only daemonize after initialization is complete.<commit_after>#include "types.h" #include "query.h" #include "util.h" #include "version.h" #include "globals.h" #include "snmp.h" using namespace std; void help(); // Setup and initialization. // Display usage. void help() { cerr << "clpoll version " << CLPOLL_VERSION << endl; cerr << " -c <file> Specify configuration file [" << rtgconf << "]" << endl; cerr << " -D Don't detach, run in foreground" << endl; cerr << " -d Disable database inserts" << endl; cerr << " -t <file> Specify target file [" << targets << "]" << endl; cerr << " -v Increase verbosity" << endl; cerr << " -z Database zero delta inserts" << endl; cerr << " -ql <num> Maximum database queue length [" << max_queue_length << "]" << endl; cerr << " Copyright (c) 2009-2010 Jakob Borg" << endl; } // Parse command line, load caonfiguration and start threads. int main (int argc, char * const argv[]) { if (argc < 2) { help(); exit(0); } for (int i = 1; i < argc; i++) { string arg = string(argv[i]); if (arg == "-v") verbosity++; else if (arg == "-D") detach = 0; else if (arg == "-d") use_db = 0; else if (arg == "-z") allow_db_zero = 1; else if (arg == "-h") { help(); exit(0); } else if (arg == "-c") { i++; rtgconf = string(argv[i]); } else if (arg == "-t") { i++; targets = string(argv[i]); } else if (arg == "-ql") { i++; max_queue_length = atoi(argv[i]); } } global_snmp_init(); // Read rtg.conf config = read_rtg_conf(rtgconf); // Read targets.cfg hosts = read_rtg_targets(targets, config); if (hosts.size() == 0) { cerr << "No hosts, so nothing to do." << endl; exit(-1); } // Calculate number of database writers needed. This is just a guess. unsigned num_dbthreads = config.threads / 8; num_dbthreads = num_dbthreads ? num_dbthreads : 1; // Allocate result cache for the number of hosts in targets.cfg cache = vector<ResultCache>(hosts.size()); // Allocate the number of threads specified in rtg.conf pthread_t threads[config.threads]; pthread_t dbthreads[num_dbthreads]; pthread_t monitor; if (verbosity >= 1) { cerr << "Polling every " << config.interval << " seconds." << endl; cerr << "Starting poll with " << config.threads << " threads." << endl; } if (detach) daemonize(); // Start the pollers for (unsigned i = 0; i < config.threads; i++) { pthread_create(&threads[i], NULL, poller_thread, NULL); } // Let them start sleep(1); // Start the database writers for (unsigned i = 0; i < num_dbthreads; i++) { pthread_create(&dbthreads[i], NULL, database_thread, NULL); } // Let them start sleep(1); // Start the monitor pthread_create(&monitor, NULL, monitor_thread, NULL); // Wait for them (forever, currently) for (unsigned i = 0; i < config.threads; i++) { pthread_join(threads[i], NULL); } for (unsigned i = 0; i < num_dbthreads; i++) { pthread_join(dbthreads[i], NULL); } pthread_join(monitor, NULL); return 0; } <|endoftext|>
<commit_before>#include "optimize.hpp" std::vector<std::vector<cv::vec2r> > image_all_pts; std::vector<std::vector<cv::vec2r> > image_all_norm_pts; std::vector<cv::matrixr> K_mats; cv::vec2r *image_pts; cv::vec3r *model_pts; real_t *A_mat; real_t *K_mat; real_t *k_vec; bool g_no_skew; bool g_fixed_aspect; unsigned a_param_count; void ext_reprojection_fcn(int m, int n, real_t* x, real_t* fvec,int *iflag) { if (*iflag == 0) return; // calculate m_projected cv::matrixr A(3, 3, A_mat); cv::matrixr K(3, 4, x); cv::vec2r image_pt_proj; for (int i = 0; i < m; ++i) { // pack model (world) 3D point. cv::vectorr model = { model_pts[i][0], model_pts[i][1], 0.0, 1.0}; auto proj_ptn = (A*K) * model; proj_ptn /= proj_ptn[2]; // calculate projection error auto x_d = image_pts[i][0] - proj_ptn[0]; auto y_d = image_pts[i][1] - proj_ptn[1]; x_d*=x_d; y_d*=y_d; fvec[i] = sqrt(x_d + y_d); } } int optimize_extrinsics(const std::vector<cv::vec2r> &image_points, const std::vector<cv::vec3r> &model_points, const cv::matrixr &A, cv::matrixr &K, real_t tol) { ASSERT(image_points.size() == model_points.size() && !image_points.empty()); image_pts = const_cast<cv::vec2r*>(image_points.data()); model_pts = const_cast<cv::vec3r*>(model_points.data()); A_mat = const_cast<real_t*>(A.data_begin()); int m = image_points.size(); int n = 12; // K.size int info; cv::vectorr _K(12); for (int i = 0; i < 12; ++i) { _K[i] = K.data_begin()[i]; } if((info = cv::lmdif1(ext_reprojection_fcn, m, n, _K.data(), tol))) { for (int i = 0; i < 12; ++i) { K.data_begin()[i] = _K[i]; } } else { std::cout << "Extrinsic optimization failed." << std::endl; } return info; } void pack_k_data(const cv::vectorr &k, real_t data[8]) { ASSERT(k.length() == 2 || k.length() == 4 || k.length() == 8); switch(k.length()) { case 2: data[0] = k[0]; data[1] = k[1]; data[2] = 0.; // k[2] data[3] = 0.; // k[3] data[4] = 0.; // k[4] data[5] = 0.; // k[5] data[6] = 0.; // p[0] data[7] = 0.; // p[1] break; case 4: data[0] = k[0]; data[1] = k[1]; data[2] = 0.; // k[2] data[3] = 0.; // k[3] data[4] = 0.; // k[4] data[5] = 0.; // k[5] data[6] = k[2]; // p[0] data[7] = k[3]; // p[1] break; case 8: data[0] = k[0]; data[1] = k[1]; data[2] = k[2]; // k[2] data[3] = k[3]; // k[3] data[4] = k[4]; // k[4] data[5] = k[5]; // k[5] data[6] = k[6]; // p[0] data[7] = k[7]; // p[1] break; default: break; } } cv::vectorr unpack_k_data(real_t data[8]) { cv::vectorr k(8); k[0] = data[0]; k[1] = data[1]; k[2] = data[2]; k[3] = data[3]; k[4] = data[4]; k[5] = data[5]; k[6] = data[6]; k[7] = data[7]; return k; } void distorion_reprojection_fcn(int m, int n, real_t* x, real_t* fvec,int *iflag) { if (*iflag == 0) return; // calculate m_projected cv::matrixr A(3, 3, A_mat); cv::vectorr k(x, x, 8, 1); unsigned f_i = 0; for (unsigned i = 0; i < image_all_pts.size(); ++i) { for (unsigned j = 0; j < image_all_pts[i].size(); ++j, ++f_i) { // pack model (world) 3D point. cv::vectorr model = { model_pts[j][0], model_pts[j][1], 0.0, 1.0}; auto proj_ptn = reproject_point(model, A, K_mats[i], k); // calculate projection error auto x_d = image_all_pts[i][j][0] - proj_ptn[0]; auto y_d = image_all_pts[i][j][1] - proj_ptn[1]; x_d*=x_d; y_d*=y_d; fvec[f_i] = sqrt(x_d + y_d); } } } int optimize_distortion(const std::vector<std::vector<cv::vec2r>> &image_points, const std::vector<cv::vec3r> &model_points, const cv::matrixr &A, const std::vector<cv::matrixr> &K, cv::vectorr &k, real_t tol) { ASSERT(k.length() == 2 || k.length() == 4 || k.length() == 8); image_all_pts = image_points; model_pts = const_cast<cv::vec3r*>(model_points.data()); A_mat = const_cast<real_t*>(A.data_begin()); K_mats = K; int m = image_points.size()*image_points[0].size(); int n = 2; int info = 0; real_t data[8]; pack_k_data(k, data); if((info = cv::lmdif1(distorion_reprojection_fcn, m, n, data, tol))) { k = unpack_k_data(data); } else { std::cout << "Distortion optimization did not converge" << std::endl; } return info; } cv::matrixr construct_a(real_t *x) { cv::matrixr A(3, 3); if (g_fixed_aspect) { if (g_no_skew) { A(0, 0) = x[0]; A(1, 1) = x[0]; A(0, 2) = x[1]; A(1, 2) = x[2]; A(0, 1) = 0; } else { A(0, 0) = x[0]; A(1, 1) = x[0]; A(0, 1) = x[1]; A(0, 2) = x[2]; A(1, 2) = x[3]; } } else { if (g_no_skew) { A(0, 0) = x[0]; A(0, 2) = x[1]; A(1, 1) = x[2]; A(1, 2) = x[3]; A(0, 1) = 0; } else { A(0, 0) = x[0]; A(0, 1) = x[1]; A(0, 2) = x[2]; A(1, 1) = x[3]; A(1, 2) = x[4]; } } A(1, 0) = A(2, 0) = A(2, 1) = 0; A(2, 2) = 1; return A; } void all_reprojection_fcn(int m, int n, real_t* x, real_t* fvec,int *iflag) { if (*iflag == 0) { return; } // calculate m_projected auto A = construct_a(x); auto k_x = x + n - 8; cv::vectorr k(k_x, k_x, 8, 1); unsigned f_i = 0; for (unsigned i = 0; i < image_all_pts.size(); ++i) { cv::matrixr K(3, 4, (x + a_param_count + (i * 12))); for (unsigned j = 0; j < image_all_pts[i].size(); ++j, ++f_i) { // pack model (world) 3D point. cv::vectorr model = { model_pts[j][0], model_pts[j][1], 0.0, 1.0}; auto proj_ptn = reproject_point(model, A, K, k); // calculate projection error auto x_d = image_all_pts[i][j][0] - proj_ptn[0]; auto y_d = image_all_pts[i][j][1] - proj_ptn[1]; x_d*=x_d; y_d*=y_d; fvec[f_i] = sqrt(x_d + y_d); } } } int optimize_calib(const std::vector<std::vector<cv::vec2r>> &image_points, const std::vector<cv::vec3r> &model_points, cv::matrixr &A, std::vector<cv::matrixr> &K, cv::vectorr &k, bool fixed_aspect, bool no_skew, real_t tol) { image_all_pts = image_points; model_pts = const_cast<cv::vec3r*>(model_points.data()); A_mat = const_cast<real_t*>(A.data_begin()); g_fixed_aspect = fixed_aspect; g_no_skew = no_skew; a_param_count = fixed_aspect ? 3 : 4; a_param_count += no_skew ? 0 : 1; int m = image_points.size()*image_points[0].size(); int n = a_param_count + (K.size()*12) + 8; // A{a, b, c, u0, v0} + K + k; int info = 0; auto *data = new real_t[n]; if (fixed_aspect) { if (no_skew) { data[0] = (A(0, 0) + A(1, 1)) / 2; data[1] = A(0, 2); data[2] = A(1, 2); } else { data[0] = (A(0, 0) + A(1, 1)) / 2; data[1] = A(0, 1); data[2] = A(0, 2); data[3] = A(1, 2); } } else { if (no_skew) { data[0] = A(0, 0); data[1] = A(0, 2); data[2] = A(1, 1); data[3] = A(1, 2); } else { data[0] = A(0, 0); data[1] = A(0, 1); data[2] = A(0, 2); data[3] = A(1, 1); data[4] = A(1, 2); } } for (unsigned b = 0; b < K.size(); ++b) { for (unsigned i = 0; i < 12; ++i) { data[a_param_count + (b * 12) + i] = K[b].data_begin()[i]; } } auto k_str = data + (n - 8); pack_k_data(k, k_str); if((info = cv::lmdif1(all_reprojection_fcn, m, n, data, tol))) { A = construct_a(data); for (unsigned b = 0; b < K.size(); ++b) { cv::matrixr K_(3, 4, (data + a_param_count + (b * 12))); K[b] = K_.clone(); } k = unpack_k_data(k_str); } else { std::cout << "Optimization failed." << std::endl; } delete [] data; return info; } <commit_msg>fixed optimizations<commit_after>#include "optimize.hpp" std::vector<std::vector<cv::vec2r> > image_all_pts; std::vector<std::vector<cv::vec2r> > image_all_norm_pts; std::vector<cv::matrixr> K_mats; cv::vec2r *image_pts; cv::vec3r *model_pts; real_t *A_mat; real_t *K_mat; real_t *k_vec; bool g_no_skew; bool g_fixed_aspect; unsigned a_param_count; void ext_reprojection_fcn(int m, int n, real_t* x, real_t* fvec,int *iflag) { if (*iflag == 0) return; // calculate m_projected cv::matrixr A(3, 3, A_mat); cv::matrixr K(3, 4, x); cv::vec2r image_pt_proj; for (int i = 0; i < m; ++i) { // pack model (world) 3D point. cv::vectorr model = { model_pts[i][0], model_pts[i][1], 0.0, 1.0}; auto proj_ptn = (A*K) * model; proj_ptn /= proj_ptn[2]; // calculate projection error auto x_d = image_pts[i][0] - proj_ptn[0]; auto y_d = image_pts[i][1] - proj_ptn[1]; x_d*=x_d; y_d*=y_d; fvec[i] = sqrt(x_d + y_d); } } int optimize_extrinsics(const std::vector<cv::vec2r> &image_points, const std::vector<cv::vec3r> &model_points, const cv::matrixr &A, cv::matrixr &K, real_t tol) { ASSERT(image_points.size() == model_points.size() && !image_points.empty()); image_pts = const_cast<cv::vec2r*>(image_points.data()); model_pts = const_cast<cv::vec3r*>(model_points.data()); A_mat = const_cast<real_t*>(A.data_begin()); int m = image_points.size(); int n = 12; // K.size int info; cv::vectorr _K(12); for (int i = 0; i < 12; ++i) { _K[i] = K.data_begin()[i]; } if((info = cv::lmdif1(ext_reprojection_fcn, m, n, _K.data(), tol))) { for (int i = 0; i < 12; ++i) { K.data_begin()[i] = _K[i]; } } else { std::cout << "Extrinsic optimization failed." << std::endl; } return info; } void pack_k_data(const cv::vectorr &k, real_t data[8]) { ASSERT(k.length() == 2 || k.length() == 4 || k.length() == 8); switch(k.length()) { case 2: data[0] = k[0]; data[1] = k[1]; data[2] = 0.; // k[2] data[3] = 0.; // k[3] data[4] = 0.; // k[4] data[5] = 0.; // k[5] data[6] = 0.; // p[0] data[7] = 0.; // p[1] break; case 4: data[0] = k[0]; data[1] = k[1]; data[2] = 0.; // k[2] data[3] = 0.; // k[3] data[4] = 0.; // k[4] data[5] = 0.; // k[5] data[6] = k[2]; // p[0] data[7] = k[3]; // p[1] break; case 8: data[0] = k[0]; data[1] = k[1]; data[2] = k[2]; // k[2] data[3] = k[3]; // k[3] data[4] = k[4]; // k[4] data[5] = k[5]; // k[5] data[6] = k[6]; // p[0] data[7] = k[7]; // p[1] break; default: break; } } cv::vectorr unpack_k_data(real_t data[8]) { cv::vectorr k(8); k[0] = data[0]; k[1] = data[1]; k[2] = data[2]; k[3] = data[3]; k[4] = data[4]; k[5] = data[5]; k[6] = data[6]; k[7] = data[7]; return k; } void distorion_reprojection_fcn(int m, int n, real_t* x, real_t* fvec,int *iflag) { if (*iflag == 0) return; // calculate m_projected cv::matrixr A(3, 3, A_mat); cv::vectorr k(x, x, 8, 1); unsigned f_i = 0; for (unsigned i = 0; i < image_all_pts.size(); ++i) { for (unsigned j = 0; j < image_all_pts[i].size(); ++j, ++f_i) { // pack model (world) 3D point. cv::vectorr model = { model_pts[j][0], model_pts[j][1], 0.0, 1.0}; auto proj_ptn = reproject_point(model, A, K_mats[i], k); // calculate projection error auto x_d = image_all_pts[i][j][0] - proj_ptn[0]; auto y_d = image_all_pts[i][j][1] - proj_ptn[1]; x_d*=x_d; y_d*=y_d; fvec[f_i] = sqrt(x_d + y_d); } } } int optimize_distortion(const std::vector<std::vector<cv::vec2r>> &image_points, const std::vector<cv::vec3r> &model_points, const cv::matrixr &A, const std::vector<cv::matrixr> &K, cv::vectorr &k, real_t tol) { ASSERT(k.length() == 2 || k.length() == 4 || k.length() == 8); image_all_pts = image_points; model_pts = const_cast<cv::vec3r*>(model_points.data()); A_mat = const_cast<real_t*>(A.data_begin()); K_mats = K; int m = image_points.size()*image_points[0].size(); int n = 2; int info = 0; real_t data[8]; pack_k_data(k, data); if((info = cv::lmdif1(distorion_reprojection_fcn, m, n, data, tol))) { k = unpack_k_data(data); } else { std::cout << "Distortion optimization did not converge" << std::endl; } return info; } cv::matrixr construct_a(real_t *x) { cv::matrixr A(3, 3); if (g_fixed_aspect) { if (g_no_skew) { A(0, 0) = x[0]; A(1, 1) = x[0]; A(0, 2) = x[1]; A(1, 2) = x[2]; A(0, 1) = 0; } else { A(0, 0) = x[0]; A(1, 1) = x[0]; A(0, 1) = x[1]; A(0, 2) = x[2]; A(1, 2) = x[3]; } } else { if (g_no_skew) { A(0, 0) = x[0]; A(0, 2) = x[1]; A(1, 1) = x[2]; A(1, 2) = x[3]; A(0, 1) = 0; } else { A(0, 0) = x[0]; A(0, 1) = x[1]; A(0, 2) = x[2]; A(1, 1) = x[3]; A(1, 2) = x[4]; } } A(1, 0) = A(2, 0) = A(2, 1) = 0; A(2, 2) = 1; return A; } void all_reprojection_fcn(int m, int n, real_t* x, real_t* fvec,int *iflag) { if (*iflag == 0) { return; } // calculate m_projected auto A = construct_a(x); auto k_x = x + n - 8; cv::vectorr k(k_x, k_x, 8, 1); unsigned f_i = 0; for (unsigned i = 0; i < image_all_pts.size(); ++i) { cv::matrixr K(3, 4, (x + a_param_count + (i * 12))); for (unsigned j = 0; j < image_all_pts[i].size(); ++j, ++f_i) { // pack model (world) 3D point. cv::vectorr model = { model_pts[j][0], model_pts[j][1], 0.0, 1.0}; auto proj_ptn = reproject_point(model, A, K, k); // calculate projection error auto x_d = image_all_pts[i][j][0] - proj_ptn[0]; auto y_d = image_all_pts[i][j][1] - proj_ptn[1]; x_d*=x_d; y_d*=y_d; fvec[f_i] = sqrt(x_d + y_d); } } } int optimize_calib(const std::vector<std::vector<cv::vec2r>> &image_points, const std::vector<cv::vec3r> &model_points, cv::matrixr &A, std::vector<cv::matrixr> &K, cv::vectorr &k, bool fixed_aspect, bool no_skew, real_t tol) { image_all_pts = image_points; model_pts = const_cast<cv::vec3r*>(model_points.data()); A_mat = const_cast<real_t*>(A.data_begin()); g_fixed_aspect = fixed_aspect; g_no_skew = no_skew; a_param_count = fixed_aspect ? 3 : 4; a_param_count += no_skew ? 0 : 1; int m = image_points.size()*image_points[0].size(); int n = a_param_count + (K.size()*12) + 8; // A{a, b, c, u0, v0} + K + k; int info = 0; auto *data = new real_t[n]; if (fixed_aspect) { if (no_skew) { data[0] = (A(0, 0) + A(1, 1)) / 2; data[1] = A(0, 2); data[2] = A(1, 2); } else { data[0] = (A(0, 0) + A(1, 1)) / 2; data[1] = A(0, 1); data[2] = A(0, 2); data[3] = A(1, 2); } } else { if (no_skew) { data[0] = A(0, 0); data[1] = A(0, 2); data[2] = A(1, 1); data[3] = A(1, 2); } else { data[0] = A(0, 0); data[1] = A(0, 1); data[2] = A(0, 2); data[3] = A(1, 1); data[4] = A(1, 2); } } for (unsigned b = 0; b < K.size(); ++b) { for (unsigned i = 0; i < 12; ++i) { data[a_param_count + (b * 12) + i] = K[b].data_begin()[i]; } } auto k_str = data + (n - 8); pack_k_data(k, k_str); if((info = cv::lmdif1(all_reprojection_fcn, m, n, data, tol))) { A = construct_a(data); for (unsigned b = 0; b < K.size(); ++b) { cv::matrixr K_(3, 4, (data + a_param_count + (b * 12))); K[b] = K_.clone(); } k = unpack_k_data(k_str); } else { std::cout << "Optimization failed." << std::endl; } delete [] data; return info; } <|endoftext|>
<commit_before>#include <algorithm> #include <string> #include <iostream> #include <opencv2/opencv.hpp> #include <tesseract/baseapi.h> #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> using namespace cv; using namespace std; namespace fs = boost::filesystem; bool compareContours(vector<Point> a, vector<Point> b) { return contourArea(a) > contourArea(b); } int main(int argc, char** argv) { // namedWindow("Window", CV_WINDOW_AUTOSIZE); const int BYTES_PER_PIXEL = 1; const string DATA_PATH = "/Users/Mike/Documents/Eclipse Workspace/Steam Captcha Breaker/Debug/data/"; int total = 0; int success = 0; fs::path folder(DATA_PATH); if(!exists(folder)) return -1; fs::directory_iterator endItr; for(fs::directory_iterator itr(folder); itr != endItr; itr++) { total++; string fullPath = itr->path().string(); string fileName = itr->path().filename().string(); string captchaCode = boost::replace_all_copy(fileName, ".png", ""); boost::replace_all(captchaCode, "at", "@"); boost::replace_all(captchaCode, "pct", "%"); boost::replace_all(captchaCode, "and", "&"); cout << total << ".) file: " << fileName << ", code: " << captchaCode; // Load our base image Mat sourceImage = imread(fullPath, CV_LOAD_IMAGE_GRAYSCALE); // Is it loaded correctly? if(!sourceImage.data) return -1; // Define our final image Mat finalImage; // Let's do some image operations threshold(sourceImage, finalImage, 150, 255, THRESH_BINARY); //adaptiveThreshold(sourceImage, finalImage, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 3, 0); // Let's find contours vector<vector<Point> > contours; findContours(finalImage, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); // Sort them by size sort(contours.begin(), contours.end(), compareContours); // Draw 6 largest contours finalImage.setTo(Scalar(0)); int contourCount = MIN(contours.size(), 6); for(int contourIndex = 0; contourIndex < contourCount; contourIndex++) drawContours(finalImage, contours, contourIndex, Scalar(255), CV_FILLED); // Initiate tesseract tesseract::TessBaseAPI tess; tess.Init(NULL, "eng", tesseract::OEM_DEFAULT); tess.SetVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ@%&"); tess.SetImage((uchar *) finalImage.data, finalImage.cols, finalImage.rows, BYTES_PER_PIXEL, BYTES_PER_PIXEL * finalImage.cols); string result(tess.GetUTF8Text()); result.erase(remove_if(result.begin(), result.end(), ::isspace ), result.end()); cout << ", result: " << result; if(captchaCode == result) { cout << " - TRUE" << endl; success++; } else { cout << " - FALSE" << endl; } // imshow("Source", sourceImage); // imshow("Final", finalImage); // waitKey(); sourceImage.release(); finalImage.release(); contours.clear(); } cout << "Success rate: " << ((double)success/(double)total)*100 << "% (" << success << "/" << total << ")." << endl; return 0; } <commit_msg>Added character segmentation.<commit_after>#include <algorithm> #include <string> #include <iostream> #include <opencv2/opencv.hpp> #include <tesseract/baseapi.h> #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include "imagereconstruct.hpp" #define SMOKETEST 0 using namespace std; using namespace cv; namespace fs = boost::filesystem; int dynamicThreshold = 100; string windowName = "Steam Captcha Breaker"; Mat sourceImage, finalImage, histImage; Mat hist; bool compareContours(vector<Point> a, vector<Point> b); void applyThreshold(int, void*); void createHistogram(int threshold); bool compareContours(vector<Point> a, vector<Point> b) { return contourArea(a) > contourArea(b); } void createHistogram(Mat& src, int threshold) { int histSize = 256; float range[] = { 0, 256 }; const float *ranges[] = { range }; calcHist(&src, 1, 0, Mat(), hist, 1, &histSize, ranges, true, false); // Let's draw our histogram int histHeight = 512; int histWidth = 512; int widthBucket = cvRound((double) histWidth/histSize); histImage = Mat(histHeight, histWidth, CV_32FC3, Scalar(0)); normalize(hist, hist, 0, histImage.rows, NORM_MINMAX, -1, Mat()); for(int i = 1; i < histSize; i++) { line(histImage, Point(widthBucket * (i - 1), histHeight - cvRound(hist.at<float>(i - 1))) , Point(widthBucket * i, histHeight - cvRound(hist.at<float>(i))), Scalar(255, 255, 255), 1); } line(histImage, Point(widthBucket * threshold, 0), Point(widthBucket * threshold, histHeight - 1), Scalar(0, 255, 0), 1); } int* horizontalSegments(Mat& src) { int* seg = (int*) calloc(src.cols, sizeof(int)); for(int i = 0; i < src.cols; i++) { for(int k = 0; k < src.rows; k++) { uchar pixel = src.data[src.cols * k + i]; if(pixel) seg[i]++; } } return seg; } Mat drawHorizontalSegments(int* seg, int rows, int cols) { Mat segImage = Mat(rows, cols, CV_8U, Scalar(0)); for(int i = 0; i < cols; i++) { if(seg[i] > 0) line(segImage, Point(i, rows - 1), Point(i, rows - 1 - seg[i]), Scalar(255), 1); } return segImage; } int* verticalSegments(Mat& src) { int* seg = (int*) calloc(src.rows, sizeof(int)); for(int i = 0; i < src.rows; i++) { for(int k = 0; k < src.cols; k++) { uchar pixel = src.data[src.cols * i + k]; if(pixel) seg[i]++; } } return seg; } Mat drawVerticalSegments(int* seg, int rows, int cols) { Mat segImage = Mat(rows, cols, CV_8U, Scalar(0)); for(int i = 0; i < rows; i++) { if(seg[i] > 0) line(segImage, Point(0, i), Point(seg[i], i), Scalar(255), 1); } return segImage; } vector<pair<int, int> > createSegmentPairs(int* seg, int segSize) { int top = 0, bottom = 0; bool in = false; vector<pair<int, int> > pairs; for(int i = 0; i < segSize; i++) { if(seg[i]) in = true; else in = false; if(in) { if(!top) { top = i; bottom = i; } else { bottom = i; } // corner case if(i == segSize - 1) { pairs.push_back(make_pair(top, bottom)); top = bottom = 0; } } else { if(top && bottom) { pairs.push_back(make_pair(top, bottom)); top = bottom = 0; } } } return pairs; } void applyThreshold(int, void*) { threshold(sourceImage, finalImage, dynamicThreshold, 255, THRESH_BINARY); createHistogram(sourceImage, dynamicThreshold); imshow("Histogram", histImage); imshow(windowName, finalImage); } Mat applyCanny(Mat& src, int threshold) { Mat edges, tmp; Canny(src, edges, threshold, threshold * 3, 3); src.copyTo(tmp, edges); tmp.copyTo(src); edges.release(); tmp.release(); return src; } int main(int argc, char** argv) { const int BYTES_PER_PIXEL = 1; const int RESIZE_FACTOR = 2; const string DATA_PATH = "/Users/Mike/Documents/Eclipse Workspace/SCB3/data/"; int total = 0; int success = 0; fs::path folder(DATA_PATH); if(!exists(folder)) return -1; fs::directory_iterator endItr; for(fs::directory_iterator itr(folder); itr != endItr; itr++) { string fullPath = itr->path().string(); string fileName = itr->path().filename().string(); // Skip all dot files if(fileName[0] == '.') continue; // Retrieve captcha string string captchaCode = boost::replace_all_copy(fileName, ".png", ""); boost::replace_all(captchaCode, "at", "@"); boost::replace_all(captchaCode, "pct", "%"); boost::replace_all(captchaCode, "and", "&"); total++; cout << total << ".) file: " << fileName << ", code: " << captchaCode; // Load our base image sourceImage = imread(fullPath, CV_LOAD_IMAGE_GRAYSCALE); // Is it loaded? if(!sourceImage.data) return -1; resize(sourceImage, sourceImage, Size(sourceImage.cols * RESIZE_FACTOR, sourceImage.rows * RESIZE_FACTOR)); // Normalize our image normalize(finalImage, finalImage, 0, 255, NORM_MINMAX, CV_8U); // Define our final image finalImage = sourceImage.clone(); // Apply adaptive threshold adaptiveThreshold(finalImage, finalImage, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 3, 1); Mat tmp; sourceImage.copyTo(tmp, finalImage); tmp.copyTo(finalImage); normalize(finalImage, finalImage, 0, 255, NORM_MINMAX, CV_8U); // Let's apply image reconstruction // finalImage -= 30; // ImageReconstruct<unsigned char>(finalImage, sourceImage); // imshow("Test", (sourceImage - finalImage) * 1); // Let's calculate histogram for our image createHistogram(finalImage, dynamicThreshold); int thresholdValueLow = 0; for(int i = 0; i < 256; i++) { if(cvRound(hist.at<float>(i)) > 10) { thresholdValueLow = i; #if SMOKETEST == 0 cout << "LOW: " << thresholdValueLow << endl; #endif } } // Calculate final threshold value int thresholdValue = thresholdValueLow + (int)((255 - thresholdValueLow) / 10 * 4); #if SMOKETEST == 0 cout << "THRESH: " << thresholdValue << endl; #endif // Apply threshold threshold(finalImage, finalImage, thresholdValue, 255, THRESH_BINARY); // Segments int* segH = horizontalSegments(finalImage); int* segV = verticalSegments(finalImage); Mat segHImage = drawHorizontalSegments(segH, finalImage.rows, finalImage.cols); Mat segVImage = drawVerticalSegments(segV, finalImage.rows, finalImage.cols); // Let's draw the rectangles vector<pair<int, int> > verticalPairs = createSegmentPairs(segV, finalImage.rows); vector<pair<int, int> > horizontalPairs = createSegmentPairs(segH, finalImage.cols); for(vector<pair<int, int> >::iterator itV = verticalPairs.begin(); itV != verticalPairs.end(); itV++) { for(vector<pair<int, int> >::iterator itH = horizontalPairs.begin(); itH != horizontalPairs.end(); itH++) { rectangle(finalImage, Point(itH->first, itV->first), Point(itH->second, itV->second), Scalar(255)); } } // // Let's find contours // vector<vector<Point> > contours; // Mat contourImage = finalImage.clone(); // findContours(contourImage, contours, CV_RETR_TREE, CV_CHAIN_APPROX_NONE); // // // Sort them by size // sort(contours.begin(), contours.end(), compareContours); // // // Hide noise by filling it with black color // int contourCount = MIN((int) contours.size(), 6); // if(contours.size() > contourCount) { // for(int contourIndex = contourCount; contourIndex < contours.size(); contourIndex++) { // drawContours(finalImage, contours, contourIndex, Scalar(0), CV_FILLED); // } // } // Initiate tesseract tesseract::TessBaseAPI tess; tess.Init(NULL, "eng", tesseract::OEM_DEFAULT); tess.SetVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ@%&"); tess.SetImage((uchar *) finalImage.data, finalImage.cols, finalImage.rows, BYTES_PER_PIXEL, BYTES_PER_PIXEL * finalImage.cols); // Retrieve the result and remove all spaces string result(tess.GetUTF8Text()); result.erase(remove_if(result.begin(), result.end(), ::isspace), result.end()); cout << ", result: " << result; if(captchaCode == result) { cout << " - TRUE" << endl; success++; } else { cout << " - FALSE" << endl; } // Resize back // resize(sourceImage, sourceImage, Size(sourceImage.cols / RESIZE_FACTOR, sourceImage.rows / RESIZE_FACTOR)); // resize(finalImage, finalImage, Size(finalImage.cols / RESIZE_FACTOR, finalImage.rows / RESIZE_FACTOR)); #if SMOKETEST == 0 // namedWindow(windowName); // finalImage.copyTo(sourceImage); // // createTrackbar("Value", windowName, &dynamicThreshold, 255, applyThreshold); // // applyThreshold(0, 0); // // while(true) // { // int c; // c = waitKey(); // if((char)c == 27) break; // } imshow("Final image", finalImage); imshow("HSeg", segHImage); imshow("VSeg", segVImage); waitKey(); #endif sourceImage.release(); finalImage.release(); // contourImage.release(); // contours.clear(); #if SMOKETEST == 0 if(total == 10) break; #endif } cout << "Success rate: " << ((double)success/(double)total)*100 << "% (" << success << "/" << total << ")." << endl; return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include <stdexcept> #include <string> #include <chrono> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <linux/i2c-dev.h> using namespace ::std; class I2CBus { public: I2CBus(unsigned _busId) :m_busFd(-1), m_busPath() { ostringstream busDevName; busDevName << "/dev/i2c-" << _busId; m_busPath = busDevName.str(); m_busFd = ::open(m_busPath.c_str(), O_RDWR | O_SYNC); if (m_busFd == -1) { ostringstream os; os << "cannot open i2c bus device " << m_busPath; throw runtime_error(os.str()); } } ~I2CBus() { if (m_busFd != -1) ::close(m_busFd); } int fd() const { return m_busFd; } const string& path() const { return m_busPath; } private: int m_busFd; string m_busPath; }; class I2CDevice { public: I2CDevice(unsigned _busId, unsigned _deviceId) :m_i2cBus(_busId) { if (ioctl(m_i2cBus.fd(), I2C_SLAVE, &_deviceId) != 0) { ostringstream os; os << "cannot select i2c slave device " << _deviceId << ", bus " << m_i2cBus.path(); throw runtime_error(os.str()); } } template <typename UInt, size_t _bytes = sizeof(UInt)> bool readUInt(UInt& _data) { uint8_t dataBuf[_bytes]; if (::read(m_i2cBus.fd(), dataBuf, sizeof(dataBuf)) != sizeof(dataBuf)) return false; _data = UInt(); for (size_t idx = 0; idx < _bytes; ++idx) _data |= static_cast<UInt>(dataBuf[idx]) << (idx*8); return true; } template <typename UInt, size_t _bytes = sizeof(UInt)> bool writeUInt(const UInt& _data) { uint8_t dataBuf[_bytes]; for (size_t idx = 0; idx < _bytes; ++idx) dataBuf[idx] = static_cast<uint8_t>(_data >> (idx*8)); if (::write(m_i2cBus.fd(), dataBuf, sizeof(dataBuf)) != sizeof(dataBuf)) return false; return true; } private: I2CBus m_i2cBus; }; class MSPControl { public: MSPControl(unsigned _busId, unsigned _deviceId) :m_i2cDevice(_busId, _deviceId) { } unsigned readWord(unsigned _addr) { uint8_t addr = static_cast<uint8_t>(_addr); if (!m_i2cDevice.writeUInt(addr)) { ostringstream os; os << "cannot write cmd"; throw runtime_error(os.str()); } uint16_t result; if (!m_i2cDevice.readUInt(result)) { ostringstream os; os << "cannot read result"; throw runtime_error(os.str()); } return result; } private: I2CDevice m_i2cDevice; }; class GPIOControl { public: GPIOControl(unsigned _gpio) :m_gpioFd(-1), m_gpioPath() { ostringstream gpioCtrlName; gpioCtrlName << "/sys/class/gpio/gpio" << _gpio << "/value"; m_gpioPath = gpioCtrlName.str(); m_gpioFd = ::open(m_gpioPath.c_str(), O_RDWR | O_SYNC); if (m_gpioFd == -1) { ostringstream os; os << "cannot open gpio control " << m_gpioPath; throw runtime_error(os.str()); } } ~GPIOControl() { if (m_gpioFd != -1) ::close(m_gpioFd); } void setValue(unsigned _val) { ostringstream valueStream; valueStream << _val << endl; const string& value = valueStream.str(); if (::write(m_gpioFd, value.c_str(), value.length()) != value.length()) { ostringstream os; os << "cannot set gpio value " << m_gpioPath; throw runtime_error(os.str()); } } const string& path() const { return m_gpioPath; } private: int m_gpioFd; string m_gpioPath; }; class TrikCoilGun { public: TrikCoilGun(unsigned _mspBusId, unsigned _mspDeviceId, unsigned _mspChargeLevelCmd, unsigned _mspDischargeCurrentCmd, unsigned _gpioChargeControl, unsigned _gpioDischargeControl) :m_mspControl(_mspBusId, _mspDeviceId), m_mspCmdChargeLevel(_mspChargeLevelCmd), m_mspCmdDischargeCurrent(_mspDischargeCurrentCmd), m_gpioChargeControl(_gpioChargeControl), m_gpioDischargeControl(_gpioDischargeControl) { m_gpioChargeControl.setValue(0); m_gpioDischargeControl.setValue(0); } ~TrikCoilGun() { m_gpioChargeControl.setValue(0); m_gpioDischargeControl.setValue(0); } void charge(unsigned _durationMs, unsigned _chargeLevel) { const chrono::steady_clock::time_point& startAt = chrono::steady_clock::now(); const bool waitCharge = _durationMs == 0; const chrono::steady_clock::time_point& elapseAt = startAt + chrono::duration<chrono::steady_clock::rep, chrono::milliseconds::period>(_durationMs); #if 1 cerr << "Preparing for charge" << endl; bool charging = false; #endif while (true) { if (!waitCharge && chrono::steady_clock::now() >= elapseAt) break; if (m_mspControl.readWord(m_mspCmdChargeLevel) >= _chargeLevel) { #if 1 if (charging) cerr << "Stop charging" << endl; charging = false; #endif if (waitCharge) break; m_gpioChargeControl.setValue(0); } else { #if 1 if (!charging) cerr << "Charging" << endl; charging = true; #endif m_gpioChargeControl.setValue(1); } usleep(1000); } #if 1 cerr << "Charge done" << endl; #endif m_gpioChargeControl.setValue(0); } void discharge(unsigned _durationMs, unsigned _zeroChargeLevel) { const chrono::steady_clock::time_point& startAt = chrono::steady_clock::now(); const bool waitDischarge = _durationMs == 0; const chrono::steady_clock::time_point& elapseAt = startAt + chrono::duration<chrono::steady_clock::rep, chrono::milliseconds::period>(_durationMs); #if 1 cerr << "Preparing for discharge" << endl; #endif while (true) { if (!waitDischarge && chrono::steady_clock::now() >= elapseAt) break; if (m_mspControl.readWord(m_mspCmdChargeLevel) <= _zeroChargeLevel) { #if 1 cerr << "Discharged" << endl; #endif break; } m_gpioDischargeControl.setValue(1); usleep(1000); } #if 1 cerr << "Discharge done" << endl; #endif m_gpioDischargeControl.setValue(0); } void fire(unsigned _preDelayMs, unsigned _durationMs, unsigned _postDelayMs) { m_gpioChargeControl.setValue(0); usleep(_preDelayMs * 1000); m_gpioDischargeControl.setValue(1); usleep(_durationMs * 1000); m_gpioChargeControl.setValue(0); usleep(_postDelayMs * 1000); } private: MSPControl m_mspControl; unsigned m_mspCmdChargeLevel; unsigned m_mspCmdDischargeCurrent; GPIOControl m_gpioChargeControl; GPIOControl m_gpioDischargeControl; }; #if 0 static int s_chargeLevel = 0; static int s_chargeDurationMs = 0; static int s_fireDurationMs = 10; static int s_dischargeDelayMs = 100; static int s_dischargeDurationMs = 0; static int s_dischargeLevel = 0; #endif int main() { TrikCoilGun coilGun(0,0,0,0,0,0); coilGun.charge(1000, 0); coilGun.fire(10, 10, 100); coilGun.discharge(1000, 0); } <commit_msg>Finished coilgun code, to be tested now<commit_after>#include <iostream> #include <sstream> #include <stdexcept> #include <string> #include <chrono> #include <unistd.h> #include <fcntl.h> #include <getopt.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <linux/i2c-dev.h> using namespace ::std; class I2CBus { public: I2CBus(unsigned _busId) :m_busFd(-1), m_busPath() { ostringstream busDevName; busDevName << "/dev/i2c-" << _busId; m_busPath = busDevName.str(); m_busFd = ::open(m_busPath.c_str(), O_RDWR | O_SYNC); if (m_busFd == -1) { ostringstream os; os << "cannot open i2c bus device " << m_busPath; throw runtime_error(os.str()); } } ~I2CBus() { if (m_busFd != -1) ::close(m_busFd); } int fd() const { return m_busFd; } const string& path() const { return m_busPath; } private: int m_busFd; string m_busPath; }; class I2CDevice { public: I2CDevice(unsigned _busId, unsigned _deviceId) :m_i2cBus(_busId) { if (ioctl(m_i2cBus.fd(), I2C_SLAVE, &_deviceId) != 0) { ostringstream os; os << "cannot select i2c slave device " << _deviceId << ", bus " << m_i2cBus.path(); throw runtime_error(os.str()); } } template <typename UInt, size_t _bytes = sizeof(UInt)> bool readUInt(UInt& _data) { uint8_t dataBuf[_bytes]; if (::read(m_i2cBus.fd(), dataBuf, sizeof(dataBuf)) != sizeof(dataBuf)) return false; _data = UInt(); for (size_t idx = 0; idx < _bytes; ++idx) _data |= static_cast<UInt>(dataBuf[idx]) << (idx*8); return true; } template <typename UInt, size_t _bytes = sizeof(UInt)> bool writeUInt(const UInt& _data) { uint8_t dataBuf[_bytes]; for (size_t idx = 0; idx < _bytes; ++idx) dataBuf[idx] = static_cast<uint8_t>(_data >> (idx*8)); if (::write(m_i2cBus.fd(), dataBuf, sizeof(dataBuf)) != sizeof(dataBuf)) return false; return true; } private: I2CBus m_i2cBus; }; class MSPControl { public: MSPControl(unsigned _busId, unsigned _deviceId) :m_i2cDevice(_busId, _deviceId) { } unsigned readWord(unsigned _addr) { uint8_t addr = static_cast<uint8_t>(_addr); if (!m_i2cDevice.writeUInt(addr)) { ostringstream os; os << "cannot write cmd"; throw runtime_error(os.str()); } uint16_t result; if (!m_i2cDevice.readUInt(result)) { ostringstream os; os << "cannot read result"; throw runtime_error(os.str()); } return result; } private: I2CDevice m_i2cDevice; }; class GPIOControl { public: GPIOControl(unsigned _gpio) :m_gpioFd(-1), m_gpioPath() { ostringstream gpioCtrlName; gpioCtrlName << "/sys/class/gpio/gpio" << _gpio << "/value"; m_gpioPath = gpioCtrlName.str(); m_gpioFd = ::open(m_gpioPath.c_str(), O_RDWR | O_SYNC); if (m_gpioFd == -1) { ostringstream os; os << "cannot open gpio control " << m_gpioPath; throw runtime_error(os.str()); } } ~GPIOControl() { if (m_gpioFd != -1) ::close(m_gpioFd); } void setValue(unsigned _val) { ostringstream valueStream; valueStream << _val << endl; const string& value = valueStream.str(); if (::write(m_gpioFd, value.c_str(), value.length()) != value.length()) { ostringstream os; os << "cannot set gpio value " << m_gpioPath; throw runtime_error(os.str()); } } const string& path() const { return m_gpioPath; } private: int m_gpioFd; string m_gpioPath; }; class TrikCoilGun { public: TrikCoilGun(unsigned _mspBusId, unsigned _mspDeviceId, unsigned _mspChargeLevelCmd, unsigned _mspDischargeCurrentCmd, unsigned _gpioChargeControl, unsigned _gpioDischargeControl) :m_mspControl(_mspBusId, _mspDeviceId), m_mspCmdChargeLevel(_mspChargeLevelCmd), m_mspCmdDischargeCurrent(_mspDischargeCurrentCmd), m_gpioChargeControl(_gpioChargeControl), m_gpioDischargeControl(_gpioDischargeControl) { m_gpioChargeControl.setValue(0); m_gpioDischargeControl.setValue(0); } ~TrikCoilGun() { m_gpioChargeControl.setValue(0); m_gpioDischargeControl.setValue(0); } void charge(unsigned _durationMs, unsigned _chargeLevel) { const chrono::steady_clock::time_point& startAt = chrono::steady_clock::now(); const bool waitCharge = _durationMs == 0; const chrono::steady_clock::time_point& elapseAt = startAt + chrono::duration<chrono::steady_clock::rep, chrono::milliseconds::period>(_durationMs); #if 1 cerr << "Preparing for charge" << endl; bool charging = false; #endif while (true) { if (!waitCharge && chrono::steady_clock::now() >= elapseAt) break; if (m_mspControl.readWord(m_mspCmdChargeLevel) >= _chargeLevel) { #if 1 if (charging) cerr << "Stop charging" << endl; charging = false; #endif if (waitCharge) break; m_gpioChargeControl.setValue(0); } else { #if 1 if (!charging) cerr << "Charging" << endl; charging = true; #endif m_gpioChargeControl.setValue(1); } usleep(1000); } #if 1 cerr << "Charge done" << endl; #endif m_gpioChargeControl.setValue(0); } void discharge(unsigned _durationMs, unsigned _zeroChargeLevel) { const chrono::steady_clock::time_point& startAt = chrono::steady_clock::now(); const bool waitDischarge = _durationMs == 0; const chrono::steady_clock::time_point& elapseAt = startAt + chrono::duration<chrono::steady_clock::rep, chrono::milliseconds::period>(_durationMs); #if 1 cerr << "Preparing for discharge" << endl; #endif while (true) { if (!waitDischarge && chrono::steady_clock::now() >= elapseAt) break; if (m_mspControl.readWord(m_mspCmdChargeLevel) <= _zeroChargeLevel) { #if 1 cerr << "Discharged" << endl; #endif break; } m_gpioDischargeControl.setValue(1); usleep(1000); } #if 1 cerr << "Discharge done" << endl; #endif m_gpioDischargeControl.setValue(0); } void fire(unsigned _preDelayMs, unsigned _durationMs, unsigned _postDelayMs) { m_gpioChargeControl.setValue(0); usleep(_preDelayMs * 1000); m_gpioDischargeControl.setValue(1); usleep(_durationMs * 1000); m_gpioChargeControl.setValue(0); usleep(_postDelayMs * 1000); } private: MSPControl m_mspControl; unsigned m_mspCmdChargeLevel; unsigned m_mspCmdDischargeCurrent; GPIOControl m_gpioChargeControl; GPIOControl m_gpioDischargeControl; }; int printUsageHelp() { #warning TODO return 1; } int main(int _argc, char* const _argv[]) { static const char* s_optstring = "h"; static const struct option s_longopts[] = { { "help", no_argument, NULL, 0}, { "msp-i2c-bus", required_argument, NULL, 0}, // 1 { "msp-i2c-device", required_argument, NULL, 0}, { "msp-i2c-charge-level", required_argument, NULL, 0}, { "msp-i2c-discharge-current", required_argument, NULL, 0}, { "gpio-charge", required_argument, NULL, 0}, // 5 { "gpio-discharge", required_argument, NULL, 0}, { "charge-duration", required_argument, NULL, 0}, // 7 { "charge-level", required_argument, NULL, 0}, { "fire-predelay", required_argument, NULL, 0}, // 9 { "fire-duration", required_argument, NULL, 0}, { "fire-postdelay", required_argument, NULL, 0}, { "discharge-duration", required_argument, NULL, 0}, // 12 { "discharge-level", required_argument, NULL, 0}, { NULL, 0, NULL, 0}, }; int longopt; int opt; unsigned mspI2cBusId = 0x2; unsigned mspI2cDeviceId = 0x48; unsigned mspChargeLevelCmd = 0; unsigned mspDischargeCurrentCmd = 0; unsigned gpioChargeCtrl = 0; unsigned gpioDischargeCtrl = 0; unsigned chargeDurationMs = 0; unsigned chargeLevel = 0x10; unsigned firePreDelayMs = 10; unsigned fireDurationMs = 10; unsigned firePostDelayMs = 100; unsigned dischargeDurationMs = 0; unsigned dischargeLevel = 0; while ((opt = getopt_long(_argc, _argv, s_optstring, s_longopts, &longopt)) != -1) { switch (opt) { case 'h': return printUsageHelp(); case 0: switch (longopt) { case 0: return printUsageHelp(); case 1: mspI2cBusId = atoi(optarg); break; case 2: mspI2cDeviceId = atoi(optarg); break; case 3: mspChargeLevelCmd = atoi(optarg); break; case 4: mspDischargeCurrentCmd = atoi(optarg); break; case 5: gpioChargeCtrl = atoi(optarg); break; case 6: gpioDischargeCtrl = atoi(optarg); break; case 7: chargeDurationMs = atoi(optarg); break; case 8: chargeLevel = atoi(optarg); break; case 9: firePreDelayMs = atoi(optarg); break; case 10: fireDurationMs = atoi(optarg); break; case 11: firePostDelayMs = atoi(optarg); break; case 12: dischargeDurationMs = atoi(optarg); break; case 13: dischargeLevel = atoi(optarg); break; default: return printUsageHelp(); } break; default: return printUsageHelp(); } } cout << "Charge duration " << chargeDurationMs << "ms, level " << chargeLevel << endl; cout << "Fire pre-delay " << firePreDelayMs << "ms, duration " << fireDurationMs << "ms, post-delay " << firePostDelayMs << "ms" << endl; cout << "Discharge duration " << dischargeDurationMs << "ms, level " << dischargeLevel << endl; TrikCoilGun coilGun(mspI2cBusId, mspI2cDeviceId, mspChargeLevelCmd, mspDischargeCurrentCmd, gpioChargeCtrl, gpioDischargeCtrl); coilGun.charge(chargeDurationMs, chargeLevel); coilGun.fire(firePreDelayMs, fireDurationMs, firePostDelayMs); coilGun.discharge(dischargeDurationMs, dischargeLevel); } <|endoftext|>
<commit_before>#ifndef OPTIMIZE_HPP_OBWEIHS0 #define OPTIMIZE_HPP_OBWEIHS0 #include <optimization.hpp> #include "calib.hpp" /*! * @brief Optimize extrinsic matrix K (3x4) by minimizing reprojection error while ignoring distortion. * * @param image_points Image 2D points from calibration pattern used to extract extrinsic matrix. * @param model_points World 3D points from calibration pattern. * @param A Intrinsic matrix 3x3. * @param K Initial extrinsic matrix. * @param tol Error tolerance used in Levenberg-Marquard optimization algorithm. */ int optimize_extrinsics(const std::vector<cv::vec2r> &image_points, const std::vector<cv::vec3r> &model_points, const cv::matrixr &A, cv::matrixr &K, double tol = 1e-14); /*! * @brief Optimize distortion parameters by minimizing reprojection. * * @param image_points Image 2D points from calibration patterns used for calibration. * @param model_points World 3D points from calibration pattern. * @param A Intrinsic matrix 3x3. * @param K Initial extrinsic matrices. * @param k Initial value for radial and tangential distortion parameters. As input can be 2, 4, and 8 dimension vector: * 2 - [k1, k2] * 4 - [k1, k2, p1, p2] * 8 - [k1, k2, k3, k4, k5, k6, p1, p2] * Returned value is always 8 point vector with all parameters. For every non-given parameter zero is set as initial value. * @param tol Error tolerance used in Levenberg-Marquard optimization algorithm. */ int optimize_distortion(const std::vector<std::vector<cv::vec2r>> &image_points, const std::vector<cv::vec3r> &model_points, const cv::matrixr &A, const std::vector<cv::matrixr> &K, cv::vectorr&k, double tol = 1e-14); /*! * @brief Optimize all calibration parameters for one pattern. * * @param image_points Image 2D points from calibration pattern. * @param model_points World 3D points from calibration pattern. * @param A Intrinsic matrix 3x3. * @param K Extrinsic matrix 3x4. * @param k Initial value for radial and tangential distortion parameters. As input can be 2, 4, and 8 dimension vector: * 2 - [k1, k2] * 4 - [k1, k2, p1, p2] * 8 - [k1, k2, k3, k4, k5, k6, p1, p2] * @param fixed_aspect Force fixed aspect ration (alpha = beta) in optimization. * @param no_skew Force zero skew (c) in optimization. * @param tol Error tolerance used in Levenberg-Marquard optimization algorithm. */ int optimize_all(const std::vector<cv::vec2r> &image_points, const std::vector<cv::vec3r> &model_points, cv::matrixr &A, cv::matrixr &K, cv::vectorr &k, bool fixed_aspect = false, bool no_skew = false, double tol = 1e-14); /*! * @brief Optimize all calibration parameters. * * @param image_points Image 2D points from calibration patterns used for calibration. * @param model_points World 3D points from calibration pattern. * @param A Intrinsic matrix 3x3. * @param K Extrinsic matrices. * @param k Initial value for radial and tangential distortion parameters. As input can be 2, 4, and 8 dimension vector: * 2 - [k1, k2] * 4 - [k1, k2, p1, p2] * 8 - [k1, k2, k3, k4, k5, k6, p1, p2] * @param fixed_aspect Force fixed aspect ration (alpha = beta) in optimization. * @param no_skew Force zero skew (c) in optimization. * @param tol Error tolerance used in Levenberg-Marquard optimization algorithm. */ int optimize_all(const std::vector<std::vector<cv::vec2r>> &image_points, const std::vector<cv::vec3r> &model_points, cv::matrixr &A, std::vector<cv::matrixr> &K, cv::vectorr &k, bool fixed_aspect = false, bool no_skew = false, double tol = 1e-14); #endif /* end of include guard: OPTIMIZE_HPP_OBWEIHS0 */ <commit_msg>removed all optimization per pattern<commit_after>#ifndef OPTIMIZE_HPP_OBWEIHS0 #define OPTIMIZE_HPP_OBWEIHS0 #include <optimization.hpp> #include "calib.hpp" /*! * @brief Optimize extrinsic matrix K (3x4) by minimizing reprojection error while ignoring distortion. * * @param image_points Image 2D points from calibration pattern used to extract extrinsic matrix. * @param model_points World 3D points from calibration pattern. * @param A Intrinsic matrix 3x3. * @param K Initial extrinsic matrix. * @param tol Error tolerance used in Levenberg-Marquard optimization algorithm. */ int optimize_extrinsics(const std::vector<cv::vec2r> &image_points, const std::vector<cv::vec3r> &model_points, const cv::matrixr &A, cv::matrixr &K, double tol = 1e-14); /*! * @brief Optimize distortion parameters by minimizing reprojection. * * @param image_points Image 2D points from calibration patterns used for calibration. * @param model_points World 3D points from calibration pattern. * @param A Intrinsic matrix 3x3. * @param K Initial extrinsic matrices. * @param k Initial value for radial and tangential distortion parameters. As input can be 2, 4, and 8 dimension vector: * 2 - [k1, k2] * 4 - [k1, k2, p1, p2] * 8 - [k1, k2, k3, k4, k5, k6, p1, p2] * Returned value is always 8 point vector with all parameters. For every non-given parameter zero is set as initial value. * @param tol Error tolerance used in Levenberg-Marquard optimization algorithm. */ int optimize_distortion(const std::vector<std::vector<cv::vec2r>> &image_points, const std::vector<cv::vec3r> &model_points, const cv::matrixr &A, const std::vector<cv::matrixr> &K, cv::vectorr&k, double tol = 1e-14); /*! * @brief Optimize all calibration parameters. * * @param image_points Image 2D points from calibration patterns used for calibration. * @param model_points World 3D points from calibration pattern. * @param A Intrinsic matrix 3x3. * @param K Extrinsic matrices. * @param k Initial value for radial and tangential distortion parameters. As input can be 2, 4, and 8 dimension vector: * 2 - [k1, k2] * 4 - [k1, k2, p1, p2] * 8 - [k1, k2, k3, k4, k5, k6, p1, p2] * @param fixed_aspect Force fixed aspect ration (alpha = beta) in optimization. * @param no_skew Force zero skew (c) in optimization. * @param tol Error tolerance used in Levenberg-Marquard optimization algorithm. */ int optimize_calib(const std::vector<std::vector<cv::vec2r>> &image_points, const std::vector<cv::vec3r> &model_points, cv::matrixr &A, std::vector<cv::matrixr> &K, cv::vectorr &k, bool fixed_aspect = false, bool no_skew = false, double tol = 1e-14); #endif /* end of include guard: OPTIMIZE_HPP_OBWEIHS0 */ <|endoftext|>
<commit_before>#include "Version.h" #include "SourceControl.h" #include "System/Config.h" #include "System/Events/EventLoop.h" #include "System/IO/IOProcessor.h" #include "System/Service.h" #include "System/FileSystem.h" #include "System/CrashReporter.h" #include "Framework/Storage/BloomFilter.h" #include "Application/Common/ContextTransport.h" #include "Application/ConfigServer/ConfigServerApp.h" #include "Application/ShardServer/ShardServerApp.h" #define IDENT "ScalienDB" const char PRODUCT_STRING[] = IDENT " v" VERSION_STRING " " PLATFORM_STRING; const char BUILD_DATE[] = "Build date: " __DATE__ " " __TIME__; static void InitLog(); static void ParseArgs(int argc, char** argv); static void SetupServiceIdentity(ServiceIdentity& ident); static void RunMain(int argc, char** argv); static void RunApplication(); static void ConfigureSystemSettings(); static bool IsController(); static void InitContextTransport(); static void LogPrintVersion(bool isController); static void CrashReporterCallback(); // the application object is global for debugging purposes static Application* app; static bool restoreMode = false; int main(int argc, char** argv) { try { // crash reporter messes up the debugging on Windows #ifndef DEBUG CrashReporter::SetCallback(CFunc(CrashReporterCallback)); #endif RunMain(argc, argv); } catch (std::bad_alloc& e) { UNUSED(e); STOP_FAIL(1, "Out of memory error"); } catch (std::exception& e) { STOP_FAIL(1, "Unexpected exception happened (%s)", e.what()); } catch (...) { STOP_FAIL(1, "Unexpected exception happened"); } Log_Message(IDENT " exited normally"); return 0; } static void RunMain(int argc, char** argv) { ServiceIdentity identity; ParseArgs(argc, argv); if (argc < 2) STOP_FAIL(1, "Config file argument not given"); if (!configFile.Init(argv[1])) STOP_FAIL(1, "Invalid config file (%s)", argv[1]); InitLog(); // HACK: this is called twice, because command line arguments may override log settings ParseArgs(argc, argv); SetupServiceIdentity(identity); Service::Main(argc, argv, RunApplication, identity); } static void RunApplication() { bool isController; StartClock(); ConfigureSystemSettings(); IOProcessor::Init(configFile.GetIntValue("io.maxfd", 32768)); InitContextTransport(); BloomFilter::StaticInit(); isController = IsController(); LogPrintVersion(isController); if (isController) app = new ConfigServerApp; else app = new ShardServerApp(restoreMode); Service::SetStatus(SERVICE_STATUS_RUNNING); app->Init(); IOProcessor::BlockSignals(IOPROCESSOR_BLOCK_ALL); EventLoop::Init(); EventLoop::Run(); Service::SetStatus(SERVICE_STATUS_STOP_PENDING); Log_Message("Shutting down..."); EventLoop::Shutdown(); app->Shutdown(); delete app; IOProcessor::Shutdown(); StopClock(); configFile.Shutdown(); Log_Shutdown(); } static void SetupServiceIdentity(ServiceIdentity& identity) { // set up service identity based on role if (IsController()) { identity.name = "ScalienController"; identity.displayName = "Scalien Database Controller"; identity.description = "Provides and stores metadata for Scalien Database cluster"; } else { identity.name = "ScalienShardServer"; identity.displayName = "Scalien Database Shard Server"; identity.description = "Provides reliable and replicated data storage for Scalien Database cluster"; } } static void InitLog() { int logTargets; bool debug; #ifdef DEBUG debug = true; #else debug = false; #endif logTargets = 0; if (configFile.GetListNum("log.targets") == 0) logTargets = LOG_TARGET_STDOUT; for (int i = 0; i < configFile.GetListNum("log.targets"); i++) { if (strcmp(configFile.GetListValue("log.targets", i, ""), "file") == 0) { logTargets |= LOG_TARGET_FILE; Log_SetOutputFile(configFile.GetValue("log.file", NULL), configFile.GetBoolValue("log.truncate", false)); } if (strcmp(configFile.GetListValue("log.targets", i, NULL), "stdout") == 0) logTargets |= LOG_TARGET_STDOUT; if (strcmp(configFile.GetListValue("log.targets", i, NULL), "stderr") == 0) logTargets |= LOG_TARGET_STDERR; } Log_SetTarget(logTargets); Log_SetTrace(configFile.GetBoolValue("log.trace", false)); Log_SetDebug(configFile.GetBoolValue("log.debug", debug)); Log_SetTimestamping(configFile.GetBoolValue("log.timestamping", false)); Log_SetAutoFlush(configFile.GetBoolValue("log.autoFlush", true)); Log_SetMaxSize(configFile.GetIntValue("log.maxSize", 100*1000*1000) / (1000 * 1000)); Log_SetTraceBufferSize(configFile.GetIntValue("log.traceBufferSize", 0)); Log_SetFlushInterval(configFile.GetIntValue("log.flushInterval", 0) * 1000); } static void ParseArgs(int argc, char** argv) { for (int i = 1; i < argc; i++) { if (argv[i][0] == '-') { switch (argv[i][1]) { case 't': Log_SetTrace(true); break; case 'X': SetExitOnError(false); SetAssertCritical(false); break; case 'v': STOP("%s", PRODUCT_STRING); break; case 'r': restoreMode = true; break; case 'h': STOP("Usage:\n" "\n" " %s config-file [options]\n" "\n" "Options:\n" "\n" " -v: print version number and exit\n" " -r: start server in restore mode\n" " -t: turn trace mode on\n" " -h: print this help\n" , argv[0]); break; } } } } static void ConfigureSystemSettings() { int memLimitPerc; uint64_t memLimit; const char* dir; // percentage of physical memory can be used by the program memLimitPerc = configFile.GetIntValue("system.memoryLimitPercentage", 90); if (memLimitPerc < 0) memLimitPerc = 90; // memoryLimit overrides memoryLimitPercentage memLimit = configFile.GetInt64Value("system.memoryLimit", 0); if (memLimit == 0) memLimit = (uint64_t) (GetTotalPhysicalMemory() * memLimit / 100.0 + 0.5); if (memLimit != 0) SetMemoryLimit(memLimit); // set the base directory dir = configFile.GetValue("dir", NULL); if (dir) { if (!FS_ChangeDir(dir)) STOP_FAIL(1, "Cannot change to dir: %s", dir); // setting the base dir may affect the location of the log file InitLog(); } // set exit on error: this is how ASSERTs are handled in release build SetExitOnError(true); SeedRandom(); } static bool IsController() { const char* role; role = configFile.GetValue("role", ""); if (role == NULL) STOP_FAIL(1, "Missing \"role\" in config file!"); if (strcmp(role, "controller") == 0) return true; else return false; } static void InitContextTransport() { const char* str; Endpoint endpoint; // set my endpoint str = configFile.GetValue("endpoint", ""); if (str == NULL) STOP_FAIL(1, "Missing \"endpoint\" in config file!"); if (!endpoint.Set(str, true)) STOP_FAIL(1, "Bad endpoint format in config file!"); CONTEXT_TRANSPORT->Init(endpoint); } static void LogPrintVersion(bool isController) { Log_Message("%s started as %s", PRODUCT_STRING, isController ? "CONTROLLER" : "SHARD SERVER"); Log_Message("Pid: %U", GetProcessID()); Log_Message("%s", BUILD_DATE); Log_Message("Branch: %s", SOURCE_CONTROL_BRANCH); Log_Message("Source control version: %s", SOURCE_CONTROL_VERSION); Log_Message("================================================================"); } static void CrashReporterCallback() { const char* msg; // We need to be careful here, because by the time the control gets here the stack and the heap // may already be corrupted. Therefore there must not be any heap allocations here, but unfortunately // stack allocations cannot be avoided. // When rotating the log there is heap allocation. To prevent it, we turn off log rotation ASAP. Log_SetMaxSize(0); CrashReporter::ReportSystemEvent(IDENT); // Generate report and send it to log and standard error msg = CrashReporter::GetReport(); Log_SetTarget(Log_GetTarget() | LOG_TARGET_STDERR | LOG_TARGET_FILE); Log_Message("%s", msg); IFDEBUG(ASSERT_FAIL()); _exit(1); } <commit_msg>Changed logging.<commit_after>#include "Version.h" #include "SourceControl.h" #include "System/Config.h" #include "System/Events/EventLoop.h" #include "System/IO/IOProcessor.h" #include "System/Service.h" #include "System/FileSystem.h" #include "System/CrashReporter.h" #include "Framework/Storage/BloomFilter.h" #include "Application/Common/ContextTransport.h" #include "Application/ConfigServer/ConfigServerApp.h" #include "Application/ShardServer/ShardServerApp.h" #define IDENT "ScalienDB" const char PRODUCT_STRING[] = IDENT " v" VERSION_STRING " " PLATFORM_STRING; const char BUILD_DATE[] = "Build date: " __DATE__ " " __TIME__; static void InitLog(); static void ParseArgs(int argc, char** argv); static void SetupServiceIdentity(ServiceIdentity& ident); static void RunMain(int argc, char** argv); static void RunApplication(); static void ConfigureSystemSettings(); static bool IsController(); static void InitContextTransport(); static void LogPrintVersion(bool isController); static void CrashReporterCallback(); // the application object is global for debugging purposes static Application* app; static bool restoreMode = false; int main(int argc, char** argv) { try { // crash reporter messes up the debugging on Windows #ifndef DEBUG CrashReporter::SetCallback(CFunc(CrashReporterCallback)); #endif RunMain(argc, argv); } catch (std::bad_alloc& e) { UNUSED(e); STOP_FAIL(1, "Out of memory error"); } catch (std::exception& e) { STOP_FAIL(1, "Unexpected exception happened (%s)", e.what()); } catch (...) { STOP_FAIL(1, "Unexpected exception happened"); } return 0; } static void RunMain(int argc, char** argv) { ServiceIdentity identity; ParseArgs(argc, argv); if (argc < 2) STOP_FAIL(1, "Config file argument not given"); if (!configFile.Init(argv[1])) STOP_FAIL(1, "Invalid config file (%s)", argv[1]); InitLog(); // HACK: this is called twice, because command line arguments may override log settings ParseArgs(argc, argv); SetupServiceIdentity(identity); Service::Main(argc, argv, RunApplication, identity); } static void RunApplication() { bool isController; StartClock(); ConfigureSystemSettings(); IOProcessor::Init(configFile.GetIntValue("io.maxfd", 32768)); InitContextTransport(); BloomFilter::StaticInit(); isController = IsController(); LogPrintVersion(isController); if (isController) app = new ConfigServerApp; else app = new ShardServerApp(restoreMode); Service::SetStatus(SERVICE_STATUS_RUNNING); app->Init(); IOProcessor::BlockSignals(IOPROCESSOR_BLOCK_ALL); EventLoop::Init(); EventLoop::Run(); Service::SetStatus(SERVICE_STATUS_STOP_PENDING); Log_Message("Shutting down..."); EventLoop::Shutdown(); app->Shutdown(); delete app; IOProcessor::Shutdown(); StopClock(); configFile.Shutdown(); // This is here and not the end of main(), because logging may be turned off by then Log_Message(IDENT " exited normally"); Log_Shutdown(); } static void SetupServiceIdentity(ServiceIdentity& identity) { // set up service identity based on role if (IsController()) { identity.name = "ScalienController"; identity.displayName = "Scalien Database Controller"; identity.description = "Provides and stores metadata for Scalien Database cluster"; } else { identity.name = "ScalienShardServer"; identity.displayName = "Scalien Database Shard Server"; identity.description = "Provides reliable and replicated data storage for Scalien Database cluster"; } } static void InitLog() { int logTargets; bool debug; #ifdef DEBUG debug = true; #else debug = false; #endif logTargets = 0; if (configFile.GetListNum("log.targets") == 0) logTargets = LOG_TARGET_STDOUT; for (int i = 0; i < configFile.GetListNum("log.targets"); i++) { if (strcmp(configFile.GetListValue("log.targets", i, ""), "file") == 0) { logTargets |= LOG_TARGET_FILE; Log_SetOutputFile(configFile.GetValue("log.file", NULL), configFile.GetBoolValue("log.truncate", false)); } if (strcmp(configFile.GetListValue("log.targets", i, NULL), "stdout") == 0) logTargets |= LOG_TARGET_STDOUT; if (strcmp(configFile.GetListValue("log.targets", i, NULL), "stderr") == 0) logTargets |= LOG_TARGET_STDERR; } Log_SetTarget(logTargets); Log_SetTrace(configFile.GetBoolValue("log.trace", false)); Log_SetDebug(configFile.GetBoolValue("log.debug", debug)); Log_SetTimestamping(configFile.GetBoolValue("log.timestamping", false)); Log_SetAutoFlush(configFile.GetBoolValue("log.autoFlush", true)); Log_SetMaxSize(configFile.GetIntValue("log.maxSize", 100*1000*1000) / (1000 * 1000)); Log_SetTraceBufferSize(configFile.GetIntValue("log.traceBufferSize", 0)); Log_SetFlushInterval(configFile.GetIntValue("log.flushInterval", 0) * 1000); } static void ParseArgs(int argc, char** argv) { for (int i = 1; i < argc; i++) { if (argv[i][0] == '-') { switch (argv[i][1]) { case 't': Log_SetTrace(true); break; case 'X': SetExitOnError(false); SetAssertCritical(false); break; case 'v': STOP("%s", PRODUCT_STRING); break; case 'r': restoreMode = true; break; case 'h': STOP("Usage:\n" "\n" " %s config-file [options]\n" "\n" "Options:\n" "\n" " -v: print version number and exit\n" " -r: start server in restore mode\n" " -t: turn trace mode on\n" " -h: print this help\n" , argv[0]); break; } } } } static void ConfigureSystemSettings() { int memLimitPerc; uint64_t memLimit; const char* dir; // percentage of physical memory can be used by the program memLimitPerc = configFile.GetIntValue("system.memoryLimitPercentage", 90); if (memLimitPerc < 0) memLimitPerc = 90; // memoryLimit overrides memoryLimitPercentage memLimit = configFile.GetInt64Value("system.memoryLimit", 0); if (memLimit == 0) memLimit = (uint64_t) (GetTotalPhysicalMemory() * memLimit / 100.0 + 0.5); if (memLimit != 0) SetMemoryLimit(memLimit); // set the base directory dir = configFile.GetValue("dir", NULL); if (dir) { if (!FS_ChangeDir(dir)) STOP_FAIL(1, "Cannot change to dir: %s", dir); // setting the base dir may affect the location of the log file InitLog(); } // set exit on error: this is how ASSERTs are handled in release build SetExitOnError(true); SeedRandom(); } static bool IsController() { const char* role; role = configFile.GetValue("role", ""); if (role == NULL) STOP_FAIL(1, "Missing \"role\" in config file!"); if (strcmp(role, "controller") == 0) return true; else return false; } static void InitContextTransport() { const char* str; Endpoint endpoint; // set my endpoint str = configFile.GetValue("endpoint", ""); if (str == NULL) STOP_FAIL(1, "Missing \"endpoint\" in config file!"); if (!endpoint.Set(str, true)) STOP_FAIL(1, "Bad endpoint format in config file!"); CONTEXT_TRANSPORT->Init(endpoint); } static void LogPrintVersion(bool isController) { Log_Message("%s started as %s", PRODUCT_STRING, isController ? "CONTROLLER" : "SHARD SERVER"); Log_Message("Pid: %U", GetProcessID()); Log_Message("%s", BUILD_DATE); Log_Message("Branch: %s", SOURCE_CONTROL_BRANCH); Log_Message("Source control version: %s", SOURCE_CONTROL_VERSION); Log_Message("================================================================"); } static void CrashReporterCallback() { const char* msg; // We need to be careful here, because by the time the control gets here the stack and the heap // may already be corrupted. Therefore there must not be any heap allocations here, but unfortunately // stack allocations cannot be avoided. // When rotating the log there is heap allocation. To prevent it, we turn off log rotation ASAP. Log_SetMaxSize(0); CrashReporter::ReportSystemEvent(IDENT); // Generate report and send it to log and standard error msg = CrashReporter::GetReport(); Log_SetTarget(Log_GetTarget() | LOG_TARGET_STDERR | LOG_TARGET_FILE); Log_Message("%s", msg); IFDEBUG(ASSERT_FAIL()); _exit(1); } <|endoftext|>
<commit_before>// main.cpp // Main function for testing Maggie code // // Oliver W. Laslett 2015 // [email protected] // #include<iostream> using std::cout; using std::endl; #include<cmath> using std::abs; #include<LangevinEquation.hpp> #include<StocLLG.hpp> #include<gtest/gtest.h> #include<boost/multi_array.hpp> typedef boost::multi_array<float,1> array_f; // Test construction of StocLLG TEST(StochasticLLG, ContructAndDim) { StocLLG llg( 1, 2, 3, 4, 5 ); EXPECT_EQ( 3, llg.getDim() ); } // Test deterministic part of StocLLG TEST(StochasticLLG, Drift) { // Tolerance for solution float tol=1e-5; // declare in and out arrays array_f out( boost::extents[3] ); array_f in( boost::extents[3] ); in[0] = 2; in[1] = 3; in[2] = 4; // Set up StocLLG and compute drift StocLLG llg( 2, 3, 1, 2, 3 ); llg.computeDrift( out, in ); // Are the solutions close? EXPECT_EQ( -34, out[0] ); EXPECT_EQ( -4, out[1] ); EXPECT_EQ( 20, out[2] ); } int main( int argc, char **argv ) { ::testing::InitGoogleTest( &argc, argv ); return RUN_ALL_TESTS(); } <commit_msg>Wrote diffusion test for StocLLG and removed tolerance lines from StocLLG tests<commit_after>// main.cpp // Main function for testing Maggie code // // Oliver W. Laslett 2015 // [email protected] // #include<iostream> using std::cout; using std::endl; #include<cmath> using std::abs; #include<LangevinEquation.hpp> #include<StocLLG.hpp> #include<gtest/gtest.h> #include<boost/multi_array.hpp> typedef boost::multi_array<float,1> array_f; typedef boost::multi_array<float,2> matrix_f; // Test construction of StocLLG TEST(StochasticLLG, ContructAndDim) { StocLLG llg( 1, 2, 3, 4, 5 ); EXPECT_EQ( 3, llg.getDim() ); } // Test deterministic part of StocLLG TEST(StochasticLLG, Drift) { // declare in and out arrays array_f out( boost::extents[3] ); array_f in( boost::extents[3] ); in[0] = 2; in[1] = 3; in[2] = 4; // Set up StocLLG and compute drift StocLLG llg( 2, 3, 1, 2, 3 ); llg.computeDrift( out, in ); // Are the solutions correct? EXPECT_EQ( -34, out[0] ); EXPECT_EQ( -4, out[1] ); EXPECT_EQ( 20, out[2] ); } // Test the stochastic part of the StocLLG TEST(StochasticLLG, Diffusion) { // declare in and out arrays array_f in( boost::extents[3] ); matrix_f out( boost::extents[3][3] ); in[0] = 2; in[1] = 3; in[2] = 4; // set up the StocLLG and compute diffusion StocLLG llg( 2, 3, 1, 2, 3 ); llg.computeDiffusion( out, in ); // are the solutions correct? EXPECT_EQ( 150, out[0][0] ); EXPECT_EQ( -28, out[0][1] ); EXPECT_EQ( -54, out[0][2] ); EXPECT_EQ( -44, out[1][0] ); EXPECT_EQ( 120, out[1][1] ); EXPECT_EQ( -68, out[1][2] ); EXPECT_EQ( -42, out[2][0] ); EXPECT_EQ( -76, out[2][1] ); EXPECT_EQ( 78, out[2][2] ); } int main( int argc, char **argv ) { ::testing::InitGoogleTest( &argc, argv ); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include <ctrcommon/input.hpp> #include <ctrcommon/platform.hpp> #include <ctrcommon/ui.hpp> #include <sstream> #include <iomanip> #include <stdio.h> typedef enum { INSTALL, DELETE } Mode; int main(int argc, char **argv) { if(!platformInit()) { return 0; } bool ninjhax = platformIsNinjhax(); std::vector<std::string> extensions; extensions.push_back("cia"); MediaType destination = SD; Mode mode = INSTALL; bool exit = false; bool netInstall = false; u64 freeSpace = fsGetFreeSpace(destination); auto onLoop = [&]() { if(ninjhax && inputIsPressed(BUTTON_START)) { exit = true; return true; } bool breakLoop = false; if(inputIsPressed(BUTTON_L)) { if(destination == SD) { destination = NAND; } else { destination = SD; } freeSpace = fsGetFreeSpace(destination); if(mode == DELETE) { breakLoop = true; } } if(inputIsPressed(BUTTON_R)) { if(mode == INSTALL) { mode = DELETE; } else { mode = INSTALL; } breakLoop = true; } if(inputIsPressed(BUTTON_Y)) { netInstall = true; breakLoop = true; } std::stringstream stream; stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n"; stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL ? "Install" : "Delete") << "\n"; stream << "L - Switch Destination, R - Switch Mode" << "\n"; stream << "Y - Receive an app over the network" << "\n"; if(ninjhax) { stream << "START - Exit to launcher" << "\n"; } std::string str = stream.str(); screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255); return breakLoop; }; auto onProgress = [&](int progress) { uiDisplayProgress(TOP_SCREEN, "Installing", "Press B to cancel.", true, progress); inputPoll(); return !inputIsPressed(BUTTON_B); }; while(platformIsRunning()) { std::string targetInstall; App targetDelete; if(mode == INSTALL) { uiSelectFile(&targetInstall, "sdmc:", extensions, [&](bool inRoot) { return onLoop(); }, [&](std::string path, bool &updateList) { if(uiPrompt(TOP_SCREEN, "Install the selected title?", true)) { AppResult ret = appInstallFile(destination, path, onProgress); std::stringstream resultMsg; resultMsg << "Install "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } return false; }); } else if(mode == DELETE) { uiSelectApp(&targetDelete, destination, onLoop, [&](App app, bool &updateList) { if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true)) { updateList = true; uiDisplayMessage(TOP_SCREEN, "Deleting title..."); AppResult ret = appDelete(app); std::stringstream resultMsg; resultMsg << "Delete "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } return false; }); } if(netInstall && !exit) { netInstall = false; screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0); RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN); if(file.fd == NULL) { continue; } std::stringstream confirmStream; confirmStream << "Install the received application?" << "\n"; confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n"; if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) { AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress); std::stringstream resultMsg; if(mode == INSTALL) { resultMsg << "Install "; } else if(mode == DELETE) { resultMsg << "Delete "; } if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); } fclose(file.fd); continue; } if(exit) { break; } } platformCleanup(); return 0; } <commit_msg>Change exit button to select.<commit_after>#include <ctrcommon/input.hpp> #include <ctrcommon/platform.hpp> #include <ctrcommon/ui.hpp> #include <sstream> #include <iomanip> #include <stdio.h> typedef enum { INSTALL, DELETE } Mode; int main(int argc, char **argv) { if(!platformInit()) { return 0; } bool ninjhax = platformIsNinjhax(); std::vector<std::string> extensions; extensions.push_back("cia"); MediaType destination = SD; Mode mode = INSTALL; bool exit = false; bool netInstall = false; u64 freeSpace = fsGetFreeSpace(destination); auto onLoop = [&]() { if(ninjhax && inputIsPressed(BUTTON_SELECT)) { exit = true; return true; } bool breakLoop = false; if(inputIsPressed(BUTTON_L)) { if(destination == SD) { destination = NAND; } else { destination = SD; } freeSpace = fsGetFreeSpace(destination); if(mode == DELETE) { breakLoop = true; } } if(inputIsPressed(BUTTON_R)) { if(mode == INSTALL) { mode = DELETE; } else { mode = INSTALL; } breakLoop = true; } if(inputIsPressed(BUTTON_Y)) { netInstall = true; breakLoop = true; } std::stringstream stream; stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n"; stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL ? "Install" : "Delete") << "\n"; stream << "L - Switch Destination, R - Switch Mode" << "\n"; stream << "Y - Receive an app over the network" << "\n"; if(ninjhax) { stream << "SELECT - Exit to launcher" << "\n"; } std::string str = stream.str(); screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255); return breakLoop; }; auto onProgress = [&](int progress) { uiDisplayProgress(TOP_SCREEN, "Installing", "Press B to cancel.", true, progress); inputPoll(); return !inputIsPressed(BUTTON_B); }; while(platformIsRunning()) { std::string targetInstall; App targetDelete; if(mode == INSTALL) { uiSelectFile(&targetInstall, "sdmc:", extensions, [&](bool inRoot) { return onLoop(); }, [&](std::string path, bool &updateList) { if(uiPrompt(TOP_SCREEN, "Install the selected title?", true)) { AppResult ret = appInstallFile(destination, path, onProgress); std::stringstream resultMsg; resultMsg << "Install "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } return false; }); } else if(mode == DELETE) { uiSelectApp(&targetDelete, destination, onLoop, [&](App app, bool &updateList) { if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true)) { updateList = true; uiDisplayMessage(TOP_SCREEN, "Deleting title..."); AppResult ret = appDelete(app); std::stringstream resultMsg; resultMsg << "Delete "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } return false; }); } if(netInstall && !exit) { netInstall = false; screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0); RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN); if(file.fd == NULL) { continue; } std::stringstream confirmStream; confirmStream << "Install the received application?" << "\n"; confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n"; if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) { AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress); std::stringstream resultMsg; if(mode == INSTALL) { resultMsg << "Install "; } else if(mode == DELETE) { resultMsg << "Delete "; } if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); } fclose(file.fd); continue; } if(exit) { break; } } platformCleanup(); return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <chrono> #include <tuple> #include "network/dimse/dimse_pm.hpp" #include "network/upperlayer/upperlayer.hpp" #include "data/attribute/attribute.hpp" #include "data/dataset/dataset_iterator.hpp" #include "data/dictionary/dictionary_dyn.hpp" #include "data/dictionary/datadictionary.hpp" #include "data/dictionary/dictionary.hpp" #include "data/attribute/constants.hpp" #include "filesystem/dicomfile.hpp" #include "serviceclass/storage_scu.hpp" #include "serviceclass/storage_scp.hpp" #include "serviceclass/queryretrieve_scp.hpp" #include "util/channel_sev_logger.hpp" #include <boost/variant.hpp> int main() { dicom::util::log::init_log(); using namespace dicom::data; using namespace dicom::data::attribute; using namespace dicom::data::dictionary; using namespace dicom::network; using namespace dicom::serviceclass; dicom::data::dictionary::dictionaries& dict = get_default_dictionaries(); // { // { // dataset::iod dicm; // dicm[{0x0008, 0x0016}] = make_elementfield<VR::CS>("1.2.840.10008.5.1.4.1.1.7"); // dicm[{0x0008, 0x0018}] = make_elementfield<VR::CS>("1.2.840.10008.25.25.25.1"); // dicm[{0x0010, 0x0010}] = make_elementfield<VR::PN>("test^test"); // dicom::filesystem::dicomfile file(dicm, dict); // std::fstream outfile("outfile.dcm", std::ios::out | std::ios::binary); // outfile << file; // outfile.flush(); // } // { dataset::iod dicm; dicom::filesystem::dicomfile file(dicm, dict); std::fstream outfile("XA-MONO2-8-12x-catheter10kb.dcm", std::ios::in | std::ios::binary); outfile >> file; std::cout << file.dataset() << std::flush; auto& set = file.dataset(); // set[{0x0080, 0x0080}] = make_elementfield<VR::OB>({1, 9, 2, 65}); std::fstream outfile2("outfile.dcm", std::ios::out | std::ios::binary); outfile2 << file; outfile2.flush(); // } // } dimse::SOP_class echo {"1.2.840.10008.1.1", { { dataset::DIMSE_SERVICE_GROUP::C_ECHO_RSP, [](dimse::dimse_pm* pm, dataset::commandset_data command, std::unique_ptr<dataset::iod> data) { assert(data == nullptr); std::cout << "Received C_ECHO_RSP\n"; std::cout << command; // pm->send_response({dataset::DIMSE_SERVICE_GROUP::C_ECHO_RQ, command}); pm->release_association(); }}} }; dimse::SOP_class findrsp {"1.2.840.10008.5.1.4.31", { { dataset::DIMSE_SERVICE_GROUP::C_FIND_RQ, [](dimse::dimse_pm* pm, dataset::commandset_data command, std::unique_ptr<dataset::iod> data) { assert(data != nullptr); std::cout << "Received C_ECHO_RSP\n"; // std::cout << *data; (*data)[{0x0008,0x4000}] = dicom::data::attribute::make_elementfield<VR::LT>("h\x12qej\x13"); (*data)[{0x0018,0x1150}] = dicom::data::attribute::make_elementfield<VR::IS>("292w9292"); pm->send_response({dataset::DIMSE_SERVICE_GROUP::C_FIND_RSP, command, *data, 0xff00}); pm->send_response({dataset::DIMSE_SERVICE_GROUP::C_FIND_RSP, command, boost::none, 0x0000}); // pm->release_association(); }}} }; dimse::SOP_class findrsp2 {"1.2.840.10008.5.1.4.31", { { dataset::DIMSE_SERVICE_GROUP::C_FIND_RSP, [](dimse::dimse_pm* pm, dataset::commandset_data command, std::unique_ptr<dataset::iod> data) { //assert(data != nullptr); std::cout << "Received C_FIND_RSP\n"; if (data) { std::cout << *data; } else { std::cout << "No dataset present\n"; } pm->release_association(); }}} }; dimse::SOP_class echorsp {"1.2.840.10008.1.1", { { dataset::DIMSE_SERVICE_GROUP::C_ECHO_RQ, [](dimse::dimse_pm* pm, dataset::commandset_data command, std::unique_ptr<dataset::iod> data) { assert(data == nullptr); std::cout << "Received C_ECHO_RQ\n"; pm->send_response({dataset::DIMSE_SERVICE_GROUP::C_ECHO_RSP, command}); }}} }; dimse::SOP_class findrq {"1.2.840.10008.5.1.4.1.1.2", { { dataset::DIMSE_SERVICE_GROUP::C_FIND_RQ, [](dimse::dimse_pm* pm, dataset::commandset_data command, std::unique_ptr<dataset::iod> data) { assert(data == nullptr); std::cout << "Send C_FIND_RQ\n"; dataset::dataset_type dat, dat2, dat3; dataset::iod seq; // dat[dicom::data::attribute::Item] = dicom::data::attribute::make_elementfield<VR::NI>(0xffffffff); // dat[{0x0008, 0x0104}] = dicom::data::attribute::make_elementfield<VR::LO>(4, "meo"); // dat[{0xfffe, 0xe00d}] = dicom::data::attribute::make_elementfield<VR::NI>(); // dat2[dicom::data::attribute::Item] = dicom::data::attribute::make_elementfield<VR::NI>(0xffffffff); // dat2[{0x0008, 0x0104}] = dicom::data::attribute::make_elementfield<VR::LO>(4, "mwo"); // dat2[{0xfffe, 0xe00d}] = dicom::data::attribute::make_elementfield<VR::NI>(); // dat3[dicom::data::attribute::SequenceDelimitationItem] = dicom::data::attribute::make_elementfield<VR::NI>(); // seq[{0x0032, 0x1064}] = dicom::data::attribute::make_elementfield<VR::SQ>(0xffffffff, {dat, dat2, dat3}); std::vector<unsigned short> largedat(25000000, 0xff); seq[{0x7fe0,0x0010}] = dicom::data::attribute::make_elementfield<VR::OW>(25000000, largedat); pm->send_response({dataset::DIMSE_SERVICE_GROUP::C_FIND_RQ, command, seq}); }}} }; dimse::SOP_class echorq {"1.2.840.10008.1.1", { { dataset::DIMSE_SERVICE_GROUP::C_ECHO_RQ, [](dimse::dimse_pm* pm, dataset::commandset_data command, std::unique_ptr<dataset::iod> data) { assert(data == nullptr); std::cout << "Send C_ECHO_RQ\n"; pm->send_response({dataset::DIMSE_SERVICE_GROUP::C_ECHO_RQ, command}); }}} }; dimse::association_definition ascdef {"STORESCP", "OFFIS", { // {echorq, {"1.2.840.10008.1.2"}, dimse::association_definition::DIMSE_MSG_TYPE::INITIATOR}, {findrq, {"1.2.840.10008.1.2"}, dimse::association_definition::DIMSE_MSG_TYPE::INITIATOR}, {echo, {"1.2.840.10008.1.2"}, dimse::association_definition::DIMSE_MSG_TYPE::RESPONSE}, {echorsp, {"1.2.840.10008.1.2"}, dimse::association_definition::DIMSE_MSG_TYPE::RESPONSE}, {findrsp, {"1.2.840.10008.1.2.1"}, dimse::association_definition::DIMSE_MSG_TYPE::RESPONSE}, {findrsp2, {"1.2.840.10008.1.2.1"}, dimse::association_definition::DIMSE_MSG_TYPE::RESPONSE} }, 4096 }; try { // int n = 0; // queryretrieve_scp qr({"QRSCP", "QRSCU", "", 1113}, dict, // [&n](queryretrieve_scp* st, dicom::data::dataset::commandset_data cmd, std::shared_ptr<dicom::data::dataset::iod> data) { // dataset::iod seq; // seq[{0x0010,0x0010}] = dicom::data::attribute::make_elementfield<VR::PN>("test"); // ++n; // if (n < 15) // st->send_image(*data); // else // st->send_image(boost::none); // }); // qr.set_move_destination("MOVESCU", {"QRSCP", "QRSCU", "localhost", 1114}); // qr.run(); storage_scp store({"STORAGESCU", "STORAGESCP", "", 1113}, dict, [&dict](storage_scp* st, dicom::data::dataset::commandset_data cmd, std::unique_ptr<dicom::data::dataset::iod> data) { std::ofstream out("out", std::ios::binary); std::cout << *data; // std::vector<unsigned short> imdata; // auto value_field = (*data)[{0x7fe0,0x0010}]; // get_value_field<VR::OW>(value_field, imdata); // out.write((char*)imdata.data(), imdata.size()*sizeof(unsigned short)); // out.flush(); dicom::filesystem::dicomfile file(*data, dict); file.set_transfer_syntax("1.2.840.10008.1.2.4.70"); std::fstream outfile("storefile.dcm", std::ios::out | std::ios::binary); outfile << file; outfile.flush(); }); store.run(); // int n = 0; // storage_scu store({"STORAGESCP", "STORAGESCU", "localhost", 1113}, dict, // [&dict, &n](storage_scu* sc, dicom::data::dataset::commandset_data cmd, std::unique_ptr<dicom::data::dataset::iod> data) // { // if (n == 0) { // ++n; // } // else // sc->release(); // }); // store.set_store_data(file.dataset()); // store.run(); } catch (std::exception& ec) { std::cout << ec.what(); } } <commit_msg>remove yet unimplemented call<commit_after>#include <iostream> #include <chrono> #include <tuple> #include "network/dimse/dimse_pm.hpp" #include "network/upperlayer/upperlayer.hpp" #include "data/attribute/attribute.hpp" #include "data/dataset/dataset_iterator.hpp" #include "data/dictionary/dictionary_dyn.hpp" #include "data/dictionary/datadictionary.hpp" #include "data/dictionary/dictionary.hpp" #include "data/attribute/constants.hpp" #include "filesystem/dicomfile.hpp" #include "serviceclass/storage_scu.hpp" #include "serviceclass/storage_scp.hpp" #include "serviceclass/queryretrieve_scp.hpp" #include "util/channel_sev_logger.hpp" #include <boost/variant.hpp> int main() { dicom::util::log::init_log(); using namespace dicom::data; using namespace dicom::data::attribute; using namespace dicom::data::dictionary; using namespace dicom::network; using namespace dicom::serviceclass; dicom::data::dictionary::dictionaries& dict = get_default_dictionaries(); // { // { // dataset::iod dicm; // dicm[{0x0008, 0x0016}] = make_elementfield<VR::CS>("1.2.840.10008.5.1.4.1.1.7"); // dicm[{0x0008, 0x0018}] = make_elementfield<VR::CS>("1.2.840.10008.25.25.25.1"); // dicm[{0x0010, 0x0010}] = make_elementfield<VR::PN>("test^test"); // dicom::filesystem::dicomfile file(dicm, dict); // std::fstream outfile("outfile.dcm", std::ios::out | std::ios::binary); // outfile << file; // outfile.flush(); // } // { dataset::iod dicm; dicom::filesystem::dicomfile file(dicm, dict); std::fstream outfile("Anonymous.MR._.14.1.2017.06.28.09.41.02.294.59320527.dcm", std::ios::in | std::ios::binary); outfile >> file; std::cout << file.dataset() << std::flush; auto& set = file.dataset(); // set[{0x0080, 0x0080}] = make_elementfield<VR::OB>({1, 9, 2, 65}); std::fstream outfile2("outfile.dcm", std::ios::out | std::ios::binary); outfile2 << file; outfile2.flush(); // } // } dimse::SOP_class echo {"1.2.840.10008.1.1", { { dataset::DIMSE_SERVICE_GROUP::C_ECHO_RSP, [](dimse::dimse_pm* pm, dataset::commandset_data command, std::unique_ptr<dataset::iod> data) { assert(data == nullptr); std::cout << "Received C_ECHO_RSP\n"; std::cout << command; // pm->send_response({dataset::DIMSE_SERVICE_GROUP::C_ECHO_RQ, command}); pm->release_association(); }}} }; dimse::SOP_class findrsp {"1.2.840.10008.5.1.4.31", { { dataset::DIMSE_SERVICE_GROUP::C_FIND_RQ, [](dimse::dimse_pm* pm, dataset::commandset_data command, std::unique_ptr<dataset::iod> data) { assert(data != nullptr); std::cout << "Received C_ECHO_RSP\n"; // std::cout << *data; (*data)[{0x0008,0x4000}] = dicom::data::attribute::make_elementfield<VR::LT>("h\x12qej\x13"); (*data)[{0x0018,0x1150}] = dicom::data::attribute::make_elementfield<VR::IS>("292w9292"); pm->send_response({dataset::DIMSE_SERVICE_GROUP::C_FIND_RSP, command, *data, 0xff00}); pm->send_response({dataset::DIMSE_SERVICE_GROUP::C_FIND_RSP, command, boost::none, 0x0000}); // pm->release_association(); }}} }; dimse::SOP_class findrsp2 {"1.2.840.10008.5.1.4.31", { { dataset::DIMSE_SERVICE_GROUP::C_FIND_RSP, [](dimse::dimse_pm* pm, dataset::commandset_data command, std::unique_ptr<dataset::iod> data) { //assert(data != nullptr); std::cout << "Received C_FIND_RSP\n"; if (data) { std::cout << *data; } else { std::cout << "No dataset present\n"; } pm->release_association(); }}} }; dimse::SOP_class echorsp {"1.2.840.10008.1.1", { { dataset::DIMSE_SERVICE_GROUP::C_ECHO_RQ, [](dimse::dimse_pm* pm, dataset::commandset_data command, std::unique_ptr<dataset::iod> data) { assert(data == nullptr); std::cout << "Received C_ECHO_RQ\n"; pm->send_response({dataset::DIMSE_SERVICE_GROUP::C_ECHO_RSP, command}); }}} }; dimse::SOP_class findrq {"1.2.840.10008.5.1.4.1.1.2", { { dataset::DIMSE_SERVICE_GROUP::C_FIND_RQ, [](dimse::dimse_pm* pm, dataset::commandset_data command, std::unique_ptr<dataset::iod> data) { assert(data == nullptr); std::cout << "Send C_FIND_RQ\n"; dataset::dataset_type dat, dat2, dat3; dataset::iod seq; // dat[dicom::data::attribute::Item] = dicom::data::attribute::make_elementfield<VR::NI>(0xffffffff); // dat[{0x0008, 0x0104}] = dicom::data::attribute::make_elementfield<VR::LO>(4, "meo"); // dat[{0xfffe, 0xe00d}] = dicom::data::attribute::make_elementfield<VR::NI>(); // dat2[dicom::data::attribute::Item] = dicom::data::attribute::make_elementfield<VR::NI>(0xffffffff); // dat2[{0x0008, 0x0104}] = dicom::data::attribute::make_elementfield<VR::LO>(4, "mwo"); // dat2[{0xfffe, 0xe00d}] = dicom::data::attribute::make_elementfield<VR::NI>(); // dat3[dicom::data::attribute::SequenceDelimitationItem] = dicom::data::attribute::make_elementfield<VR::NI>(); // seq[{0x0032, 0x1064}] = dicom::data::attribute::make_elementfield<VR::SQ>(0xffffffff, {dat, dat2, dat3}); std::vector<unsigned short> largedat(25000000, 0xff); seq[{0x7fe0,0x0010}] = dicom::data::attribute::make_elementfield<VR::OW>(25000000, largedat); pm->send_response({dataset::DIMSE_SERVICE_GROUP::C_FIND_RQ, command, seq}); }}} }; dimse::SOP_class echorq {"1.2.840.10008.1.1", { { dataset::DIMSE_SERVICE_GROUP::C_ECHO_RQ, [](dimse::dimse_pm* pm, dataset::commandset_data command, std::unique_ptr<dataset::iod> data) { assert(data == nullptr); std::cout << "Send C_ECHO_RQ\n"; pm->send_response({dataset::DIMSE_SERVICE_GROUP::C_ECHO_RQ, command}); }}} }; dimse::association_definition ascdef {"STORESCP", "OFFIS", { // {echorq, {"1.2.840.10008.1.2"}, dimse::association_definition::DIMSE_MSG_TYPE::INITIATOR}, {findrq, {"1.2.840.10008.1.2"}, dimse::association_definition::DIMSE_MSG_TYPE::INITIATOR}, {echo, {"1.2.840.10008.1.2"}, dimse::association_definition::DIMSE_MSG_TYPE::RESPONSE}, {echorsp, {"1.2.840.10008.1.2"}, dimse::association_definition::DIMSE_MSG_TYPE::RESPONSE}, {findrsp, {"1.2.840.10008.1.2.1"}, dimse::association_definition::DIMSE_MSG_TYPE::RESPONSE}, {findrsp2, {"1.2.840.10008.1.2.1"}, dimse::association_definition::DIMSE_MSG_TYPE::RESPONSE} }, 4096 }; try { // int n = 0; // queryretrieve_scp qr({"QRSCP", "QRSCU", "", 1113}, dict, // [&n](queryretrieve_scp* st, dicom::data::dataset::commandset_data cmd, std::shared_ptr<dicom::data::dataset::iod> data) { // dataset::iod seq; // seq[{0x0010,0x0010}] = dicom::data::attribute::make_elementfield<VR::PN>("test"); // ++n; // if (n < 15) // st->send_image(*data); // else // st->send_image(boost::none); // }); // qr.set_move_destination("MOVESCU", {"QRSCP", "QRSCU", "localhost", 1114}); // qr.run(); storage_scp store({"STORAGESCU", "STORAGESCP", "", 1113}, dict, [&dict](storage_scp* st, dicom::data::dataset::commandset_data cmd, std::unique_ptr<dicom::data::dataset::iod> data) { std::ofstream out("out", std::ios::binary); std::cout << *data; // std::vector<unsigned short> imdata; // auto value_field = (*data)[{0x7fe0,0x0010}]; // get_value_field<VR::OW>(value_field, imdata); // out.write((char*)imdata.data(), imdata.size()*sizeof(unsigned short)); // out.flush(); dicom::filesystem::dicomfile file(*data, dict); // file.set_transfer_syntax("1.2.840.10008.1.2.4.70"); std::fstream outfile("storefile.dcm", std::ios::out | std::ios::binary); outfile << file; outfile.flush(); }); store.run(); // int n = 0; // storage_scu store({"STORAGESCP", "STORAGESCU", "localhost", 1113}, dict, // [&dict, &n](storage_scu* sc, dicom::data::dataset::commandset_data cmd, std::unique_ptr<dicom::data::dataset::iod> data) // { // if (n == 0) { // ++n; // } // else // sc->release(); // }); // store.set_store_data(file.dataset()); // store.run(); } catch (std::exception& ec) { std::cout << ec.what(); } } <|endoftext|>
<commit_before>#include <iostream> #include <functional> #include <memory> #include <vector> #include <boost/asio.hpp> #include <boost/shared_array.hpp> #include <boost/thread.hpp> /* #include <boost/archive/xml_iarchive.hpp> #include <boost/archive/xml_oarchive.hpp> #include "mif/remote/ps.h" #include "mif/remote/proxy_stub.h" #include "mif/remote/serialization/serialization.h" #include "mif/remote/serialization/boost/serialization.h" struct ITest { virtual ~ITest() = default; virtual void Print() = 0; virtual void SetVersion(int major, int minor) = 0; virtual void SetName(std::string const &name) = 0; virtual std::string GetName() = 0; virtual int GetMajor() const = 0; virtual int GetMinor() const = 0; }; MIF_REMOTE_PS_BEGIN(ITest) MIF_REMOTE_METHOD(Print) MIF_REMOTE_METHOD(SetVersion) MIF_REMOTE_METHOD(SetName) MIF_REMOTE_METHOD(GetName) MIF_REMOTE_METHOD(GetMajor) MIF_REMOTE_METHOD(GetMinor) MIF_REMOTE_PS_END() class Test final : public ITest { private: std::string m_name{"TestDefault"}; int m_major{0}; int m_minor{0}; virtual void Print() override { std::cout << "[Test::Print] Name\"" << m_name << "\" Major " << m_major << " Minor " << m_minor << std::endl; } virtual void SetVersion(int major, int minor) override { std::cout << "[Test::SetVersion] New major " << major << " New minor " << minor << std::endl; m_major = major; m_minor = minor; } virtual void SetName(std::string const &name) override { std::cout << "[Test::SetName] New name \"" << name << "\"" << std::endl; m_name = name; } virtual std::string GetName() override { std::cout << "[Test::GetName] Name \"" << m_name << "\"" << std::endl; return m_name; } virtual int GetMajor() const override { std::cout << "[Test::GetMajor] Major " << m_major << std::endl; return m_major; } virtual int GetMinor() const override { std::cout << "[Test::GetMinor] Minor " << m_minor << std::endl; return m_minor; } }; class TestTransport; TestTransport *p_transport = nullptr; class TestTransport { public: virtual ~TestTransport() = default; TestTransport() { } using Buffer = std::vector<char>; using DataHandler = std::function<Buffer (Buffer &&)>; DataHandler m_handler; void SetHandler(DataHandler && handler) { p_transport = this; m_handler = std::move(handler); } Buffer Send(Buffer && buffer); Buffer Call(Buffer && buffer) { return m_handler(std::move(buffer)); } }; TestTransport::Buffer TestTransport::Send(Buffer && buffer) { return p_transport->Call(std::move(buffer)); } int main() { try { using BoostSerializer = Mif::Remote::Serialization::Boost::Serializer<boost::archive::xml_oarchive>; using BoostDeserializer = Mif::Remote::Serialization::Boost::Deserializer<boost::archive::xml_iarchive>; using SerializerTraits = Mif::Remote::Serialization::SerializerTraits<BoostSerializer, BoostDeserializer>; using ProxyStub = ITest_PS<Mif::Remote::Proxy<SerializerTraits, TestTransport>, Mif::Remote::Stub<SerializerTraits, TestTransport>>; TestTransport proxyTransport; TestTransport stubTransport; ProxyStub::Stub stub("100500", std::make_shared<Test>(), std::move(stubTransport)); stub.Init(); ProxyStub::Proxy proxy("100500", std::move(proxyTransport)); ITest &rps = proxy; std::cout << "Old name: " << rps.GetName() << std::endl; std::cout << "Old major: " << rps.GetMajor() << std::endl; std::cout << "Old minor: " << rps.GetMinor() << std::endl; std::cout << "--------------------------- RPC ---------------------------" << std::endl; rps.SetName("New name"); rps.SetVersion(100, 500); std::cout << "--------------------------- RPC ---------------------------" << std::endl; std::cout << "New name: " << rps.GetName() << std::endl; std::cout << "New major: " << rps.GetMajor() << std::endl; std::cout << "New minor: " << rps.GetMinor() << std::endl; } catch (std::exception const &e) { std::cerr << "Error: " << e.what() << std::endl; } return 0; } */ namespace Mif { namespace Remote { } // namespace Remote } // namespace Mif namespace Mif { namespace Net { using Buffer = std::pair<std::size_t, boost::shared_array<char>>; struct IControl { virtual ~IControl() = default; virtual void CloseMe() = 0; }; using IControlPtr = std::shared_ptr<IControl>; struct IPublisher { virtual ~IPublisher() = default; virtual void Publish(Buffer buffer) = 0; }; using IPublisherPtr = std::shared_ptr<IPublisher>; struct ISubscriber { virtual ~ISubscriber() = default; virtual void OnData(Buffer buffer) = 0; }; using ISubscriberPtr = std::shared_ptr<ISubscriber>; struct ISubscriberFactory { virtual ~ISubscriberFactory() = default; virtual std::shared_ptr<ISubscriber> Create(std::weak_ptr<IControl> control, std::weak_ptr<IPublisher> publisher) = 0; }; class Client : public std::enable_shared_from_this<Client> , public ISubscriber { public: virtual ~Client() = default; Client(std::weak_ptr<IControl> control, std::weak_ptr<IPublisher> publisher) : m_control(control) , m_publisher(publisher) { } private: std::weak_ptr<IControl> m_control; std::weak_ptr<IPublisher> m_publisher; // ISubscriber virtual void OnData(Buffer buffer) override final { throw std::runtime_error{"OnData not implemented."}; } }; class ClientFactory final : public ISubscriberFactory { public: private: // ISubscriberFactory virtual std::shared_ptr<ISubscriber> Create(std::weak_ptr<IControl> control, std::weak_ptr<IPublisher> publisher) override { return std::make_shared<Client>(control, publisher); } }; } // namespace Net } // namespace Mif namespace Mif { namespace Net { namespace Detail { class TCPSession final : public std::enable_shared_from_this<TCPSession> , public IPublisher , public IControl { public: TCPSession(boost::asio::ip::tcp::socket socket, ISubscriberFactory &factory) : m_socket(std::move(socket)) , m_factory(factory) { } void Start() { m_subscriber = m_factory.Create(std::weak_ptr<IControl>(shared_from_this()), std::weak_ptr<IPublisher>(shared_from_this())); DoRead(); } private: boost::asio::ip::tcp::socket m_socket; ISubscriberFactory &m_factory; std::shared_ptr<ISubscriber> m_subscriber; //---------------------------------------------------------------------------- // IPublisher virtual void Publish(Buffer buffer) override { try { auto self(shared_from_this()); auto publisherTask = [self, buffer] () { boost::asio::async_write(self->m_socket, boost::asio::buffer(buffer.second.get(), buffer.first), [self, buffer] (boost::system::error_code error, std::size_t /*length*/) { if (error) { // TODO: error to log self->CloseMe(); } } ); }; m_socket.get_io_service().post(publisherTask); } catch (std::exception const &) { // TODO: to log CloseMe(); } } //---------------------------------------------------------------------------- // IControl virtual void CloseMe() override { try { auto self = shared_from_this(); m_socket.get_io_service().post([self] () { self->m_socket.close(); } ); } catch (std::exception const &) { // TODO: to log } } //---------------------------------------------------------------------------- void DoRead() { std::size_t const bytes = 4096; // TODO: from params auto buffer = std::make_pair(bytes, boost::shared_array<char>(new char [bytes])); auto self(shared_from_this()); m_socket.async_read_some(boost::asio::buffer(buffer.second.get(), buffer.first), [self, buffer] (boost::system::error_code error, std::size_t length) { try { if (!error) self->m_subscriber->OnData(std::move(buffer)); else self->CloseMe(); } catch (std::exception const &) { // TODO: to lgg self->CloseMe(); } } ); } }; class TCPServer final { public: TCPServer(std::string const &host, std::uint16_t port, std::uint16_t ioTreadCount, std::shared_ptr<ISubscriberFactory> factory) : m_factory(factory) , m_acceptor(m_ioService, boost::asio::ip::tcp::endpoint( boost::asio::ip::address::from_string(host), port) ) , m_socket(m_ioService) { std::unique_ptr<boost::asio::io_service::work> ioWork(new boost::asio::io_service::work(m_ioService)); for (std::uint16_t i = 0 ; i < ioTreadCount ; ++i) { std::exception_ptr exception{}; m_ioTreads.create_thread([this, &exception] () { try { m_ioService.run(); } catch (std::exception const &) { // TODO: to log exception = std::current_exception(); } } ); if (exception) { m_socket.close(); ioWork.reset(); m_ioTreads.join_all(); std::rethrow_exception(exception); } m_ioWork = std::move(ioWork); DoAccept(); } } virtual ~TCPServer() { try { m_socket.close(); m_ioWork.reset(); m_ioTreads.join_all(); } catch (std::exception const &) { // TODO: to log } } private: std::shared_ptr<ISubscriberFactory> m_factory; boost::asio::io_service m_ioService; std::unique_ptr<boost::asio::io_service::work> m_ioWork; boost::asio::ip::tcp::acceptor m_acceptor; boost::asio::ip::tcp::socket m_socket; boost::thread_group m_ioTreads; void DoAccept() { m_acceptor.async_accept(m_socket, [this] (boost::system::error_code error) { if (!error) { std::make_shared<TCPSession>(std::move(m_socket), *m_factory)->Start(); } DoAccept(); } ); } }; } // namespace Detail } // namespace Net } // namespace Mif int main() { try { auto server = std::make_shared<Mif::Net::Detail::TCPServer>( "127.0.0.1", 5555, 2, std::make_shared<Mif::Net::ClientFactory>()); std::cin.get(); } catch (std::exception const &e) { std::cerr << "Error: " << e.what() << std::endl; } } <commit_msg>Finish work on TCPServer and start work on TCPClients<commit_after>#include <iostream> #include <functional> #include <memory> #include <vector> #include <thread> #include <chrono> #include <boost/asio.hpp> #include <boost/shared_array.hpp> #include <boost/thread.hpp> /* #include <boost/archive/xml_iarchive.hpp> #include <boost/archive/xml_oarchive.hpp> #include "mif/remote/ps.h" #include "mif/remote/proxy_stub.h" #include "mif/remote/serialization/serialization.h" #include "mif/remote/serialization/boost/serialization.h" struct ITest { virtual ~ITest() = default; virtual void Print() = 0; virtual void SetVersion(int major, int minor) = 0; virtual void SetName(std::string const &name) = 0; virtual std::string GetName() = 0; virtual int GetMajor() const = 0; virtual int GetMinor() const = 0; }; MIF_REMOTE_PS_BEGIN(ITest) MIF_REMOTE_METHOD(Print) MIF_REMOTE_METHOD(SetVersion) MIF_REMOTE_METHOD(SetName) MIF_REMOTE_METHOD(GetName) MIF_REMOTE_METHOD(GetMajor) MIF_REMOTE_METHOD(GetMinor) MIF_REMOTE_PS_END() class Test final : public ITest { private: std::string m_name{"TestDefault"}; int m_major{0}; int m_minor{0}; virtual void Print() override { std::cout << "[Test::Print] Name\"" << m_name << "\" Major " << m_major << " Minor " << m_minor << std::endl; } virtual void SetVersion(int major, int minor) override { std::cout << "[Test::SetVersion] New major " << major << " New minor " << minor << std::endl; m_major = major; m_minor = minor; } virtual void SetName(std::string const &name) override { std::cout << "[Test::SetName] New name \"" << name << "\"" << std::endl; m_name = name; } virtual std::string GetName() override { std::cout << "[Test::GetName] Name \"" << m_name << "\"" << std::endl; return m_name; } virtual int GetMajor() const override { std::cout << "[Test::GetMajor] Major " << m_major << std::endl; return m_major; } virtual int GetMinor() const override { std::cout << "[Test::GetMinor] Minor " << m_minor << std::endl; return m_minor; } }; class TestTransport; TestTransport *p_transport = nullptr; class TestTransport { public: virtual ~TestTransport() = default; TestTransport() { } using Buffer = std::vector<char>; using DataHandler = std::function<Buffer (Buffer &&)>; DataHandler m_handler; void SetHandler(DataHandler && handler) { p_transport = this; m_handler = std::move(handler); } Buffer Send(Buffer && buffer); Buffer Call(Buffer && buffer) { return m_handler(std::move(buffer)); } }; TestTransport::Buffer TestTransport::Send(Buffer && buffer) { return p_transport->Call(std::move(buffer)); } int main() { try { using BoostSerializer = Mif::Remote::Serialization::Boost::Serializer<boost::archive::xml_oarchive>; using BoostDeserializer = Mif::Remote::Serialization::Boost::Deserializer<boost::archive::xml_iarchive>; using SerializerTraits = Mif::Remote::Serialization::SerializerTraits<BoostSerializer, BoostDeserializer>; using ProxyStub = ITest_PS<Mif::Remote::Proxy<SerializerTraits, TestTransport>, Mif::Remote::Stub<SerializerTraits, TestTransport>>; TestTransport proxyTransport; TestTransport stubTransport; ProxyStub::Stub stub("100500", std::make_shared<Test>(), std::move(stubTransport)); stub.Init(); ProxyStub::Proxy proxy("100500", std::move(proxyTransport)); ITest &rps = proxy; std::cout << "Old name: " << rps.GetName() << std::endl; std::cout << "Old major: " << rps.GetMajor() << std::endl; std::cout << "Old minor: " << rps.GetMinor() << std::endl; std::cout << "--------------------------- RPC ---------------------------" << std::endl; rps.SetName("New name"); rps.SetVersion(100, 500); std::cout << "--------------------------- RPC ---------------------------" << std::endl; std::cout << "New name: " << rps.GetName() << std::endl; std::cout << "New major: " << rps.GetMajor() << std::endl; std::cout << "New minor: " << rps.GetMinor() << std::endl; } catch (std::exception const &e) { std::cerr << "Error: " << e.what() << std::endl; } return 0; } */ namespace Mif { namespace Remote { } // namespace Remote } // namespace Mif namespace Mif { namespace Common { class ThreadPool final { public: using Task = std::function<void ()>; ThreadPool(std::uint16_t count) : m_work{new boost::asio::io_service::work{m_ioService}} { if (!count) throw std::invalid_argument{"[Mif::Common::ThreadPool] Thread count must be more than 0."}; std::exception_ptr exception{}; for ( ; count ; --count) { m_threads.create_thread([this, &exception] () { try { m_ioService.run(); } catch (std::exception const &e) { exception = std::current_exception(); // TODO: to log std::cerr << "Failed to run thread pool. Error: " << e.what() << std::endl; } } ); if (exception) break; } if (exception) { if (count) Stop(); try { std::rethrow_exception(exception); } catch (std::exception const &e) { throw std::runtime_error{"[Mif::Common::ThreadPool] Failed to run thread pool. " "Error: " + std::string{e.what()}}; } } } ~ThreadPool() { Stop(); } void Post(Task task) { m_ioService.post(task); } private: boost::asio::io_service m_ioService; std::unique_ptr<boost::asio::io_service::work> m_work; boost::thread_group m_threads; void Stop() { try { m_work.reset(); m_ioService.post([this] () { m_ioService.stop(); }); m_threads.join_all(); } catch (std::exception const &e) { // TODO: to log std::cerr << "[Mif::Common::ThreadPool::Stop] Failed to stop thread pool. Error: " << e.what() << std::endl; } } }; } // namespace Common } // namespace Mif namespace Mif { namespace Net { using Buffer = std::pair<std::size_t, boost::shared_array<char>>; struct IControl { virtual ~IControl() = default; virtual void CloseMe() = 0; }; struct IPublisher { virtual ~IPublisher() = default; virtual void Publish(Buffer buffer) = 0; }; struct ISubscriber { virtual ~ISubscriber() = default; virtual void OnData(Buffer buffer) = 0; }; struct ISubscriberFactory { virtual ~ISubscriberFactory() = default; virtual std::shared_ptr<ISubscriber> Create(std::weak_ptr<IControl> control, std::weak_ptr<IPublisher> publisher) = 0; }; class Client : public std::enable_shared_from_this<Client> , public ISubscriber { public: virtual ~Client() = default; Client(std::weak_ptr<IControl> control, std::weak_ptr<IPublisher> publisher) : m_control(control) , m_publisher(publisher) { } private: std::weak_ptr<IControl> m_control; std::weak_ptr<IPublisher> m_publisher; // ISubscriber virtual void OnData(Buffer buffer) override final { //std::cout << std::this_thread::get_id() << std::endl; //std::cout << "Readed " << buffer.first << " bytes." << std::endl; //throw std::runtime_error{"OnData not implemented."}; char const resp[] = "HTTP/1.x 200 OK\r\nContent-Length: 0\r\nConnection: Closed\r\n\r\n"; boost::shared_array<char> r(new char [sizeof(resp)]); char *p = r.get(); char const *s = &resp[0]; while(*p++ = *s++); Buffer b = std::make_pair(sizeof(resp) - 1, r); m_publisher.lock()->Publish(b); m_control.lock()->CloseMe(); } }; class ClientFactory final : public ISubscriberFactory { public: private: // ISubscriberFactory virtual std::shared_ptr<ISubscriber> Create(std::weak_ptr<IControl> control, std::weak_ptr<IPublisher> publisher) override { return std::make_shared<Client>(control, publisher); } }; } // namespace Net } // namespace Mif namespace Mif { namespace Net { namespace Detail { class TCPSession final : public std::enable_shared_from_this<TCPSession> , public IPublisher , public IControl { public: TCPSession(boost::asio::ip::tcp::socket socket, Common::ThreadPool &workers, ISubscriberFactory &factory) : m_socket(std::move(socket)) , m_workers(workers) , m_factory(factory) { //std::cout << "TCPSession" << std::endl; } ~TCPSession() { //std::cout << "~TCPSession" << std::endl; } void Start() { m_subscriber = m_factory.Create(std::weak_ptr<IControl>(shared_from_this()), std::weak_ptr<IPublisher>(shared_from_this())); DoRead(); } private: boost::asio::ip::tcp::socket m_socket; Common::ThreadPool &m_workers; ISubscriberFactory &m_factory; std::shared_ptr<ISubscriber> m_subscriber; //---------------------------------------------------------------------------- // IPublisher virtual void Publish(Buffer buffer) override { try { auto self(shared_from_this()); m_socket.get_io_service().post([self, buffer] () { boost::asio::async_write(self->m_socket, boost::asio::buffer(buffer.second.get(), buffer.first), [self, buffer] (boost::system::error_code error, std::size_t /*length*/) { if (error) { // TODO: error to log self->CloseMe(); std::cout << "OnWrite error." << std::endl; } } ); } ); } catch (std::exception const &) { // TODO: to log CloseMe(); } } //---------------------------------------------------------------------------- // IControl virtual void CloseMe() override { auto self = shared_from_this(); m_socket.get_io_service().post([self] () { try { self->m_socket.close(); } catch (std::exception const &e) { std::cerr << "CloseMe error: " << e.what() << std::endl; // TODO: to log } } ); } //---------------------------------------------------------------------------- void DoRead() { std::size_t const bytes = 4096; // TODO: from params auto buffer = std::make_pair(bytes, boost::shared_array<char>(new char [bytes])); auto self(shared_from_this()); m_socket.async_read_some(boost::asio::buffer(buffer.second.get(), buffer.first), [self, buffer] (boost::system::error_code error, std::size_t length) { try { if (!error) { self->m_workers.Post([self, length, buffer] () { try { self->m_subscriber->OnData(std::make_pair(length, std::move(buffer.second))); } catch (std::exception const &e) { // TODO: to log std::cerr << "Failed to process data. Error: " << e.what() << std::endl; } } ); self->DoRead(); } else { // TODO: to log self->CloseMe(); //std::cerr << "Failed to process data." << std::endl; } } catch (std::exception const &e) { // TODO: to lgg self->CloseMe(); std::cerr << "Failed to process data. Error: " << e.what() << std::endl; } } ); } }; class TCPServer final { public: TCPServer(std::string const &host, std::string const &port, std::uint16_t workers, std::shared_ptr<ISubscriberFactory> factory) try : m_factory{factory} , m_workers{std::make_shared<Common::ThreadPool>(workers)} , m_acceptor{m_ioService, [this, &host, &port] () -> boost::asio::ip::tcp::endpoint { boost::asio::ip::tcp::resolver resolver{m_ioService}; boost::asio::ip::tcp::resolver::query query{host, port}; return *resolver.resolve(query); } () } , m_socket{m_ioService} , m_work{m_ioService} { std::exception_ptr exception{}; m_thread.reset(new std::thread([this, &exception] () { try { m_ioService.run(); } catch (std::exception const &e) { exception = std::current_exception(); } } ) ); if (exception) std::rethrow_exception(exception); DoAccept(); } catch (std::exception const &e) { throw std::runtime_error{"[Mif::Net::Detail::TCPServer] Failed to start server. " "Error: " + std::string{e.what()}}; } catch (...) { throw std::runtime_error{"[Mif::Net::Detail::TCPServer] Failed to start server. Error: unknown."}; } virtual ~TCPServer() { try { m_ioService.post([this] () { try { m_ioService.stop(); } catch (std::exception const &e) { std::cerr << "[Mif::Net::Detail::~TCPServer] Failed to post 'stop' to server object. Error: " << e.what() << std::endl; } } ); m_thread->join(); } catch (std::exception const &e) { std::cerr << "[Mif::Net::Detail::~TCPServer] Failed to stop server. Error: " << e.what() << std::endl; } } private: std::shared_ptr<ISubscriberFactory> m_factory; std::shared_ptr<Common::ThreadPool> m_workers; std::unique_ptr<std::thread> m_thread; boost::asio::io_service m_ioService; boost::asio::ip::tcp::acceptor m_acceptor; boost::asio::ip::tcp::socket m_socket; boost::asio::io_service::work m_work; void DoAccept() { m_acceptor.async_accept(m_socket, [this] (boost::system::error_code error) { try { if (!error) std::make_shared<TCPSession>(std::move(m_socket), *m_workers, *m_factory)->Start(); else { std::cerr << "[Mif::Net::Detail::TCPServer::DoAccept] Failed tp accept connection." << std::endl; } DoAccept(); } catch (std::exception const &e) { std::cerr << "[Mif::Net::Detail::TCPServer::DoAccept] Failed to accept connection. Error: " << e.what() << std::endl; } } ); } }; class TCPClients final { public: TCPClients() { ; } ~TCPClients() { ; } private: }; } // namespace Detail } // namespace Net } // namespace Mif int main() { try { auto server = std::make_shared<Mif::Net::Detail::TCPServer>( "localhost", "5555", 4, std::make_shared<Mif::Net::ClientFactory>()); std::cin.get(); } catch (std::exception const &e) { std::cerr << "Error: " << e.what() << std::endl; } } <|endoftext|>
<commit_before>#include <string> #include <iostream> #include <fstream> #include <iomanip> using namespace std; #include "options.hpp" #include "version.h" #include "latticePair.hpp" int main(int argc, char * argv[]) { ifstream theFile; CmdLineOptions parsedOptions(argc, argv); if ( !parsedOptions.getQuiet() ) cout << "awg20400-lattice-gen " << GIT_VERSION << endl; if ( parsedOptions.getDebug() ) { cout << "Command invoked as: " << argv[0]; for(int arg=1; arg<argc; arg++) { cout << ' ' << argv[arg]; } cout << "\n"; } if ( parsedOptions.getHelp() ) { parsedOptions.printUsage(); return -1; } string inputFilePath("AWGSpec.csv"); if ( parsedOptions.getInputPath().size() > 0 ) inputFilePath = parsedOptions.getInputPath(); if ( !parsedOptions.getQuiet() ) cout << "\nReading file from: \"" << inputFilePath << "\"\n"; theFile.open(inputFilePath.c_str()); if (!theFile.is_open() || !theFile.good()) { cerr << "Problem opening data file!" << endl; theFile.close(); return -1; } string theLine; unsigned int linesRead(0); latticePair ourPair; bool syntaxOK(true); while( theFile.good() ) { std::getline(theFile, theLine); theFile.peek(); linesRead++; if ( parsedOptions.getDebug() ) cout << setw(4) << linesRead << " | " << theLine << "\n"; if ( !ourPair.processLine(theLine, true) ) { syntaxOK = false; cerr << "\tSyntax error on line " << linesRead << endl; } } if ( !syntaxOK ) { cerr << "Problems reading file, correct it and try again later" << endl; return -1; } if ( !parsedOptions.getQuiet() ) cout << "Done reading file." << endl; ofstream outputFiles("Master.AWG.txt"); if ( outputFiles.is_open() && outputFiles.good() ) { outputFiles << ourPair.masterProgrammingString(); outputFiles.close(); if (! parsedOptions.getQuiet()) cout << "Commands saved to Master.AWG.txt" << endl; } outputFiles.open("Slave.AWG.txt"); if ( outputFiles.is_open() && outputFiles.good() ) { outputFiles << ourPair.slaveProgrammingString(); outputFiles.close(); if (! parsedOptions.getQuiet()) cout << "Commands saved to Slave.AWG.txt" << endl; } return 0; } <commit_msg>Switch filenames to #define s<commit_after>#include <string> #include <iostream> #include <fstream> #include <iomanip> using namespace std; #include "options.hpp" #include "version.h" #include "latticePair.hpp" #define MASTER_FILE "Master.AWG.txt" #define SLAVE_FILE "Slave.AWG.txt" int main(int argc, char * argv[]) { ifstream theFile; CmdLineOptions parsedOptions(argc, argv); if ( !parsedOptions.getQuiet() ) cout << "awg20400-lattice-gen " << GIT_VERSION << endl; if ( parsedOptions.getDebug() ) { cout << "Command invoked as: " << argv[0]; for(int arg=1; arg<argc; arg++) { cout << ' ' << argv[arg]; } cout << "\n"; } if ( parsedOptions.getHelp() ) { parsedOptions.printUsage(); return -1; } string inputFilePath("AWGSpec.csv"); if ( parsedOptions.getInputPath().size() > 0 ) inputFilePath = parsedOptions.getInputPath(); if ( !parsedOptions.getQuiet() ) cout << "\nReading file from: \"" << inputFilePath << "\"\n"; theFile.open(inputFilePath.c_str()); if (!theFile.is_open() || !theFile.good()) { cerr << "Problem opening data file!" << endl; theFile.close(); return -1; } string theLine; unsigned int linesRead(0); latticePair ourPair; bool syntaxOK(true); while( theFile.good() ) { std::getline(theFile, theLine); theFile.peek(); linesRead++; if ( parsedOptions.getDebug() ) cout << setw(4) << linesRead << " | " << theLine << "\n"; if ( !ourPair.processLine(theLine, true) ) { syntaxOK = false; cerr << "\tSyntax error on line " << linesRead << endl; } } if ( !syntaxOK ) { cerr << "Problems reading file, correct it and try again later" << endl; return -1; } if ( !parsedOptions.getQuiet() ) cout << "Done reading file." << endl; ofstream outputFiles(MASTER_FILE); if ( outputFiles.is_open() && outputFiles.good() ) { outputFiles << ourPair.masterProgrammingString(); outputFiles.close(); if (! parsedOptions.getQuiet()) cout << "Commands saved to" << MASTER_FILE << endl; } outputFiles.open("Slave.AWG.txt"); if ( outputFiles.is_open() && outputFiles.good() ) { outputFiles << ourPair.slaveProgrammingString(); outputFiles.close(); if (! parsedOptions.getQuiet()) cout << "Commands saved to" << SLAVE_FILE << endl; } return 0; } <|endoftext|>
<commit_before>#include <cassert> #include <algorithm> #include <cmath> #include "scene.h" #include "monte_carlo/util.h" #include "monte_carlo/distribution1d.h" #include "integrator/surface_integrator.h" void SurfaceIntegrator::preprocess(const Scene&){} Colorf SurfaceIntegrator::spec_reflect(const RayDifferential &ray, const BSDF &bsdf, const Renderer &renderer, const Scene &scene, Sampler &sampler, MemoryPool &pool) { const Normal &n = bsdf.dg.normal; const Point &p = bsdf.dg.point; Vector w_o = -ray.d; Vector w_i; float pdf_val = 0; int n_samples = 1; std::array<float, 2> u_sample; float c_sample = 0; sampler.get_samples(&u_sample, n_samples); sampler.get_samples(&c_sample, n_samples); //Compute the color reflected off the BSDF Colorf reflected{0}; Colorf f = bsdf.sample(w_o, w_i, u_sample, c_sample, pdf_val, BxDFTYPE(BxDFTYPE::REFLECTION | BxDFTYPE::SPECULAR)); if (pdf_val > 0 && !f.is_black() && std::abs(w_i.dot(n)) != 0){ RayDifferential refl{p, w_i, ray, 0.001}; if (ray.has_differentials()){ refl.rx = Ray{p + bsdf.dg.dp_dx, w_i, ray, 0.001}; refl.ry = Ray{p + bsdf.dg.dp_dy, w_i, ray, 0.001}; //We compute dn_dx and dn_dy as described in PBR since we're following their differential //geometry method, the rest of the computation is directly from Igehy's paper auto dn_dx = Vector{bsdf.dg.dn_du * bsdf.dg.du_dx + bsdf.dg.dn_dv * bsdf.dg.dv_dx}; auto dn_dy = Vector{bsdf.dg.dn_du * bsdf.dg.du_dy + bsdf.dg.dn_dv * bsdf.dg.dv_dy}; auto dd_dx = -ray.rx.d - w_o; auto dd_dy = -ray.ry.d - w_o; float ddn_dx = dd_dx.dot(n) + w_o.dot(dn_dx); float ddn_dy = dd_dy.dot(n) + w_o.dot(dn_dy); refl.rx.d = w_i - dd_dx + 2 * Vector{w_o.dot(n) * dn_dx + Vector{ddn_dx * n}}; refl.ry.d = w_i - dd_dy + 2 * Vector{w_o.dot(n) * dn_dy + Vector{ddn_dy * n}}; } Colorf li = renderer.illumination(refl, scene, sampler, pool); reflected = f * li * std::abs(w_i.dot(n)) / pdf_val; } return reflected / n_samples; } Colorf SurfaceIntegrator::spec_transmit(const RayDifferential &ray, const BSDF &bsdf, const Renderer &renderer, const Scene &scene, Sampler &sampler, MemoryPool &pool) { const Normal &n = bsdf.dg.normal; const Point &p = bsdf.dg.point; Vector w_o = -ray.d; Vector w_i; float pdf_val = 0; std::array<float, 2> u_sample; float c_sample; sampler.get_samples(&u_sample, 1); sampler.get_samples(&c_sample, 1); Colorf f = bsdf.sample(w_o, w_i, u_sample, c_sample, pdf_val, BxDFTYPE(BxDFTYPE::TRANSMISSION | BxDFTYPE::SPECULAR)); //Compute the color transmitted through the BSDF Colorf transmitted{0}; if (pdf_val > 0 && f.is_black() && std::abs(w_i.dot(n)) != 0){ RayDifferential refr_ray{p, w_i, ray, 0.001}; if (ray.has_differentials()){ refr_ray.rx = Ray{p + bsdf.dg.dp_dx, w_i, ray, 0.001}; refr_ray.ry = Ray{p + bsdf.dg.dp_dy, w_i, ray, 0.001}; float eta = w_o.dot(n) < 0 ? 1 / bsdf.eta : bsdf.eta; //We compute dn_dx and dn_dy as described in PBR since we're following their differential //geometry method, the rest of the computation is directly from Igehy's paper auto dn_dx = Vector{bsdf.dg.dn_du * bsdf.dg.du_dx + bsdf.dg.dn_dv * bsdf.dg.dv_dx}; auto dn_dy = Vector{bsdf.dg.dn_du * bsdf.dg.du_dy + bsdf.dg.dn_dv * bsdf.dg.dv_dy}; auto dd_dx = -ray.rx.d - w_o; auto dd_dy = -ray.ry.d - w_o; float ddn_dx = dd_dx.dot(n) + w_o.dot(dn_dx); float ddn_dy = dd_dy.dot(n) + w_o.dot(dn_dy); float mu = eta * ray.d.dot(n) - w_i.dot(n); float dmu_dx = (eta - eta * eta * ray.d.dot(n) / w_i.dot(n)) * ddn_dx; float dmu_dy = (eta - eta * eta * ray.d.dot(n) / w_i.dot(n)) * ddn_dy; refr_ray.rx.d = w_i + eta * dd_dx - Vector{mu * dn_dx + Vector{dmu_dx * n}}; refr_ray.ry.d = w_i + eta * dd_dy - Vector{mu * dn_dy + Vector{dmu_dy * n}}; } Colorf li = renderer.illumination(refr_ray, scene, sampler, pool); transmitted = f * li * std::abs(w_i.dot(n)) / pdf_val; } return transmitted; } Colorf SurfaceIntegrator::uniform_sample_one_light(const Scene &scene, const Renderer &renderer, const Point &p, const Normal &n, const Vector &w_o, const BSDF &bsdf, const LightSample &l_sample, const BSDFSample &bsdf_sample) { int n_lights = scene.get_light_cache().size(); if (n_lights == 0){ return Colorf{0}; } int light_num = static_cast<int>(l_sample.light * n_lights); light_num = std::min(light_num, n_lights - 1); //The unordered map isn't a random access container, so 'find' the light_num light auto lit = std::find_if(scene.get_light_cache().begin(), scene.get_light_cache().end(), [&light_num](const auto&){ return light_num-- == 0; }); assert(lit != scene.get_light_cache().end()); return n_lights * estimate_direct(scene, renderer, p, n, w_o, bsdf, *lit->second, l_sample, bsdf_sample, BxDFTYPE(BxDFTYPE::ALL & ~BxDFTYPE::SPECULAR)); } Colorf SurfaceIntegrator::estimate_direct(const Scene &scene, const Renderer &, const Point &p, const Normal &n, const Vector &w_o, const BSDF &bsdf, const Light &light, const LightSample &l_sample, const BSDFSample &bsdf_sample, BxDFTYPE flags) { //We sample both the light source and the BSDF and weight them accordingly to sample both well Colorf direct_light; Vector w_i; float pdf_light = 0, pdf_bsdf = 0; OcclusionTester occlusion; //Sample the light Colorf li = light.sample(p, l_sample, w_i, pdf_light, occlusion); if (pdf_light > 0 && !li.is_black()){ Colorf f = bsdf(w_o, w_i, flags); if (!f.is_black() && !occlusion.occluded(scene)){ //If we have a delta distribution in the light we don't do MIS as it'd be incorrect //Otherwise we do MIS using the power heuristic if (light.delta_light()){ direct_light += f * li * std::abs(w_i.dot(n)) / pdf_light; } else { pdf_bsdf = bsdf.pdf(w_o, w_i, flags); float w = power_heuristic(1, pdf_light, 1, pdf_bsdf); direct_light += f * li * std::abs(w_i.dot(n)) * w / pdf_light; } } } //Sample the BSDF in the same manner as the light if (!light.delta_light()){ BxDFTYPE sampled_bxdf; Colorf f = bsdf.sample(w_o, w_i, bsdf_sample.u, bsdf_sample.comp, pdf_bsdf, flags, &sampled_bxdf); if (pdf_bsdf > 0 && !f.is_black()){ //Handle delta distributions in the BSDF the same way we did for the light float weight = 1; if (!(sampled_bxdf & BxDFTYPE::SPECULAR)){ pdf_light = light.pdf(p, w_i); if (pdf_light == 0){ return direct_light; } weight = power_heuristic(1, pdf_bsdf, 1, pdf_light); } //Find out if the ray along w_i actually hits the light source DifferentialGeometry dg; Colorf li; RayDifferential ray{p, w_i, 0.001}; if (scene.get_root().intersect(ray, dg)){ if (dg.node->get_area_light() == &light){ li = dg.node->get_area_light()->radiance(dg.point, dg.normal, -w_i); } } if (!li.is_black()){ direct_light += f * li * std::abs(w_i.dot(n)) * weight / pdf_bsdf; } } } return direct_light; } Distribution1D SurfaceIntegrator::light_sampling_cdf(const Scene &scene){ std::vector<float> light_power(scene.get_light_cache().size()); std::transform(scene.get_light_cache().begin(), scene.get_light_cache().end(), light_power.begin(), [&](const auto &l){ return l.second->power(scene).luminance(); }); return Distribution1D{light_power}; } <commit_msg>Fix bug in specular transmission<commit_after>#include <cassert> #include <algorithm> #include <cmath> #include "scene.h" #include "monte_carlo/util.h" #include "monte_carlo/distribution1d.h" #include "integrator/surface_integrator.h" void SurfaceIntegrator::preprocess(const Scene&){} Colorf SurfaceIntegrator::spec_reflect(const RayDifferential &ray, const BSDF &bsdf, const Renderer &renderer, const Scene &scene, Sampler &sampler, MemoryPool &pool) { const Normal &n = bsdf.dg.normal; const Point &p = bsdf.dg.point; Vector w_o = -ray.d; Vector w_i; float pdf_val = 0; int n_samples = 1; std::array<float, 2> u_sample; float c_sample = 0; sampler.get_samples(&u_sample, n_samples); sampler.get_samples(&c_sample, n_samples); //Compute the color reflected off the BSDF Colorf reflected{0}; Colorf f = bsdf.sample(w_o, w_i, u_sample, c_sample, pdf_val, BxDFTYPE(BxDFTYPE::REFLECTION | BxDFTYPE::SPECULAR)); if (pdf_val > 0 && !f.is_black() && std::abs(w_i.dot(n)) != 0){ RayDifferential refl{p, w_i, ray, 0.001}; if (ray.has_differentials()){ refl.rx = Ray{p + bsdf.dg.dp_dx, w_i, ray, 0.001}; refl.ry = Ray{p + bsdf.dg.dp_dy, w_i, ray, 0.001}; //We compute dn_dx and dn_dy as described in PBR since we're following their differential //geometry method, the rest of the computation is directly from Igehy's paper auto dn_dx = Vector{bsdf.dg.dn_du * bsdf.dg.du_dx + bsdf.dg.dn_dv * bsdf.dg.dv_dx}; auto dn_dy = Vector{bsdf.dg.dn_du * bsdf.dg.du_dy + bsdf.dg.dn_dv * bsdf.dg.dv_dy}; auto dd_dx = -ray.rx.d - w_o; auto dd_dy = -ray.ry.d - w_o; float ddn_dx = dd_dx.dot(n) + w_o.dot(dn_dx); float ddn_dy = dd_dy.dot(n) + w_o.dot(dn_dy); refl.rx.d = w_i - dd_dx + 2 * Vector{w_o.dot(n) * dn_dx + Vector{ddn_dx * n}}; refl.ry.d = w_i - dd_dy + 2 * Vector{w_o.dot(n) * dn_dy + Vector{ddn_dy * n}}; } Colorf li = renderer.illumination(refl, scene, sampler, pool); reflected = f * li * std::abs(w_i.dot(n)) / pdf_val; } return reflected / n_samples; } Colorf SurfaceIntegrator::spec_transmit(const RayDifferential &ray, const BSDF &bsdf, const Renderer &renderer, const Scene &scene, Sampler &sampler, MemoryPool &pool) { const Normal &n = bsdf.dg.normal; const Point &p = bsdf.dg.point; Vector w_o = -ray.d; Vector w_i; float pdf_val = 0; std::array<float, 2> u_sample; float c_sample; sampler.get_samples(&u_sample, 1); sampler.get_samples(&c_sample, 1); Colorf f = bsdf.sample(w_o, w_i, u_sample, c_sample, pdf_val, BxDFTYPE(BxDFTYPE::TRANSMISSION | BxDFTYPE::SPECULAR)); //Compute the color transmitted through the BSDF Colorf transmitted{0}; if (pdf_val > 0 && !f.is_black() && std::abs(w_i.dot(n)) != 0){ RayDifferential refr_ray{p, w_i, ray, 0.001}; if (ray.has_differentials()){ refr_ray.rx = Ray{p + bsdf.dg.dp_dx, w_i, ray, 0.001}; refr_ray.ry = Ray{p + bsdf.dg.dp_dy, w_i, ray, 0.001}; float eta = w_o.dot(n) < 0 ? 1 / bsdf.eta : bsdf.eta; //We compute dn_dx and dn_dy as described in PBR since we're following their differential //geometry method, the rest of the computation is directly from Igehy's paper auto dn_dx = Vector{bsdf.dg.dn_du * bsdf.dg.du_dx + bsdf.dg.dn_dv * bsdf.dg.dv_dx}; auto dn_dy = Vector{bsdf.dg.dn_du * bsdf.dg.du_dy + bsdf.dg.dn_dv * bsdf.dg.dv_dy}; auto dd_dx = -ray.rx.d - w_o; auto dd_dy = -ray.ry.d - w_o; float ddn_dx = dd_dx.dot(n) + w_o.dot(dn_dx); float ddn_dy = dd_dy.dot(n) + w_o.dot(dn_dy); float mu = eta * ray.d.dot(n) - w_i.dot(n); float dmu_dx = (eta - eta * eta * ray.d.dot(n) / w_i.dot(n)) * ddn_dx; float dmu_dy = (eta - eta * eta * ray.d.dot(n) / w_i.dot(n)) * ddn_dy; refr_ray.rx.d = w_i + eta * dd_dx - Vector{mu * dn_dx + Vector{dmu_dx * n}}; refr_ray.ry.d = w_i + eta * dd_dy - Vector{mu * dn_dy + Vector{dmu_dy * n}}; } Colorf li = renderer.illumination(refr_ray, scene, sampler, pool); transmitted = f * li * std::abs(w_i.dot(n)) / pdf_val; } return transmitted; } Colorf SurfaceIntegrator::uniform_sample_one_light(const Scene &scene, const Renderer &renderer, const Point &p, const Normal &n, const Vector &w_o, const BSDF &bsdf, const LightSample &l_sample, const BSDFSample &bsdf_sample) { int n_lights = scene.get_light_cache().size(); if (n_lights == 0){ return Colorf{0}; } int light_num = static_cast<int>(l_sample.light * n_lights); light_num = std::min(light_num, n_lights - 1); //The unordered map isn't a random access container, so 'find' the light_num light auto lit = std::find_if(scene.get_light_cache().begin(), scene.get_light_cache().end(), [&light_num](const auto&){ return light_num-- == 0; }); assert(lit != scene.get_light_cache().end()); return n_lights * estimate_direct(scene, renderer, p, n, w_o, bsdf, *lit->second, l_sample, bsdf_sample, BxDFTYPE(BxDFTYPE::ALL & ~BxDFTYPE::SPECULAR)); } Colorf SurfaceIntegrator::estimate_direct(const Scene &scene, const Renderer &, const Point &p, const Normal &n, const Vector &w_o, const BSDF &bsdf, const Light &light, const LightSample &l_sample, const BSDFSample &bsdf_sample, BxDFTYPE flags) { //We sample both the light source and the BSDF and weight them accordingly to sample both well Colorf direct_light; Vector w_i; float pdf_light = 0, pdf_bsdf = 0; OcclusionTester occlusion; //Sample the light Colorf li = light.sample(p, l_sample, w_i, pdf_light, occlusion); if (pdf_light > 0 && !li.is_black()){ Colorf f = bsdf(w_o, w_i, flags); if (!f.is_black() && !occlusion.occluded(scene)){ //If we have a delta distribution in the light we don't do MIS as it'd be incorrect //Otherwise we do MIS using the power heuristic if (light.delta_light()){ direct_light += f * li * std::abs(w_i.dot(n)) / pdf_light; } else { pdf_bsdf = bsdf.pdf(w_o, w_i, flags); float w = power_heuristic(1, pdf_light, 1, pdf_bsdf); direct_light += f * li * std::abs(w_i.dot(n)) * w / pdf_light; } } } //Sample the BSDF in the same manner as the light if (!light.delta_light()){ BxDFTYPE sampled_bxdf; Colorf f = bsdf.sample(w_o, w_i, bsdf_sample.u, bsdf_sample.comp, pdf_bsdf, flags, &sampled_bxdf); if (pdf_bsdf > 0 && !f.is_black()){ //Handle delta distributions in the BSDF the same way we did for the light float weight = 1; if (!(sampled_bxdf & BxDFTYPE::SPECULAR)){ pdf_light = light.pdf(p, w_i); if (pdf_light == 0){ return direct_light; } weight = power_heuristic(1, pdf_bsdf, 1, pdf_light); } //Find out if the ray along w_i actually hits the light source DifferentialGeometry dg; Colorf li; RayDifferential ray{p, w_i, 0.001}; if (scene.get_root().intersect(ray, dg)){ if (dg.node->get_area_light() == &light){ li = dg.node->get_area_light()->radiance(dg.point, dg.normal, -w_i); } } if (!li.is_black()){ direct_light += f * li * std::abs(w_i.dot(n)) * weight / pdf_bsdf; } } } return direct_light; } Distribution1D SurfaceIntegrator::light_sampling_cdf(const Scene &scene){ std::vector<float> light_power(scene.get_light_cache().size()); std::transform(scene.get_light_cache().begin(), scene.get_light_cache().end(), light_power.begin(), [&](const auto &l){ return l.second->power(scene).luminance(); }); return Distribution1D{light_power}; } <|endoftext|>
<commit_before>/****************************************************************************** * Fake Frog * * An Arduino-based project to build a frog-shaped temperature logger. * * Author: David Lougheed. Copyright 2017. * ******************************************************************************/ #define VERSION "0.1.0" // Includes #include <Arduino.h> #include <Wire.h> #include <LiquidCrystal.h> #include <SD.h> #include <RTClib.h> // Compile-Time Settings #define SERIAL_LOGGING true // Log to the serial display for debug. #define FILE_LOGGING true // Log to file on SD card. (recommended) #define DISPLAY_ENABLED true // Show menus and information on an LCD. #define NUM_SAMPLES 10 // Samples get averaged to reduce noise. #define SAMPLE_DELAY 10 // Milliseconds between samples. #define READING_INTERVAL 60 // Seconds between readings. // Hardware Settings // - The data logging shield uses A4, A5, and digital pins 10, 11, 12, and 13. #define NUM_THERMISTORS 4 #define THERMISTOR_1_PIN 0 // Analog pin #define THERMISTOR_2_PIN 1 // Analog pin #define THERMISTOR_3_PIN 2 // Analog pin #define THERMISTOR_4_PIN 3 // Analog pin const uint8_t thermistor_pins[NUM_THERMISTORS] = { THERMISTOR_1_PIN, THERMISTOR_2_PIN, THERMISTOR_3_PIN, THERMISTOR_4_PIN }; #define THERMISTOR_SERIES_RES 10000 #define THERMISTOR_RES_NOM 10000 // Nominal resistance, R0. #define THERMISTOR_B_COEFF 3950 // Beta coefficient of the thermistor. #define THERMISTOR_TEMP_NOM 25 // Nominal temperature of R0. #define BUTTON_1_PIN 2 #define BUTTON_2_PIN 3 #define SD_CARD_PIN 10 #define RTC_PIN_1 A4 // Analog pin #define RTC_PIN_2 A5 // Analog pin #define LCD_PIN_RS 4 #define LCD_PIN_EN 5 #define LCD_PIN_DB4 6 #define LCD_PIN_DB5 7 #define LCD_PIN_DB6 8 #define LCD_PIN_DB7 9 #define LCD_ROWS 2 #define LCD_COLUMNS 16 #define RTC_TYPE RTC_PCF8523 // Other Compile-Time Constants #define MAX_LOG_FILES 1000 #define MAX_DATA_FILES 1000 // Globals bool serial_logging_started = false; // - Files File log_file; File data_file; // - Hardware Objects RTC_TYPE rtc; LiquidCrystal* lcd; // - Data Point Variables // (to save memory, use global data point variables) DateTime now; char formatted_timestamp[] = "0000-00-00T00:00:00"; char* data_file_entry_buffer = (char*) malloc(sizeof(char) * 50); char temperature_string[4][8]; double latest_resistance[4]; double latest_temperature[4]; /* DISPLAY MODES (ALL WITH LOGGING) 0: Idle 1: Information (RAM free) 2: RTC Editor */ uint8_t display_mode = 0; uint16_t i, z; // 16-bit iterator uint8_t timer = 0; // Counts seconds uint32_t milli_timer = 0; // Counts time taken to do a loop uint32_t uptime = 0; bool button_1 = false; bool button_2 = false; // Utility Methods // Determine amount of free RAM. // - Retrieved 2017-05-19 (https://playground.arduino.cc/Code/AvailableMemory) int freeRAM() { extern int __heap_start, *__brkval; int v; return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval); } // Log a generic message. void log(const char* msg, bool with_newline = true) { if (SERIAL_LOGGING) { if(!serial_logging_started) { Serial.begin(9600); Serial.println(); serial_logging_started = true; } if (with_newline) { Serial.println(msg); } else { Serial.print(msg); } } if (FILE_LOGGING) { if (log_file) { if (with_newline) { log_file.println(msg); } else { log_file.print(msg); } } } } // Flush various logging buffers. void log_flush() { if (SERIAL_LOGGING) { Serial.flush(); } if (FILE_LOGGING) { log_file.flush(); } } // Log an error message. Uses standard log method, then hangs forever. void log_error(const char* msg, bool with_newline = true) { log(msg, with_newline); log_flush(); while (true); // Loop forever } // Update the LCD to display latest values for the set display mode. void update_display() { if (DISPLAY_ENABLED && lcd) { lcd->clear(); switch (display_mode) { case 1: // Information lcd->print("Free RAM: "); lcd->print(freeRAM(), 10); break; case 2: // RTC Editor lcd->print("TBD"); break; case 0: // Idle default: break; } } } // Switch the display mode, triggering a display update. void switch_display_mode(uint8_t m) { display_mode = m % 3; update_display(); } // Data Methods // Update the global formatted timestamp string with the contents of 'now'. void update_formatted_timestamp() { sprintf(formatted_timestamp, "%04u-%02u-%02uT%02u:%02u:%02u", now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second()); } double resistance_to_temperature(double resistance) { // Formula: T = 1/(1/B * ln(R/R_0) + (1/T0)) - 273.15 (celcius) return 1 / ((log(resistance / THERMISTOR_RES_NOM) / THERMISTOR_B_COEFF) + 1 / (THERMISTOR_TEMP_NOM + 273.15)) - 273.15; } void take_reading(uint8_t t) { now = rtc.now(); latest_resistance[t] = 0; for (i = 0; i < NUM_SAMPLES; i++) { latest_resistance[t] += (double) analogRead(thermistor_pins[t]); delay(SAMPLE_DELAY); } // Formulas: R = sr / (1023 / mean_of_samples - 1) // sr = thermistor series resistance latest_resistance[t] = THERMISTOR_SERIES_RES / (1023 / (latest_resistance[t] / NUM_SAMPLES) - 1); // Resistance latest_temperature[t] = resistance_to_temperature(latest_resistance[t]); // TODO: Error calculations } void save_reading_to_card() { if (data_file) { update_formatted_timestamp(); for (i = 0; i < NUM_THERMISTORS; i++) { dtostrf(latest_temperature[i], 5, 2, temperature_string[i]); } log("Took reading: ", false); log(formatted_timestamp, false); log(",", false); log(temperature_string[0], false); log(",", false); log(temperature_string[1], false); log(",", false); log(temperature_string[2], false); log(",", false); log(temperature_string[3]); log_flush(); data_file.print(formatted_timestamp); data_file.print(","); data_file.print(temperature_string[0]); data_file.print(","); data_file.print(temperature_string[1]); data_file.print(","); data_file.print(temperature_string[2]); data_file.print(","); data_file.println(temperature_string[3]); // data_file.println(data_file_entry_buffer); data_file.flush(); } } // Main Methods void setup() { // SET UP EXTERNAL ANALOG VOLTAGE REFERENCE // Typically from 3.3V Arduino supply. This reduces the voltage noise seen // from reading analog values. analogReference(EXTERNAL); // INITIALIZE SD CARD log("Initializing SD card... ", false); pinMode(SD_CARD_PIN, OUTPUT); if (!SD.begin()) { log_error("Failed."); } log("Done."); // SET UP LOG FILE if (FILE_LOGGING) { log("Creating log file... ", false); char log_file_name[] = "log_000.txt"; for (i = 0; i < MAX_LOG_FILES; i++) { // Increment until we can find a log file slot. // Need to add 48 to get ASCII number characters. log_file_name[4] = i / 100 + 48; log_file_name[5] = i / 10 + 48; log_file_name[6] = i % 10 + 48; if (!SD.exists(log_file_name)) { log_file = SD.open(log_file_name, FILE_WRITE); break; } } if (log_file) { log("Done."); } else { log_error("Failed."); } } // SET UP RTC log("Initializing RTC...", false); Wire.begin(); if (!rtc.begin()) { log_error("Failed."); } log("Done."); // INPUT RTC TIME if (SERIAL_LOGGING) { uint16_t year; uint8_t month, day, hour, minute, second; Serial.print("Change clock? (y/n) "); while (Serial.available() < 1); if (Serial.read() == 'y') { Serial.println(); Serial.print("Enter Year: "); while (Serial.available() < 4); year += (Serial.read() - 48) * 1000; year += (Serial.read() - 48) * 100; year += (Serial.read() - 48) * 10; year += (Serial.read() - 48); Serial.println(year); Serial.print("Enter Month: "); while (Serial.available() < 2); month += (Serial.read() - 48) * 10; month += (Serial.read() - 48); Serial.println(month); Serial.print("Enter Day: "); while (Serial.available() < 2); day += (Serial.read() - 48) * 10; day += (Serial.read() - 48); Serial.println(day); Serial.print("Enter Hour: "); while (Serial.available() < 2); hour += (Serial.read() - 48) * 10; hour += (Serial.read() - 48); Serial.println(hour); Serial.print("Enter Minute: "); while (Serial.available() < 2); minute += (Serial.read() - 48) * 10; minute += (Serial.read() - 48); Serial.println(minute); Serial.print("Enter Second: "); while (Serial.available() < 2); second += (Serial.read() - 48) * 10; second += (Serial.read() - 48); Serial.println(second); rtc.adjust(DateTime(year, month, day, hour, minute, second)); } } // SET UP DATA FILE log("Creating data file...", false); char data_file_name[] = "dat_000.csv"; for (i = 0; i < MAX_DATA_FILES; i++) { // Increment until we can find a data file slot. // Need to add 48 to get ASCII digit characters. data_file_name[4] = i / 100 + 48; data_file_name[5] = i / 10 + 48; data_file_name[6] = i % 10 + 48; if (!SD.exists(data_file_name)) { data_file = SD.open(data_file_name, FILE_WRITE); break; } } if (data_file) { log("Done."); } else { log_error("Failed."); } // PRINT DATA FILE CSV HEADERS data_file.println("Timestamp,Temp1,Temp2,Temp3,Temp4"); data_file.flush(); // SET UP LCD if (DISPLAY_ENABLED) { lcd = new LiquidCrystal(LCD_PIN_RS, LCD_PIN_EN, LCD_PIN_DB4, LCD_PIN_DB5, LCD_PIN_DB6, LCD_PIN_DB7); lcd->begin(LCD_COLUMNS, LCD_ROWS); update_display(); } // SET UP BUTTONS pinMode(BUTTON_1_PIN, INPUT); pinMode(BUTTON_2_PIN, INPUT); // Finished everything! now = rtc.now(); update_formatted_timestamp(); log("Data logger started at ", false); log(formatted_timestamp, false); log(". Software version: ", false); log(VERSION); log_flush(); } void loop() { // Time the loop to make sure it runs rounded to the nearest second. milli_timer = millis(); if (timer >= READING_INTERVAL) { timer = 0; for (z = 0; z < NUM_THERMISTORS; z++) { // Loop through all thermistors take_reading(z); } save_reading_to_card(); } milli_timer = millis() - milli_timer; while (milli_timer >= 1000) { // Prevent an integer overflow error by making sure milli_timer < 1000 timer++; // An extra second has occurred - don't let it slip away! milli_timer -= 1000; } timer++; uptime++; delay(1000 - milli_timer); // (Ideally) 1 second between loops } <commit_msg>Add a cursor position variable<commit_after>/****************************************************************************** * Fake Frog * * An Arduino-based project to build a frog-shaped temperature logger. * * Author: David Lougheed. Copyright 2017. * ******************************************************************************/ #define VERSION "0.1.0" // Includes #include <Arduino.h> #include <Wire.h> #include <LiquidCrystal.h> #include <SD.h> #include <RTClib.h> // Compile-Time Settings #define SERIAL_LOGGING true // Log to the serial display for debug. #define FILE_LOGGING true // Log to file on SD card. (recommended) #define DISPLAY_ENABLED true // Show menus and information on an LCD. #define NUM_SAMPLES 10 // Samples get averaged to reduce noise. #define SAMPLE_DELAY 10 // Milliseconds between samples. #define READING_INTERVAL 60 // Seconds between readings. // Hardware Settings // - The data logging shield uses A4, A5, and digital pins 10, 11, 12, and 13. #define NUM_THERMISTORS 4 #define THERMISTOR_1_PIN 0 // Analog pin #define THERMISTOR_2_PIN 1 // Analog pin #define THERMISTOR_3_PIN 2 // Analog pin #define THERMISTOR_4_PIN 3 // Analog pin const uint8_t thermistor_pins[NUM_THERMISTORS] = { THERMISTOR_1_PIN, THERMISTOR_2_PIN, THERMISTOR_3_PIN, THERMISTOR_4_PIN }; #define THERMISTOR_SERIES_RES 10000 #define THERMISTOR_RES_NOM 10000 // Nominal resistance, R0. #define THERMISTOR_B_COEFF 3950 // Beta coefficient of the thermistor. #define THERMISTOR_TEMP_NOM 25 // Nominal temperature of R0. #define BUTTON_1_PIN 2 #define BUTTON_2_PIN 3 #define SD_CARD_PIN 10 #define RTC_PIN_1 A4 // Analog pin #define RTC_PIN_2 A5 // Analog pin #define LCD_PIN_RS 4 #define LCD_PIN_EN 5 #define LCD_PIN_DB4 6 #define LCD_PIN_DB5 7 #define LCD_PIN_DB6 8 #define LCD_PIN_DB7 9 #define LCD_ROWS 2 #define LCD_COLUMNS 16 #define RTC_TYPE RTC_PCF8523 // Other Compile-Time Constants #define MAX_LOG_FILES 1000 #define MAX_DATA_FILES 1000 // Globals bool serial_logging_started = false; // - Files File log_file; File data_file; // - Hardware Objects RTC_TYPE rtc; LiquidCrystal* lcd; // - Data Point Variables // (to save memory, use global data point variables) DateTime now; char formatted_timestamp[] = "0000-00-00T00:00:00"; char* data_file_entry_buffer = (char*) malloc(sizeof(char) * 50); char temperature_string[4][8]; double latest_resistance[4]; double latest_temperature[4]; /* DISPLAY MODES (ALL WITH LOGGING) 0: Idle 1: Information (RAM free) 2: RTC Editor */ uint8_t display_mode = 0; uint16_t i, z; // 16-bit iterator uint8_t timer = 0; // Counts seconds uint32_t milli_timer = 0; // Counts time taken to do a loop uint32_t uptime = 0; uint8_t cursor = 0; // Maximum: 31 (second row, last column) bool button_1 = false; bool button_2 = false; // Utility Methods // Determine amount of free RAM. // - Retrieved 2017-05-19 (https://playground.arduino.cc/Code/AvailableMemory) int freeRAM() { extern int __heap_start, *__brkval; int v; return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval); } // Log a generic message. void log(const char* msg, bool with_newline = true) { if (SERIAL_LOGGING) { if(!serial_logging_started) { Serial.begin(9600); Serial.println(); serial_logging_started = true; } if (with_newline) { Serial.println(msg); } else { Serial.print(msg); } } if (FILE_LOGGING) { if (log_file) { if (with_newline) { log_file.println(msg); } else { log_file.print(msg); } } } } // Flush various logging buffers. void log_flush() { if (SERIAL_LOGGING) { Serial.flush(); } if (FILE_LOGGING) { log_file.flush(); } } // Log an error message. Uses standard log method, then hangs forever. void log_error(const char* msg, bool with_newline = true) { log(msg, with_newline); log_flush(); while (true); // Loop forever } // Update the LCD to display latest values for the set display mode. void update_display() { if (DISPLAY_ENABLED && lcd) { lcd->clear(); cursor = 0; switch (display_mode) { case 1: // Information lcd->print("Free RAM: "); lcd->print(freeRAM(), 10); lcd->noBlink(); break; case 2: // RTC Editor lcd->print("TBD"); lcd->setCursor(0, 0); lcd->blink(); break; case 0: // Idle default: lcd->noBlink(); break; } } } // Switch the display mode, triggering a display update. void switch_display_mode(uint8_t m) { display_mode = m % 3; update_display(); } // Data Methods // Update the global formatted timestamp string with the contents of 'now'. void update_formatted_timestamp() { sprintf(formatted_timestamp, "%04u-%02u-%02uT%02u:%02u:%02u", now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second()); } double resistance_to_temperature(double resistance) { // Formula: T = 1/(1/B * ln(R/R_0) + (1/T0)) - 273.15 (celcius) return 1 / ((log(resistance / THERMISTOR_RES_NOM) / THERMISTOR_B_COEFF) + 1 / (THERMISTOR_TEMP_NOM + 273.15)) - 273.15; } void take_reading(uint8_t t) { now = rtc.now(); latest_resistance[t] = 0; for (i = 0; i < NUM_SAMPLES; i++) { latest_resistance[t] += (double) analogRead(thermistor_pins[t]); delay(SAMPLE_DELAY); } // Formulas: R = sr / (1023 / mean_of_samples - 1) // sr = thermistor series resistance latest_resistance[t] = THERMISTOR_SERIES_RES / (1023 / (latest_resistance[t] / NUM_SAMPLES) - 1); // Resistance latest_temperature[t] = resistance_to_temperature(latest_resistance[t]); // TODO: Error calculations } void save_reading_to_card() { if (data_file) { update_formatted_timestamp(); for (i = 0; i < NUM_THERMISTORS; i++) { dtostrf(latest_temperature[i], 5, 2, temperature_string[i]); } log("Took reading: ", false); log(formatted_timestamp, false); log(",", false); log(temperature_string[0], false); log(",", false); log(temperature_string[1], false); log(",", false); log(temperature_string[2], false); log(",", false); log(temperature_string[3]); log_flush(); data_file.print(formatted_timestamp); data_file.print(","); data_file.print(temperature_string[0]); data_file.print(","); data_file.print(temperature_string[1]); data_file.print(","); data_file.print(temperature_string[2]); data_file.print(","); data_file.println(temperature_string[3]); // data_file.println(data_file_entry_buffer); data_file.flush(); } } // Main Methods void setup() { // SET UP EXTERNAL ANALOG VOLTAGE REFERENCE // Typically from 3.3V Arduino supply. This reduces the voltage noise seen // from reading analog values. analogReference(EXTERNAL); // INITIALIZE SD CARD log("Initializing SD card... ", false); pinMode(SD_CARD_PIN, OUTPUT); if (!SD.begin()) { log_error("Failed."); } log("Done."); // SET UP LOG FILE if (FILE_LOGGING) { log("Creating log file... ", false); char log_file_name[] = "log_000.txt"; for (i = 0; i < MAX_LOG_FILES; i++) { // Increment until we can find a log file slot. // Need to add 48 to get ASCII number characters. log_file_name[4] = i / 100 + 48; log_file_name[5] = i / 10 + 48; log_file_name[6] = i % 10 + 48; if (!SD.exists(log_file_name)) { log_file = SD.open(log_file_name, FILE_WRITE); break; } } if (log_file) { log("Done."); } else { log_error("Failed."); } } // SET UP RTC log("Initializing RTC...", false); Wire.begin(); if (!rtc.begin()) { log_error("Failed."); } log("Done."); // INPUT RTC TIME if (SERIAL_LOGGING) { uint16_t year; uint8_t month, day, hour, minute, second; Serial.print("Change clock? (y/n) "); while (Serial.available() < 1); if (Serial.read() == 'y') { Serial.println(); Serial.print("Enter Year: "); while (Serial.available() < 4); year += (Serial.read() - 48) * 1000; year += (Serial.read() - 48) * 100; year += (Serial.read() - 48) * 10; year += (Serial.read() - 48); Serial.println(year); Serial.print("Enter Month: "); while (Serial.available() < 2); month += (Serial.read() - 48) * 10; month += (Serial.read() - 48); Serial.println(month); Serial.print("Enter Day: "); while (Serial.available() < 2); day += (Serial.read() - 48) * 10; day += (Serial.read() - 48); Serial.println(day); Serial.print("Enter Hour: "); while (Serial.available() < 2); hour += (Serial.read() - 48) * 10; hour += (Serial.read() - 48); Serial.println(hour); Serial.print("Enter Minute: "); while (Serial.available() < 2); minute += (Serial.read() - 48) * 10; minute += (Serial.read() - 48); Serial.println(minute); Serial.print("Enter Second: "); while (Serial.available() < 2); second += (Serial.read() - 48) * 10; second += (Serial.read() - 48); Serial.println(second); rtc.adjust(DateTime(year, month, day, hour, minute, second)); } } // SET UP DATA FILE log("Creating data file...", false); char data_file_name[] = "dat_000.csv"; for (i = 0; i < MAX_DATA_FILES; i++) { // Increment until we can find a data file slot. // Need to add 48 to get ASCII digit characters. data_file_name[4] = i / 100 + 48; data_file_name[5] = i / 10 + 48; data_file_name[6] = i % 10 + 48; if (!SD.exists(data_file_name)) { data_file = SD.open(data_file_name, FILE_WRITE); break; } } if (data_file) { log("Done."); } else { log_error("Failed."); } // PRINT DATA FILE CSV HEADERS data_file.println("Timestamp,Temp1,Temp2,Temp3,Temp4"); data_file.flush(); // SET UP LCD if (DISPLAY_ENABLED) { lcd = new LiquidCrystal(LCD_PIN_RS, LCD_PIN_EN, LCD_PIN_DB4, LCD_PIN_DB5, LCD_PIN_DB6, LCD_PIN_DB7); lcd->begin(LCD_COLUMNS, LCD_ROWS); update_display(); } // SET UP BUTTONS pinMode(BUTTON_1_PIN, INPUT); pinMode(BUTTON_2_PIN, INPUT); // Finished everything! now = rtc.now(); update_formatted_timestamp(); log("Data logger started at ", false); log(formatted_timestamp, false); log(". Software version: ", false); log(VERSION); log_flush(); } void loop() { // Time the loop to make sure it runs rounded to the nearest second. milli_timer = millis(); if (timer >= READING_INTERVAL) { timer = 0; for (z = 0; z < NUM_THERMISTORS; z++) { // Loop through all thermistors take_reading(z); } save_reading_to_card(); } milli_timer = millis() - milli_timer; while (milli_timer >= 1000) { // Prevent an integer overflow error by making sure milli_timer < 1000 timer++; // An extra second has occurred - don't let it slip away! milli_timer -= 1000; } timer++; uptime++; delay(1000 - milli_timer); // (Ideally) 1 second between loops } <|endoftext|>
<commit_before>#ifndef __TEST_CPP__ #define __TEST_CPP__ #include <unistd.h> #include <stdio.h> #include <sys/wait.h> #include <sys/types.h> #include <sys/stat.h> #include <cstdlib> #include <string> #include <cstring> #include <vector> #include <queue> #include <sstream> #include <dirent.h> #include <iostream> using namespace std; #include "Test.h" #include "Base.h" //constructors Test::Test(char* command, queue<char *> flags) { this->command = command; this->flags = flags; } Test::Test(queue<char*> flags) { this->flags = flags; } Test::Test() {} //push any new flags into the queue<char *> flags void Test::add_flag(char*a) { flags.push(a); } //Used for the Exit Command to fix Exit bug string Test::get_data() { return command; } //executes the test according the flag specified //if flag == -e it will be tested to see if it is either a directory or a regular file //if flag == -f it will be tested to see if it is a regular file //if flag == -d it will be tested to see if it is a directory //if no flag is provided then -e will be assumed bool Test::execute(int in, int out) { struct stat buf; string flag; string path; bool exists = false; if(flags.size() == 1) { flag = "-e"; path = flags.front(); } else { //cout << flags.front() << endl; flag = flags.front(); flags.pop(); //cout << flags.front() << endl; path = flags.front(); } //cout << path << endl; int statret = stat(path.c_str(),&buf); if (statret == 0) { exists = true; } dup2(in,0); dup2(out,1); if(statret == -1) { perror("stat"); return false; } if(flag == "-e") { cout << "(true)" << endl; return exists; } else if(flag == "-d") { if(S_ISDIR(buf.st_mode)) { cout << "(true)" << endl; return true; } else { cout << "(false)" << endl; return false; } } else if(flag == "-f") { if(S_ISREG(buf.st_mode)) { cout << "(true)" << endl; return true; } else { cout << "(false)" << endl; return false; } } else { cout << "Error: In test flag " << flag << " is not valid." << endl; return false; } } #endif <commit_msg>added in error checking to dup calls<commit_after>#ifndef __TEST_CPP__ #define __TEST_CPP__ #include <unistd.h> #include <stdio.h> #include <sys/wait.h> #include <sys/types.h> #include <sys/stat.h> #include <cstdlib> #include <string> #include <cstring> #include <vector> #include <queue> #include <sstream> #include <dirent.h> #include <iostream> using namespace std; #include "Test.h" #include "Base.h" //constructors Test::Test(char* command, queue<char *> flags) { this->command = command; this->flags = flags; } Test::Test(queue<char*> flags) { this->flags = flags; } Test::Test() {} //push any new flags into the queue<char *> flags void Test::add_flag(char*a) { flags.push(a); } //Used for the Exit Command to fix Exit bug string Test::get_data() { return command; } //executes the test according the flag specified //if flag == -e it will be tested to see if it is either a directory or a regular file //if flag == -f it will be tested to see if it is a regular file //if flag == -d it will be tested to see if it is a directory //if no flag is provided then -e will be assumed bool Test::execute(int in, int out) { struct stat buf; string flag; string path; bool exists = false; if(flags.size() == 1) { flag = "-e"; path = flags.front(); } else { //cout << flags.front() << endl; flag = flags.front(); flags.pop(); //cout << flags.front() << endl; path = flags.front(); } //cout << path << endl; int statret = stat(path.c_str(),&buf); if (statret == 0) { exists = true; } if(dup2(in,0) == -1) { perror("dup2"); return false; } if(dup2(out,1) == -1) { perror("dup2"); return false; } if(statret == -1) { perror("stat"); return false; } if(flag == "-e") { cout << "(true)" << endl; return exists; } else if(flag == "-d") { if(S_ISDIR(buf.st_mode)) { cout << "(true)" << endl; return true; } else { cout << "(false)" << endl; return false; } } else if(flag == "-f") { if(S_ISREG(buf.st_mode)) { cout << "(true)" << endl; return true; } else { cout << "(false)" << endl; return false; } } else { cout << "Error: In test flag " << flag << " is not valid." << endl; return false; } } #endif <|endoftext|>
<commit_before>#include "Tree.hpp" #include <stdexcept> #include <tuple> #include <cassert> #include "pll_util.hpp" #include "epa_pll_util.hpp" #include "file_io.hpp" #include "Sequence.hpp" using namespace std; Tree::Tree(const string& tree_file, const string& msa_file, const Model& model) : model_(model) { // TODO handle filetypes other than newick/fasta //parse, build tree nums_ = Tree_Numbers(); ref_msa_ = build_MSA_from_file(msa_file); tie(partition_, tree_) = build_partition_from_file(tree_file, model_, nums_, ref_msa_.num_sites()); link_tree_msa(tree_, partition_, ref_msa_, nums_.tip_nodes); // TODO reference part of the MSA can now be freed precompute_clvs(tree_, partition_, nums_); } Tree::~Tree() { // free data segment of tree nodes utree_free_node_data(tree_); pll_partition_destroy(partition_); } void Tree::place(const MSA &msa) const { // get all edges auto node_list = new pll_utree_t*[nums_.branches]; auto num_traversed = utree_query_branches(tree_, node_list); // TODO create output class // place all s on every edge for (auto s : msa) for (int i = 0; i < num_traversed; ++i) { place_on_edge(s, node_list[i]); } } /* Compute loglikelihood of a Sequence, when placed on the edge defined by node */ double Tree::place_on_edge(Sequence& s, pll_utree_t * node) const { assert(node != NULL); int old_left_clv_index = 0; int old_right_clv_index = 1; int new_tip_clv_index = 2; int inner_clv_index = 3; pll_utree_t * old_left = node; pll_utree_t * old_right = node->back; /* create new tiny tree including the given nodes and a new node for the sequence s [2] new_tip | | inner [3] / \ / \ old_left old_right [0] [1] numbers in brackets are the nodes clv indices */ // stack (TODO) new partition with 3 tips, 1 inner node //partition_create_stackd(tiny_partition, pll_partition_t * tiny_partition = pll_partition_create( 3, // tips 1, // extra clv's partition_->states, partition_->sites, 0, // number of mixture models partition_->rate_matrices, 3, // number of prob. matrices (one per unique branch length) partition_->rate_cats, 4, // number of scale buffers (one per node) partition_->attributes); // shallow copy model params tiny_partition->rates = partition_->rates; tiny_partition->subst_params = partition_->subst_params; tiny_partition->frequencies = partition_->frequencies; // shallow copy 2 existing nodes clvs tiny_partition->clv[old_left_clv_index] = partition_->clv[old_left->clv_index]; tiny_partition->clv[old_right_clv_index] = partition_->clv[old_right->clv_index]; // shallow copy scalers TODO is this right? tiny_partition->scale_buffer[old_left_clv_index] = partition_->scale_buffer[old_left->scaler_index]; tiny_partition->scale_buffer[old_right_clv_index] = partition_->scale_buffer[old_right->scaler_index]; // init the new tip with s.sequence(), branch length pll_set_tip_states(tiny_partition, new_tip_clv_index, pll_map_nt, s.sequence().c_str()); // set up branch lengths //int num_unique_branch_lengths = 2; /* heuristic insertion as described in EPA paper from 2011 (Berger et al.): original branch, now split by "inner", or base, node of the inserted sequence, defines the new branch lengths between inner and old left/right respectively as old branch length / 2. The new branch leading from inner to the new tip is initialized with length 0.9, which is the default branch length in RAxML. */ double branch_lengths[2] = { old_left->length / 2, 0.9}; unsigned int matrix_indices[2] = { 0, 1 }; // TODO Newton-Raphson // use branch lengths to compute the probability matrices pll_update_prob_matrices(tiny_partition, 0, matrix_indices, branch_lengths, 2); /* Creating a single operation for the inner node computation. Here we specify which clvs and pmatrices to use, so we don't need to mess with what the internal tree structure points to */ pll_operation_t ops[1]; ops[0].parent_clv_index = inner_clv_index; ops[0].child1_clv_index = old_left_clv_index; ops[0].child2_clv_index = old_right_clv_index; ops[0].child1_matrix_index = 0;// TODO depends on NR vs heuristic ops[0].child2_matrix_index = 0;// TODO depends on NR vs heuristic ops[0].parent_scaler_index = PLL_SCALE_BUFFER_NONE;// TODO this should be inner_clv_index once scale buffers are fixed ops[0].child1_scaler_index = old_left_clv_index; ops[0].child2_scaler_index = old_right_clv_index; // use update_partials to compute the clv poining toward the new tip pll_update_partials(tiny_partition, ops, 1); // compute the loglikelihood using inner node and new tip double likelihood = pll_compute_edge_loglikelihood(tiny_partition, new_tip_clv_index, new_tip_clv_index,// scaler_index inner_clv_index, inner_clv_index, // scaler_index 1,// matrix index of branch TODO depends on NR 0);// freq index //pll_partition_destroy(tiny_partition); return likelihood; } void Tree::visit(std::function<void(pll_partition_t *, pll_utree_t *)> f) { f(partition_, tree_); } <commit_msg>fixed invalid read<commit_after>#include "Tree.hpp" #include <stdexcept> #include <tuple> #include <cassert> #include "pll_util.hpp" #include "epa_pll_util.hpp" #include "file_io.hpp" #include "Sequence.hpp" using namespace std; Tree::Tree(const string& tree_file, const string& msa_file, const Model& model) : model_(model) { // TODO handle filetypes other than newick/fasta //parse, build tree nums_ = Tree_Numbers(); ref_msa_ = build_MSA_from_file(msa_file); tie(partition_, tree_) = build_partition_from_file(tree_file, model_, nums_, ref_msa_.num_sites()); link_tree_msa(tree_, partition_, ref_msa_, nums_.tip_nodes); // TODO reference part of the MSA can now be freed precompute_clvs(tree_, partition_, nums_); } Tree::~Tree() { // free data segment of tree nodes utree_free_node_data(tree_); pll_partition_destroy(partition_); pll_utree_destroy(tree_); } void Tree::place(const MSA &msa) const { // get all edges auto node_list = new pll_utree_t*[nums_.branches]; auto num_traversed = utree_query_branches(tree_, node_list); // TODO create output class // place all s on every edge for (auto s : msa) for (int i = 0; i < num_traversed; ++i) { // TODO pass tiny tree instead of node place_on_edge(s, node_list[i]); } } /* Compute loglikelihood of a Sequence, when placed on the edge defined by node */ double Tree::place_on_edge(Sequence& s, pll_utree_t * node) const { assert(node != NULL); int old_left_clv_index = 0; int old_right_clv_index = 1; int new_tip_clv_index = 2; int inner_clv_index = 3; pll_utree_t * old_left = node; pll_utree_t * old_right = node->back; /* create new tiny tree including the given nodes and a new node for the sequence s [2] new_tip | | inner [3] / \ / \ old_left old_right [0] [1] numbers in brackets are the nodes clv indices */ // stack (TODO) new partition with 3 tips, 1 inner node //partition_create_stackd(tiny_partition, pll_partition_t * tiny_partition = pll_partition_create( 3, // tips 1, // extra clv's partition_->states, partition_->sites, 0, // number of mixture models partition_->rate_matrices, 3, // number of prob. matrices (one per unique branch length) partition_->rate_cats, 4, // number of scale buffers (one per node) partition_->attributes); // shallow copy model params tiny_partition->rates = partition_->rates; tiny_partition->subst_params = partition_->subst_params; tiny_partition->frequencies = partition_->frequencies; // shallow copy 2 existing nodes clvs tiny_partition->clv[old_left_clv_index] = partition_->clv[old_left->clv_index]; tiny_partition->clv[old_right_clv_index] = partition_->clv[old_right->clv_index]; // shallow copy scalers if (old_left->scaler_index != PLL_SCALE_BUFFER_NONE) tiny_partition->scale_buffer[old_left_clv_index] = partition_->scale_buffer[old_left->scaler_index]; if (old_right->scaler_index != PLL_SCALE_BUFFER_NONE) tiny_partition->scale_buffer[old_right_clv_index] = partition_->scale_buffer[old_right->scaler_index]; // init the new tip with s.sequence(), branch length pll_set_tip_states(tiny_partition, new_tip_clv_index, pll_map_nt, s.sequence().c_str()); // set up branch lengths //int num_unique_branch_lengths = 2; /* heuristic insertion as described in EPA paper from 2011 (Berger et al.): original branch, now split by "inner", or base, node of the inserted sequence, defines the new branch lengths between inner and old left/right respectively as old branch length / 2. The new branch leading from inner to the new tip is initialized with length 0.9, which is the default branch length in RAxML. */ double branch_lengths[2] = { old_left->length / 2, 0.9}; unsigned int matrix_indices[2] = { 0, 1 }; // TODO Newton-Raphson // use branch lengths to compute the probability matrices pll_update_prob_matrices(tiny_partition, 0, matrix_indices, branch_lengths, 2); /* Creating a single operation for the inner node computation. Here we specify which clvs and pmatrices to use, so we don't need to mess with what the internal tree structure points to */ pll_operation_t ops[1]; ops[0].parent_clv_index = inner_clv_index; ops[0].child1_clv_index = old_left_clv_index; ops[0].child2_clv_index = old_right_clv_index; ops[0].child1_matrix_index = 0;// TODO depends on NR vs heuristic ops[0].child2_matrix_index = 0;// TODO depends on NR vs heuristic ops[0].parent_scaler_index = inner_clv_index;// TODO this should be inner_clv_index once scale buffers are fixed ops[0].child1_scaler_index = old_left_clv_index; ops[0].child2_scaler_index = old_right_clv_index; // use update_partials to compute the clv poining toward the new tip pll_update_partials(tiny_partition, ops, 1); // compute the loglikelihood using inner node and new tip double likelihood = pll_compute_edge_loglikelihood(tiny_partition, new_tip_clv_index, PLL_SCALE_BUFFER_NONE,// scaler_index inner_clv_index, inner_clv_index, // scaler_index 1,// matrix index of branch TODO depends on NR 0);// freq index // TODO properly free the tiny partition //pll_partition_destroy(tiny_partition); return likelihood; } void Tree::visit(std::function<void(pll_partition_t *, pll_utree_t *)> f) { f(partition_, tree_); } <|endoftext|>
<commit_before>/* * DSA Parameter Generation * (C) 1999-2007 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/numthry.h> #include <botan/hash.h> #include <botan/parsing.h> #include <algorithm> namespace Botan { namespace { /* * Check if this size is allowed by FIPS 186-3 */ bool fips186_3_valid_size(size_t pbits, size_t qbits) { if(qbits == 160) return (pbits == 512 || pbits == 768 || pbits == 1024); if(qbits == 224) return (pbits == 2048); if(qbits == 256) return (pbits == 2048 || pbits == 3072); return false; } } /* * Attempt DSA prime generation with given seed */ bool generate_dsa_primes(RandomNumberGenerator& rng, BigInt& p, BigInt& q, size_t pbits, size_t qbits, const std::vector<byte>& seed_c) { if(!fips186_3_valid_size(pbits, qbits)) throw Invalid_Argument( "FIPS 186-3 does not allow DSA domain parameters of " + std::to_string(pbits) + "/" + std::to_string(qbits) + " bits long"); if(seed_c.size() * 8 < qbits) throw Invalid_Argument( "Generating a DSA parameter set with a " + std::to_string(qbits) + "long q requires a seed at least as many bits long"); const std::string hash_name = "SHA-" + std::to_string(qbits); std::unique_ptr<HashFunction> hash(HashFunction::create(hash_name)); if(!hash) throw Algorithm_Not_Found(hash_name); const size_t HASH_SIZE = hash->output_length(); class Seed { public: explicit Seed(const std::vector<byte>& s) : m_seed(s) {} operator std::vector<byte>& () { return m_seed; } Seed& operator++() { for(size_t j = m_seed.size(); j > 0; --j) if(++m_seed[j-1]) break; return (*this); } private: std::vector<byte> m_seed; }; Seed seed(seed_c); q.binary_decode(hash->process(seed)); q.set_bit(qbits-1); q.set_bit(0); if(!is_prime(q, rng)) return false; const size_t n = (pbits-1) / (HASH_SIZE * 8), b = (pbits-1) % (HASH_SIZE * 8); BigInt X; std::vector<byte> V(HASH_SIZE * (n+1)); for(size_t j = 0; j != 4096; ++j) { for(size_t k = 0; k <= n; ++k) { ++seed; hash->update(seed); hash->final(&V[HASH_SIZE * (n-k)]); } X.binary_decode(&V[HASH_SIZE - 1 - b/8], V.size() - (HASH_SIZE - 1 - b/8)); X.set_bit(pbits-1); p = X - (X % (2*q) - 1); if(p.bits() == pbits && is_prime(p, rng)) return true; } return false; } /* * Generate DSA Primes */ std::vector<byte> generate_dsa_primes(RandomNumberGenerator& rng, BigInt& p, BigInt& q, size_t pbits, size_t qbits) { while(true) { std::vector<byte> seed(qbits / 8); rng.randomize(seed.data(), seed.size()); if(generate_dsa_primes(rng, p, q, pbits, qbits, seed)) return seed; } } } <commit_msg>Fix DSA parameter generation to use the correct loop bound.<commit_after>/* * DSA Parameter Generation * (C) 1999-2007 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/numthry.h> #include <botan/hash.h> #include <botan/parsing.h> #include <algorithm> namespace Botan { namespace { /* * Check if this size is allowed by FIPS 186-3 */ bool fips186_3_valid_size(size_t pbits, size_t qbits) { if(qbits == 160) return (pbits == 1024); if(qbits == 224) return (pbits == 2048); if(qbits == 256) return (pbits == 2048 || pbits == 3072); return false; } } /* * Attempt DSA prime generation with given seed */ bool generate_dsa_primes(RandomNumberGenerator& rng, BigInt& p, BigInt& q, size_t pbits, size_t qbits, const std::vector<byte>& seed_c) { if(!fips186_3_valid_size(pbits, qbits)) throw Invalid_Argument( "FIPS 186-3 does not allow DSA domain parameters of " + std::to_string(pbits) + "/" + std::to_string(qbits) + " bits long"); if(seed_c.size() * 8 < qbits) throw Invalid_Argument( "Generating a DSA parameter set with a " + std::to_string(qbits) + "long q requires a seed at least as many bits long"); const std::string hash_name = "SHA-" + std::to_string(qbits); std::unique_ptr<HashFunction> hash(HashFunction::create_or_throw(hash_name)); const size_t HASH_SIZE = hash->output_length(); class Seed { public: explicit Seed(const std::vector<byte>& s) : m_seed(s) {} operator std::vector<byte>& () { return m_seed; } Seed& operator++() { for(size_t j = m_seed.size(); j > 0; --j) if(++m_seed[j-1]) break; return (*this); } private: std::vector<byte> m_seed; }; Seed seed(seed_c); q.binary_decode(hash->process(seed)); q.set_bit(qbits-1); q.set_bit(0); if(!is_prime(q, rng)) return false; const size_t n = (pbits-1) / (HASH_SIZE * 8), b = (pbits-1) % (HASH_SIZE * 8); BigInt X; std::vector<byte> V(HASH_SIZE * (n+1)); for(size_t j = 0; j != 4*pbits; ++j) { for(size_t k = 0; k <= n; ++k) { ++seed; hash->update(seed); hash->final(&V[HASH_SIZE * (n-k)]); } X.binary_decode(&V[HASH_SIZE - 1 - b/8], V.size() - (HASH_SIZE - 1 - b/8)); X.set_bit(pbits-1); p = X - (X % (2*q) - 1); if(p.bits() == pbits && is_prime(p, rng)) return true; } return false; } /* * Generate DSA Primes */ std::vector<byte> generate_dsa_primes(RandomNumberGenerator& rng, BigInt& p, BigInt& q, size_t pbits, size_t qbits) { while(true) { std::vector<byte> seed(qbits / 8); rng.randomize(seed.data(), seed.size()); if(generate_dsa_primes(rng, p, q, pbits, qbits, seed)) return seed; } } } <|endoftext|>
<commit_before>/* * 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 3 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. */ #include <QtGui/QApplication> #include "config.h" #include "dbmanager.h" #include "iconmanager.h" #include "mainwindow.h" #include "sqlhighlighter.h" #include "tabwidget/abstracttabwidget.h" #include "widgets/querytextedit.h" int main(int argc, char *argv[]) { QApplication::setApplicationName("dbmaster"); QApplication::setApplicationVersion("0.7"); QApplication::setOrganizationDomain("dbmaster.sourceforge.net"); QApplication a(argc, argv); QSplashScreen splash(QPixmap(":/img/splash.png")); splash.show(); // Loading translations splash.showMessage(QObject::tr("Loading translations..."), Qt::AlignBottom); QTranslator translator; // getting the current locale QString lang = QLocale::system().name(); QString transdir; #if defined(Q_WS_X11) // for *nix transdir = QString(PREFIX).append("/share/dbmaster/tr"); #endif #if defined(Q_WS_WIN) transdir = "share/tr"; #endif QString path; /* on teste d'abord si le .qm est dans le dossier courant -> alors on est en * dev, on le charge, sinon il est dans le répertoire d'installation. */ path = QDir::currentPath() + QString("/tr/%1.qm").arg(lang); if (!QFile::exists(path)) path = transdir.append("/%1.qm").arg(lang); translator.load(path); a.installTranslator(&translator); QTranslator qtTranslator; qtTranslator.load("qt_" + lang, #if defined (Q_WS_X11) QLibraryInfo::location(QLibraryInfo::TranslationsPath)); #endif #if defined (Q_WS_WIN) QDir::currentPath()); #endif a.installTranslator(&qtTranslator); splash.showMessage(QObject::tr("Initialization..."), Qt::AlignBottom); IconManager::init(); DbManager::init(); Config::init(); QueryTextEdit::reloadCompleter(); MainWindow *w = new MainWindow(); w->show(); splash.finish(w); return a.exec(); } <commit_msg>Num version<commit_after>/* * 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 3 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. */ #include <QtGui/QApplication> #include "config.h" #include "dbmanager.h" #include "iconmanager.h" #include "mainwindow.h" #include "sqlhighlighter.h" #include "tabwidget/abstracttabwidget.h" #include "widgets/querytextedit.h" int main(int argc, char *argv[]) { QApplication::setApplicationName("dbmaster"); QApplication::setApplicationVersion("0.7.1"); QApplication::setOrganizationDomain("dbmaster.sourceforge.net"); QApplication a(argc, argv); QSplashScreen splash(QPixmap(":/img/splash.png")); splash.show(); // Loading translations splash.showMessage(QObject::tr("Loading translations..."), Qt::AlignBottom); QTranslator translator; // getting the current locale QString lang = QLocale::system().name(); QString transdir; #if defined(Q_WS_X11) // for *nix transdir = QString(PREFIX).append("/share/dbmaster/tr"); #endif #if defined(Q_WS_WIN) transdir = "share/tr"; #endif QString path; /* on teste d'abord si le .qm est dans le dossier courant -> alors on est en * dev, on le charge, sinon il est dans le répertoire d'installation. */ path = QDir::currentPath() + QString("/tr/%1.qm").arg(lang); if (!QFile::exists(path)) path = transdir.append("/%1.qm").arg(lang); translator.load(path); a.installTranslator(&translator); QTranslator qtTranslator; qtTranslator.load("qt_" + lang, #if defined (Q_WS_X11) QLibraryInfo::location(QLibraryInfo::TranslationsPath)); #endif #if defined (Q_WS_WIN) QDir::currentPath()); #endif a.installTranslator(&qtTranslator); splash.showMessage(QObject::tr("Initialization..."), Qt::AlignBottom); IconManager::init(); DbManager::init(); Config::init(); QueryTextEdit::reloadCompleter(); MainWindow *w = new MainWindow(); w->show(); splash.finish(w); return a.exec(); } <|endoftext|>
<commit_before>/* * Elliptic curves over GF(p) Montgomery Representation * (C) 2014,2015 Jack Lloyd * 2016 Matthias Gierlings * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/curve_gfp.h> #include <botan/curve_nistp.h> #include <botan/numthry.h> #include <botan/reducer.h> #include <botan/internal/mp_core.h> #include <botan/internal/mp_asmi.h> namespace Botan { namespace { class CurveGFp_Montgomery final : public CurveGFp_Repr { public: CurveGFp_Montgomery(const BigInt& p, const BigInt& a, const BigInt& b) : m_p(p), m_a(a), m_b(b), m_p_words(m_p.sig_words()), m_p_dash(monty_inverse(m_p.word_at(0))) { Modular_Reducer mod_p(m_p); m_r.set_bit(m_p_words * BOTAN_MP_WORD_BITS); m_r = mod_p.reduce(m_r); m_r2 = mod_p.square(m_r); m_r3 = mod_p.multiply(m_r, m_r2); m_a_r = mod_p.multiply(m_r, m_a); m_b_r = mod_p.multiply(m_r, m_b); } const BigInt& get_a() const override { return m_a; } const BigInt& get_b() const override { return m_b; } const BigInt& get_p() const override { return m_p; } const BigInt& get_a_rep() const override { return m_a_r; } const BigInt& get_b_rep() const override { return m_b_r; } bool is_one(const BigInt& x) const override { return x == m_r; } size_t get_p_words() const override { return m_p_words; } size_t get_ws_size() const override { return 2*m_p_words + 4; } BigInt invert_element(const BigInt& x, secure_vector<word>& ws) const override; void to_curve_rep(BigInt& x, secure_vector<word>& ws) const override; void from_curve_rep(BigInt& x, secure_vector<word>& ws) const override; void curve_mul(BigInt& z, const BigInt& x, const BigInt& y, secure_vector<word>& ws) const override; void curve_sqr(BigInt& z, const BigInt& x, secure_vector<word>& ws) const override; private: BigInt m_p; BigInt m_a, m_b; BigInt m_a_r, m_b_r; size_t m_p_words; // cache of m_p.sig_words() // Montgomery parameters BigInt m_r, m_r2, m_r3; word m_p_dash; }; BigInt CurveGFp_Montgomery::invert_element(const BigInt& x, secure_vector<word>& ws) const { // Should we use Montgomery inverse instead? const BigInt inv = inverse_mod(x, m_p); BigInt res; curve_mul(res, inv, m_r3, ws); return res; } void CurveGFp_Montgomery::to_curve_rep(BigInt& x, secure_vector<word>& ws) const { const BigInt tx = x; curve_mul(x, tx, m_r2, ws); } void CurveGFp_Montgomery::from_curve_rep(BigInt& x, secure_vector<word>& ws) const { const BigInt tx = x; curve_mul(x, tx, 1, ws); } void CurveGFp_Montgomery::curve_mul(BigInt& z, const BigInt& x, const BigInt& y, secure_vector<word>& ws) const { if(x.is_zero() || y.is_zero()) { z.clear(); return; } if(ws.size() < get_ws_size()) ws.resize(get_ws_size()); const size_t output_size = 2*m_p_words + 2; if(z.size() < output_size) z.grow_to(output_size); bigint_mul(z.mutable_data(), z.size(), x.data(), x.size(), x.sig_words(), y.data(), y.size(), y.sig_words(), ws.data(), ws.size()); bigint_monty_redc(z.mutable_data(), m_p.data(), m_p_words, m_p_dash, ws.data(), ws.size()); } void CurveGFp_Montgomery::curve_sqr(BigInt& z, const BigInt& x, secure_vector<word>& ws) const { if(x.is_zero()) { z.clear(); return; } const size_t x_sw = x.sig_words(); BOTAN_ASSERT(x_sw <= m_p_words, "Input in range"); if(ws.size() < get_ws_size()) ws.resize(get_ws_size()); const size_t output_size = 2*m_p_words + 2; if(z.size() < output_size) z.grow_to(output_size); bigint_sqr(z.mutable_data(), z.size(), x.data(), x.size(), x_sw, ws.data(), ws.size()); bigint_monty_redc(z.mutable_data(), m_p.data(), m_p_words, m_p_dash, ws.data(), ws.size()); } class CurveGFp_NIST : public CurveGFp_Repr { public: CurveGFp_NIST(size_t p_bits, const BigInt& a, const BigInt& b) : m_a(a), m_b(b), m_p_words((p_bits + BOTAN_MP_WORD_BITS - 1) / BOTAN_MP_WORD_BITS) { } const BigInt& get_a() const override { return m_a; } const BigInt& get_b() const override { return m_b; } size_t get_p_words() const override { return m_p_words; } size_t get_ws_size() const override { return 2*m_p_words + 4; } const BigInt& get_a_rep() const override { return m_a; } const BigInt& get_b_rep() const override { return m_b; } bool is_one(const BigInt& x) const override { return x == 1; } void to_curve_rep(BigInt& x, secure_vector<word>& ws) const override { redc(x, ws); } void from_curve_rep(BigInt& x, secure_vector<word>& ws) const override { redc(x, ws); } BigInt invert_element(const BigInt& x, secure_vector<word>& ws) const override; void curve_mul(BigInt& z, const BigInt& x, const BigInt& y, secure_vector<word>& ws) const override; void curve_sqr(BigInt& z, const BigInt& x, secure_vector<word>& ws) const override; private: virtual void redc(BigInt& x, secure_vector<word>& ws) const = 0; // Curve parameters BigInt m_a, m_b; size_t m_p_words; // cache of m_p.sig_words() }; BigInt CurveGFp_NIST::invert_element(const BigInt& x, secure_vector<word>& ws) const { BOTAN_UNUSED(ws); return inverse_mod(x, get_p()); } void CurveGFp_NIST::curve_mul(BigInt& z, const BigInt& x, const BigInt& y, secure_vector<word>& ws) const { if(x.is_zero() || y.is_zero()) { z.clear(); return; } if(ws.size() < get_ws_size()) ws.resize(get_ws_size()); const size_t output_size = 2*m_p_words + 2; if(z.size() < output_size) z.grow_to(output_size); bigint_mul(z.mutable_data(), z.size(), x.data(), x.size(), x.sig_words(), y.data(), y.size(), y.sig_words(), ws.data(), ws.size()); this->redc(z, ws); } void CurveGFp_NIST::curve_sqr(BigInt& z, const BigInt& x, secure_vector<word>& ws) const { if(x.is_zero()) { z.clear(); return; } if(ws.size() < get_ws_size()) ws.resize(get_ws_size()); const size_t output_size = 2*m_p_words + 2; if(z.size() < output_size) z.grow_to(output_size); bigint_sqr(z.mutable_data(), output_size, x.data(), x.size(), x.sig_words(), ws.data(), ws.size()); this->redc(z, ws); } #if defined(BOTAN_HAS_NIST_PRIME_REDUCERS_W32) /** * The NIST P-192 curve */ class CurveGFp_P192 final : public CurveGFp_NIST { public: CurveGFp_P192(const BigInt& a, const BigInt& b) : CurveGFp_NIST(192, a, b) {} const BigInt& get_p() const override { return prime_p192(); } private: void redc(BigInt& x, secure_vector<word>& ws) const override { redc_p192(x, ws); } }; /** * The NIST P-224 curve */ class CurveGFp_P224 final : public CurveGFp_NIST { public: CurveGFp_P224(const BigInt& a, const BigInt& b) : CurveGFp_NIST(224, a, b) {} const BigInt& get_p() const override { return prime_p224(); } private: void redc(BigInt& x, secure_vector<word>& ws) const override { redc_p224(x, ws); } }; /** * The NIST P-256 curve */ class CurveGFp_P256 final : public CurveGFp_NIST { public: CurveGFp_P256(const BigInt& a, const BigInt& b) : CurveGFp_NIST(256, a, b) {} const BigInt& get_p() const override { return prime_p256(); } private: void redc(BigInt& x, secure_vector<word>& ws) const override { redc_p256(x, ws); } }; /** * The NIST P-384 curve */ class CurveGFp_P384 final : public CurveGFp_NIST { public: CurveGFp_P384(const BigInt& a, const BigInt& b) : CurveGFp_NIST(384, a, b) {} const BigInt& get_p() const override { return prime_p384(); } private: void redc(BigInt& x, secure_vector<word>& ws) const override { redc_p384(x, ws); } }; #endif /** * The NIST P-521 curve */ class CurveGFp_P521 final : public CurveGFp_NIST { public: CurveGFp_P521(const BigInt& a, const BigInt& b) : CurveGFp_NIST(521, a, b) {} const BigInt& get_p() const override { return prime_p521(); } private: void redc(BigInt& x, secure_vector<word>& ws) const override { redc_p521(x, ws); } }; } std::shared_ptr<CurveGFp_Repr> CurveGFp::choose_repr(const BigInt& p, const BigInt& a, const BigInt& b) { #if defined(BOTAN_HAS_NIST_PRIME_REDUCERS_W32) if(p == prime_p192()) return std::shared_ptr<CurveGFp_Repr>(new CurveGFp_P192(a, b)); if(p == prime_p224()) return std::shared_ptr<CurveGFp_Repr>(new CurveGFp_P224(a, b)); if(p == prime_p256()) return std::shared_ptr<CurveGFp_Repr>(new CurveGFp_P256(a, b)); if(p == prime_p384()) return std::shared_ptr<CurveGFp_Repr>(new CurveGFp_P384(a, b)); #endif if(p == prime_p521()) return std::shared_ptr<CurveGFp_Repr>(new CurveGFp_P521(a, b)); return std::shared_ptr<CurveGFp_Repr>(new CurveGFp_Montgomery(p, a, b)); } } <commit_msg>Assume CurveGFp inputs are at most p words long<commit_after>/* * Elliptic curves over GF(p) Montgomery Representation * (C) 2014,2015 Jack Lloyd * 2016 Matthias Gierlings * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/curve_gfp.h> #include <botan/curve_nistp.h> #include <botan/numthry.h> #include <botan/reducer.h> #include <botan/internal/mp_core.h> #include <botan/internal/mp_asmi.h> namespace Botan { namespace { class CurveGFp_Montgomery final : public CurveGFp_Repr { public: CurveGFp_Montgomery(const BigInt& p, const BigInt& a, const BigInt& b) : m_p(p), m_a(a), m_b(b), m_p_words(m_p.sig_words()), m_p_dash(monty_inverse(m_p.word_at(0))) { Modular_Reducer mod_p(m_p); m_r.set_bit(m_p_words * BOTAN_MP_WORD_BITS); m_r = mod_p.reduce(m_r); m_r2 = mod_p.square(m_r); m_r3 = mod_p.multiply(m_r, m_r2); m_a_r = mod_p.multiply(m_r, m_a); m_b_r = mod_p.multiply(m_r, m_b); } const BigInt& get_a() const override { return m_a; } const BigInt& get_b() const override { return m_b; } const BigInt& get_p() const override { return m_p; } const BigInt& get_a_rep() const override { return m_a_r; } const BigInt& get_b_rep() const override { return m_b_r; } bool is_one(const BigInt& x) const override { return x == m_r; } size_t get_p_words() const override { return m_p_words; } size_t get_ws_size() const override { return 2*m_p_words + 4; } BigInt invert_element(const BigInt& x, secure_vector<word>& ws) const override; void to_curve_rep(BigInt& x, secure_vector<word>& ws) const override; void from_curve_rep(BigInt& x, secure_vector<word>& ws) const override; void curve_mul(BigInt& z, const BigInt& x, const BigInt& y, secure_vector<word>& ws) const override; void curve_sqr(BigInt& z, const BigInt& x, secure_vector<word>& ws) const override; private: BigInt m_p; BigInt m_a, m_b; BigInt m_a_r, m_b_r; size_t m_p_words; // cache of m_p.sig_words() // Montgomery parameters BigInt m_r, m_r2, m_r3; word m_p_dash; }; BigInt CurveGFp_Montgomery::invert_element(const BigInt& x, secure_vector<word>& ws) const { // Should we use Montgomery inverse instead? const BigInt inv = inverse_mod(x, m_p); BigInt res; curve_mul(res, inv, m_r3, ws); return res; } void CurveGFp_Montgomery::to_curve_rep(BigInt& x, secure_vector<word>& ws) const { const BigInt tx = x; curve_mul(x, tx, m_r2, ws); } void CurveGFp_Montgomery::from_curve_rep(BigInt& z, secure_vector<word>& ws) const { if(ws.size() < get_ws_size()) ws.resize(get_ws_size()); const size_t output_size = 2*m_p_words + 2; if(z.size() < output_size) z.grow_to(output_size); bigint_monty_redc(z.mutable_data(), m_p.data(), m_p_words, m_p_dash, ws.data(), ws.size()); } void CurveGFp_Montgomery::curve_mul(BigInt& z, const BigInt& x, const BigInt& y, secure_vector<word>& ws) const { if(x.is_zero() || y.is_zero()) { z.clear(); return; } if(ws.size() < get_ws_size()) ws.resize(get_ws_size()); const size_t output_size = 2*m_p_words + 2; if(z.size() < output_size) z.grow_to(output_size); const size_t x_words = (x.size() >= m_p_words) ? m_p_words : x.sig_words(); const size_t y_words = (y.size() >= m_p_words) ? m_p_words : y.sig_words(); bigint_mul(z.mutable_data(), z.size(), x.data(), x.size(), x_words, y.data(), y.size(), y_words, ws.data(), ws.size()); bigint_monty_redc(z.mutable_data(), m_p.data(), m_p_words, m_p_dash, ws.data(), ws.size()); } void CurveGFp_Montgomery::curve_sqr(BigInt& z, const BigInt& x, secure_vector<word>& ws) const { if(x.is_zero()) { z.clear(); return; } if(ws.size() < get_ws_size()) ws.resize(get_ws_size()); const size_t output_size = 2*m_p_words + 2; if(z.size() < output_size) z.grow_to(output_size); const size_t x_words = (x.size() >= m_p_words) ? m_p_words : x.sig_words(); bigint_sqr(z.mutable_data(), z.size(), x.data(), x.size(), x_words, ws.data(), ws.size()); bigint_monty_redc(z.mutable_data(), m_p.data(), m_p_words, m_p_dash, ws.data(), ws.size()); } class CurveGFp_NIST : public CurveGFp_Repr { public: CurveGFp_NIST(size_t p_bits, const BigInt& a, const BigInt& b) : m_a(a), m_b(b), m_p_words((p_bits + BOTAN_MP_WORD_BITS - 1) / BOTAN_MP_WORD_BITS) { } const BigInt& get_a() const override { return m_a; } const BigInt& get_b() const override { return m_b; } size_t get_p_words() const override { return m_p_words; } size_t get_ws_size() const override { return 2*m_p_words + 4; } const BigInt& get_a_rep() const override { return m_a; } const BigInt& get_b_rep() const override { return m_b; } bool is_one(const BigInt& x) const override { return x == 1; } void to_curve_rep(BigInt& x, secure_vector<word>& ws) const override { redc(x, ws); } void from_curve_rep(BigInt& x, secure_vector<word>& ws) const override { redc(x, ws); } BigInt invert_element(const BigInt& x, secure_vector<word>& ws) const override; void curve_mul(BigInt& z, const BigInt& x, const BigInt& y, secure_vector<word>& ws) const override; void curve_sqr(BigInt& z, const BigInt& x, secure_vector<word>& ws) const override; private: virtual void redc(BigInt& x, secure_vector<word>& ws) const = 0; // Curve parameters BigInt m_a, m_b; size_t m_p_words; // cache of m_p.sig_words() }; BigInt CurveGFp_NIST::invert_element(const BigInt& x, secure_vector<word>& ws) const { BOTAN_UNUSED(ws); return inverse_mod(x, get_p()); } void CurveGFp_NIST::curve_mul(BigInt& z, const BigInt& x, const BigInt& y, secure_vector<word>& ws) const { if(x.is_zero() || y.is_zero()) { z.clear(); return; } if(ws.size() < get_ws_size()) ws.resize(get_ws_size()); const size_t output_size = 2*m_p_words + 2; if(z.size() < output_size) z.grow_to(output_size); const size_t x_words = (x.size() >= m_p_words) ? m_p_words : x.sig_words(); const size_t y_words = (y.size() >= m_p_words) ? m_p_words : y.sig_words(); bigint_mul(z.mutable_data(), z.size(), x.data(), x.size(), x_words, y.data(), y.size(), y_words, ws.data(), ws.size()); this->redc(z, ws); } void CurveGFp_NIST::curve_sqr(BigInt& z, const BigInt& x, secure_vector<word>& ws) const { if(x.is_zero()) { z.clear(); return; } if(ws.size() < get_ws_size()) ws.resize(get_ws_size()); const size_t output_size = 2*m_p_words + 2; if(z.size() < output_size) z.grow_to(output_size); const size_t x_words = (x.size() >= m_p_words) ? m_p_words : x.sig_words(); bigint_sqr(z.mutable_data(), output_size, x.data(), x.size(), x_words, ws.data(), ws.size()); this->redc(z, ws); } #if defined(BOTAN_HAS_NIST_PRIME_REDUCERS_W32) /** * The NIST P-192 curve */ class CurveGFp_P192 final : public CurveGFp_NIST { public: CurveGFp_P192(const BigInt& a, const BigInt& b) : CurveGFp_NIST(192, a, b) {} const BigInt& get_p() const override { return prime_p192(); } private: void redc(BigInt& x, secure_vector<word>& ws) const override { redc_p192(x, ws); } }; /** * The NIST P-224 curve */ class CurveGFp_P224 final : public CurveGFp_NIST { public: CurveGFp_P224(const BigInt& a, const BigInt& b) : CurveGFp_NIST(224, a, b) {} const BigInt& get_p() const override { return prime_p224(); } private: void redc(BigInt& x, secure_vector<word>& ws) const override { redc_p224(x, ws); } }; /** * The NIST P-256 curve */ class CurveGFp_P256 final : public CurveGFp_NIST { public: CurveGFp_P256(const BigInt& a, const BigInt& b) : CurveGFp_NIST(256, a, b) {} const BigInt& get_p() const override { return prime_p256(); } private: void redc(BigInt& x, secure_vector<word>& ws) const override { redc_p256(x, ws); } }; /** * The NIST P-384 curve */ class CurveGFp_P384 final : public CurveGFp_NIST { public: CurveGFp_P384(const BigInt& a, const BigInt& b) : CurveGFp_NIST(384, a, b) {} const BigInt& get_p() const override { return prime_p384(); } private: void redc(BigInt& x, secure_vector<word>& ws) const override { redc_p384(x, ws); } }; #endif /** * The NIST P-521 curve */ class CurveGFp_P521 final : public CurveGFp_NIST { public: CurveGFp_P521(const BigInt& a, const BigInt& b) : CurveGFp_NIST(521, a, b) {} const BigInt& get_p() const override { return prime_p521(); } private: void redc(BigInt& x, secure_vector<word>& ws) const override { redc_p521(x, ws); } }; } std::shared_ptr<CurveGFp_Repr> CurveGFp::choose_repr(const BigInt& p, const BigInt& a, const BigInt& b) { #if defined(BOTAN_HAS_NIST_PRIME_REDUCERS_W32) if(p == prime_p192()) return std::shared_ptr<CurveGFp_Repr>(new CurveGFp_P192(a, b)); if(p == prime_p224()) return std::shared_ptr<CurveGFp_Repr>(new CurveGFp_P224(a, b)); if(p == prime_p256()) return std::shared_ptr<CurveGFp_Repr>(new CurveGFp_P256(a, b)); if(p == prime_p384()) return std::shared_ptr<CurveGFp_Repr>(new CurveGFp_P384(a, b)); #endif if(p == prime_p521()) return std::shared_ptr<CurveGFp_Repr>(new CurveGFp_P521(a, b)); return std::shared_ptr<CurveGFp_Repr>(new CurveGFp_Montgomery(p, a, b)); } } <|endoftext|>
<commit_before>#include <iostream> #include "main.hpp" #include "util.hpp" #include "system/printer.hpp" #ifndef OBJ_PATH #define OBJ_PATH "share/sphere.obj" #endif /*#ifndef MTL_PATH #define MTL_PATH "share/cube.mtl" #endif*/ #ifndef VERT_PATH #define VERT_PATH "share/fallback.vert" #endif #ifndef FRAG_PATH #define FRAG_PATH "share/shade.frag" #endif void printErrors(std::ostream &oss) {} template<typename T1, typename... TN> void printErrors(std::ostream &oss, T1 &t1, TN &... tn) { for(auto e : t1) { oss << e << std::endl; } printErrors(oss, tn...); } int main(int argc, const char **argv) { using namespace Util; using namespace System; if(glfwInit() == 0) { std::cout << "Failed to initialize GLFW " << glfwGetVersionString() << std::endl; return 1; } const char *obj_fname, *vert_fname, *frag_fname; if(argc >= 2) obj_fname = argv[1]; else obj_fname = OBJ_PATH; /*if(argc >= 3) mtl_fname = argv[2]; else mtl_fname = MTL_PATH;*/ if(argc >= 4) vert_fname = argv[2]; else vert_fname = VERT_PATH; if(argc >= 5) frag_fname = argv[3]; else frag_fname = FRAG_PATH; std::atomic_bool alive(true); Control::control ctl(alive, obj_fname); // Control::control ctl(alive, 0); // Use mesh instead if(!alive) { std::cout << "Control construction failed." << std::endl; printErrors(std::cout, ctl.viewer.errors, ctl.errors); return 1; } if(!ctl.viewer.setProg(alive, vert_fname, frag_fname)) { std::cout << "Failed to compile or link shaders." << std::endl; printErrors(std::cout, ctl.viewer.errors, ctl.errors); return 1; } using namespace System; Printer<5> printer; std::string cols[]{"GLFW", "OpenGL", "Path"}, rows[]{"", "Major", "Minor", "Revision", "", "", "Wavefront obj", "Vertex shader", "Fragment shader", ""}, paths[]{obj_fname, vert_fname, frag_fname}; int versions[6]{0}; glfwGetVersion(&versions[0], &versions[2], &versions[4]); glGetIntegerv(GL_MAJOR_VERSION, &versions[1]); glGetIntegerv(GL_MINOR_VERSION, &versions[3]); printer.push(&rows[5], &rows[5]+5) .level().insert(0, " ").level() .push<std::string, 3, 1, 31>(paths, &cols[2], &cols[3]+1) .level().insert(0, " ").level() .push(&rows[0], &rows[5]) .level().insert(0, " ").level() .push<int, 3, 2>(versions, &cols[0], &cols[2]); std::cout << printer << std::endl; if(!task::init(alive, &ctl)) { std::cout << "Control Initialization failed." << std::endl; printErrors(std::cout, ctl.viewer.errors, ctl.errors); return 1; } if(!task::run(alive, &ctl)) { printErrors(std::cout, ctl.viewer.errors, ctl.errors); } glfwTerminate(); return 0; } <commit_msg>Restructured main to use new control constructor<commit_after>#include <iostream> #include "main.hpp" #include "util.hpp" #include "system/printer.hpp" #ifndef VERT_PATH #define VERT_PATH "share/fallback.vert" #endif #ifndef FRAG_PATH #define FRAG_PATH "share/shade.frag" #endif void printErrors(std::ostream &oss) {} template<typename T1, typename... TN> void printErrors(std::ostream &oss, T1 &t1, TN &... tn) { for(auto e : t1) { oss << e << std::endl; } printErrors(oss, tn...); } int main(int argc, const char *argv[]) { const char *obj_fname = nullptr, *vert_fname = nullptr, *frag_fname = nullptr; if(argc >= 2) obj_fname = argv[1]; //else obj_fname = OBJ_PATH; if(argc >= 3) vert_fname = argv[2]; else vert_fname = VERT_PATH; if(argc >= 4) frag_fname = argv[3]; else frag_fname = FRAG_PATH; if(argc >= 5) { std::cout << "Usage: " << argv[0] << " [obj_fname [vert_fname [frag_fname]]]" << std::endl; return 1; } using namespace Model; model model; if(obj_fname) { obj_t obj; auto status = obj_t::load(obj_fname, obj); if(status != obj_t::e_ok) { std::cout << "Failed to load model " << obj_fname << std::endl; return 1; } model = obj; std::cout << "Initialized model with obj " << obj_fname << '.' << std::endl; } else { model = mesh_t(150, 150, [](float s, float t, std::vector<float> &vertices) { auto theta = s*M_PI*2, phi = t*M_PI; vertices.emplace_back(cos(theta)*sin(phi)); // X vertices.emplace_back(sin(theta)*sin(phi)); // Y vertices.emplace_back(cos(phi)); // Z }); std::cout << "Initialized model with ad-hoc mesh." << std::endl; } std::atomic_bool alive(true); View::view view(alive, vert_fname, frag_fname); if(!alive) { std::cout << "View construction failed." << std::endl; printErrors(std::cout, view.errors); return 1; } else if(!view.init(alive)) { std::cout << "View initialization failed." << std::endl; printErrors(std::cout, view.errors); return 1; } else { int gl_major, gl_minor, glfw_major, glfw_minor, glfw_rev; glGetIntegerv(GL_MAJOR_VERSION, &gl_major); glGetIntegerv(GL_MINOR_VERSION, &gl_minor); glfwGetVersion(&glfw_major, &glfw_minor, &glfw_rev); std::cout << "Initialized view with OpenGL " << gl_major << '.' << gl_minor << " and GLFW " << glfw_major << '.' << glfw_minor << '.' << glfw_rev << '.' << std::endl; } Control::control ctl(alive, model, view); if(!alive) { std::cout << "Control construction failed." << std::endl; printErrors(std::cout, ctl.errors); return 1; } else if(!ctl.init(alive)) { std::cout << "Control initialization failed." << std::endl; printErrors(std::cout, view.errors, ctl.errors); return 1; } std::cout << "Initialized control." << std::endl; if(!ctl.run(alive)) { printErrors(std::cout, view.errors, ctl.errors); } return 0; } <|endoftext|>
<commit_before> #include "./aux.hpp" #include "./String.hpp" #include "./Log.hpp" #include "./Word.hpp" #include <duct/char.hpp> #include <duct/debug.hpp> #include <duct/CharacterSet.hpp> #include <duct/IO.hpp> #include <cstdlib> #include <algorithm> #include <string> #include <iostream> namespace { static duct::CharacterSet const s_set_whitespace{"\t \r\n"}; } // anonymous namespace // class Word implementation void Word::refresh_counts() { m_counts.clear(); duct::char32 cp; String::const_iterator pos=m_word.cbegin(), next; for (; m_word.cend()!=pos; pos=next) { next=duct::UTF8Utils::decode( pos, m_word.cend(), cp, duct::CHAR_REPLACEMENT); if (next==pos) { // Incomplete sequence; just get out of here return; } else if (!s_set_whitespace.contains(cp)) { count_map_type::iterator const iter=m_counts.find(cp); if (m_counts.end()!=iter) { ++(iter->second); } else { m_counts[cp]=1; } } } } bool Word::matches(Word const& other) const { if (distinct_char_count()!=other.distinct_char_count()) { // Quick exit: the words don't share the same number // of distinct characters return false; } else { for (auto const& x : m_counts) { auto const& iter=other.m_counts.find(x.first); // Either other doesn't have character x.first or // its count is not equal to x's if (other.m_counts.cend()==iter || x.second!=iter->second) { return false; } } } return true; } void Word::print( bool const style, ConsoleAttribute const attr, ConsoleColor const ovr_fgc, ConsoleColor const ovr_bgc ) const { if (style) { Console::instance()->push( attr, (COLOR_NULL!=ovr_fgc) ? ovr_fgc : m_fgc, (COLOR_NULL!=ovr_bgc) ? ovr_bgc : m_bgc ); std::cout<<m_word; Console::instance()->pop(); } else { std::cout<<m_word; } } // class Wordutator implementation namespace { static PhraseParser s_parser{}; struct ColorPair { ConsoleColor fg; ConsoleColor bg; }; ColorPair const s_color_pairs[]{ // BG black {COLOR_RED, COLOR_BLACK}, {COLOR_GREEN, COLOR_BLACK}, {COLOR_BLUE, COLOR_BLACK}, {COLOR_CYAN, COLOR_BLACK}, {COLOR_MAGENTA, COLOR_BLACK}, {COLOR_YELLOW, COLOR_BLACK}, {COLOR_WHITE, COLOR_BLACK}, // BG blue {COLOR_RED, COLOR_BLUE}, {COLOR_GREEN, COLOR_BLUE}, {COLOR_CYAN, COLOR_BLUE}, {COLOR_MAGENTA, COLOR_BLUE}, {COLOR_YELLOW, COLOR_BLUE}, {COLOR_WHITE, COLOR_BLUE}, // BG magenta {COLOR_RED, COLOR_MAGENTA}, {COLOR_GREEN, COLOR_MAGENTA}, {COLOR_CYAN, COLOR_MAGENTA}, {COLOR_YELLOW, COLOR_MAGENTA}, {COLOR_WHITE, COLOR_MAGENTA}, // BG cyan {COLOR_RED, COLOR_CYAN}, {COLOR_YELLOW, COLOR_CYAN}, {COLOR_WHITE, COLOR_CYAN}, // BG white {COLOR_RED, COLOR_WHITE}, {COLOR_BLACK, COLOR_WHITE}, {COLOR_CYAN, COLOR_WHITE}, {COLOR_MAGENTA, COLOR_WHITE}, // BG yellow {COLOR_RED, COLOR_YELLOW}, {COLOR_BLACK, COLOR_YELLOW}, {COLOR_NULL, COLOR_NULL} }; } // anonymous namespace size_t Wordutator::set_phrase(String const& phrase) { m_phrase.assign(phrase); clear(); s_parser.process(m_group, m_phrase); calc_colors(); return get_count(); } void Wordutator::calc_colors() { auto iter=m_group.begin(); auto const* pair=s_color_pairs; for (; m_group.end()!=iter; ++iter, ++pair) { if (COLOR_NULL==pair->fg) { pair=s_color_pairs; } (*iter)->set_color(pair->fg, pair->bg); } } bool Wordutator::compare(Wordutator& other) const { // Match words aux::vector<Word const*> unmatched; aux::list<std::shared_ptr<Word> > candidates {other.m_group.begin(), other.m_group.end()}; for (auto const& word : m_group) { auto candidate_iter=candidates.begin(); for (; candidates.end()!=candidate_iter; ++candidate_iter) { if (word->matches(**candidate_iter)) { break; } } if (candidates.end()!=candidate_iter) { // Match found // Colorize matching word (*candidate_iter)->set_color(*word); candidates.erase(candidate_iter); } else { // No match for word unmatched.emplace_back(word.get()); } } // Any remaining words in candidates were not matchable for (auto& word : candidates) { word->set_color(COLOR_WHITE, COLOR_RED); } bool matches=(candidates.empty() && get_count()==other.get_count()); other.print("compare", false, matches ? COLOR_GREEN : COLOR_RED); // Print un-matched original words if (!unmatched.empty()) { std::putchar(' '); Console::instance()->push(ATTR_BOLD); Log::msgps("||", ATTR_STRIKE, COLOR_DEFAULT, COLOR_RED); Console::instance()->pop(); std::printf(" "); for (auto const word : unmatched) { word->print(true); std::putchar(' '); } } std::putchar('\n'); return matches; } void Wordutator::print( char const prefix[], bool const newline, ConsoleColor const fgc ) const { Log::msgps("%s (%-2lu): ", ATTR_BOLD, fgc, COLOR_DEFAULT, prefix, get_count()); for (auto const& word : m_group) { word->print(true); std::putchar(' '); } if (newline) { std::putchar('\n'); } } // class PhraseParser implementation namespace { enum { TOK_WORD=1, TOK_WORD_SPAN, TOK_PUNCTUATION, TOK_EOF }; } // anonymous namespace bool PhraseParser::process( Wordutator::word_vector_type& group, String const& str ) { duct::IO::imemstream stream{str.data(), str.size()}; if (initialize(stream)) { m_group=&group; do {} while (parse()); reset(); return true; } return false; } void PhraseParser::skip_whitespace() { while ( m_curchar!=duct::CHAR_EOF && s_set_whitespace.contains(m_curchar) ) { next_char(); } } void PhraseParser::reset() { duct::Parser::reset(); m_group=nullptr; } bool PhraseParser::parse() { skip_whitespace(); discern_token(); read_token(); handle_token(); if (TOK_EOF==m_token.get_type() || duct::CHAR_EOF==m_curchar) { return false; } return true; } void PhraseParser::discern_token() { m_token.reset(duct::NULL_TOKEN, false); m_token.set_position(m_line, m_column); switch (m_curchar) { case duct::CHAR_EOF : m_token.set_type(TOK_EOF); break; case duct::CHAR_OPENBRACE : m_token.set_type(TOK_WORD_SPAN); break; default: m_token.set_type(TOK_WORD); break; } } void PhraseParser::read_token() { switch (m_token.get_type()) { case TOK_WORD: read_word_token(); break; case TOK_WORD_SPAN: read_word_span_token(); break; case TOK_EOF: break; // Do nothing default: DUCT_ASSERT(false, "unhandled token"); } } void PhraseParser::handle_token() { switch (m_token.get_type()) { case TOK_WORD_SPAN: case TOK_WORD: if (!m_token.get_buffer().compare(s_set_whitespace)) { m_group->emplace_back( new Word(m_token.get_buffer().to_string<String>())); } break; default: break; } } void PhraseParser::read_word_token() { while (duct::CHAR_EOF!=m_curchar) { if (s_set_whitespace.contains(m_curchar)) { break; } else { m_token.get_buffer().push_back(m_curchar); } next_char(); } } void PhraseParser::read_word_span_token() { while (duct::CHAR_EOF!=m_curchar) { if (duct::CHAR_OPENBRACE==m_curchar) { // Ignore } else if (duct::CHAR_CLOSEBRACE==m_curchar) { next_char(); break; } else { m_token.get_buffer().push_back(m_curchar); } next_char(); } } <commit_msg>Word: appeased the static analyzer.<commit_after> #include "./aux.hpp" #include "./String.hpp" #include "./Log.hpp" #include "./Word.hpp" #include <duct/char.hpp> #include <duct/debug.hpp> #include <duct/CharacterSet.hpp> #include <duct/IO.hpp> #include <cstdlib> #include <algorithm> #include <string> #include <iostream> namespace { static duct::CharacterSet const s_set_whitespace{"\t \r\n"}; } // anonymous namespace // class Word implementation void Word::refresh_counts() { m_counts.clear(); duct::char32 cp=duct::CHAR_REPLACEMENT; String::const_iterator pos=m_word.cbegin(), next; for (; m_word.cend()!=pos; pos=next) { next=duct::UTF8Utils::decode( pos, m_word.cend(), cp, duct::CHAR_REPLACEMENT); if (next==pos) { // Incomplete sequence; just get out of here return; } else if (!s_set_whitespace.contains(cp)) { count_map_type::iterator const iter=m_counts.find(cp); if (m_counts.end()!=iter) { ++(iter->second); } else { m_counts[cp]=1; } } } } bool Word::matches(Word const& other) const { if (distinct_char_count()!=other.distinct_char_count()) { // Quick exit: the words don't share the same number // of distinct characters return false; } else { for (auto const& x : m_counts) { auto const& iter=other.m_counts.find(x.first); // Either other doesn't have character x.first or // its count is not equal to x's if (other.m_counts.cend()==iter || x.second!=iter->second) { return false; } } } return true; } void Word::print( bool const style, ConsoleAttribute const attr, ConsoleColor const ovr_fgc, ConsoleColor const ovr_bgc ) const { if (style) { Console::instance()->push( attr, (COLOR_NULL!=ovr_fgc) ? ovr_fgc : m_fgc, (COLOR_NULL!=ovr_bgc) ? ovr_bgc : m_bgc ); std::cout<<m_word; Console::instance()->pop(); } else { std::cout<<m_word; } } // class Wordutator implementation namespace { static PhraseParser s_parser{}; struct ColorPair { ConsoleColor fg; ConsoleColor bg; }; ColorPair const s_color_pairs[]{ // BG black {COLOR_RED, COLOR_BLACK}, {COLOR_GREEN, COLOR_BLACK}, {COLOR_BLUE, COLOR_BLACK}, {COLOR_CYAN, COLOR_BLACK}, {COLOR_MAGENTA, COLOR_BLACK}, {COLOR_YELLOW, COLOR_BLACK}, {COLOR_WHITE, COLOR_BLACK}, // BG blue {COLOR_RED, COLOR_BLUE}, {COLOR_GREEN, COLOR_BLUE}, {COLOR_CYAN, COLOR_BLUE}, {COLOR_MAGENTA, COLOR_BLUE}, {COLOR_YELLOW, COLOR_BLUE}, {COLOR_WHITE, COLOR_BLUE}, // BG magenta {COLOR_RED, COLOR_MAGENTA}, {COLOR_GREEN, COLOR_MAGENTA}, {COLOR_CYAN, COLOR_MAGENTA}, {COLOR_YELLOW, COLOR_MAGENTA}, {COLOR_WHITE, COLOR_MAGENTA}, // BG cyan {COLOR_RED, COLOR_CYAN}, {COLOR_YELLOW, COLOR_CYAN}, {COLOR_WHITE, COLOR_CYAN}, // BG white {COLOR_RED, COLOR_WHITE}, {COLOR_BLACK, COLOR_WHITE}, {COLOR_CYAN, COLOR_WHITE}, {COLOR_MAGENTA, COLOR_WHITE}, // BG yellow {COLOR_RED, COLOR_YELLOW}, {COLOR_BLACK, COLOR_YELLOW}, {COLOR_NULL, COLOR_NULL} }; } // anonymous namespace size_t Wordutator::set_phrase(String const& phrase) { m_phrase.assign(phrase); clear(); s_parser.process(m_group, m_phrase); calc_colors(); return get_count(); } void Wordutator::calc_colors() { auto iter=m_group.begin(); auto const* pair=s_color_pairs; for (; m_group.end()!=iter; ++iter, ++pair) { if (COLOR_NULL==pair->fg) { pair=s_color_pairs; } (*iter)->set_color(pair->fg, pair->bg); } } bool Wordutator::compare(Wordutator& other) const { // Match words aux::vector<Word const*> unmatched; aux::list<std::shared_ptr<Word> > candidates {other.m_group.begin(), other.m_group.end()}; for (auto const& word : m_group) { auto candidate_iter=candidates.begin(); for (; candidates.end()!=candidate_iter; ++candidate_iter) { if (word->matches(**candidate_iter)) { break; } } if (candidates.end()!=candidate_iter) { // Match found // Colorize matching word (*candidate_iter)->set_color(*word); candidates.erase(candidate_iter); } else { // No match for word unmatched.emplace_back(word.get()); } } // Any remaining words in candidates were not matchable for (auto& word : candidates) { word->set_color(COLOR_WHITE, COLOR_RED); } bool matches=(candidates.empty() && get_count()==other.get_count()); other.print("compare", false, matches ? COLOR_GREEN : COLOR_RED); // Print un-matched original words if (!unmatched.empty()) { std::putchar(' '); Console::instance()->push(ATTR_BOLD); Log::msgps("||", ATTR_STRIKE, COLOR_DEFAULT, COLOR_RED); Console::instance()->pop(); std::printf(" "); for (auto const word : unmatched) { word->print(true); std::putchar(' '); } } std::putchar('\n'); return matches; } void Wordutator::print( char const prefix[], bool const newline, ConsoleColor const fgc ) const { Log::msgps("%s (%-2lu): ", ATTR_BOLD, fgc, COLOR_DEFAULT, prefix, get_count()); for (auto const& word : m_group) { word->print(true); std::putchar(' '); } if (newline) { std::putchar('\n'); } } // class PhraseParser implementation namespace { enum { TOK_WORD=1, TOK_WORD_SPAN, TOK_PUNCTUATION, TOK_EOF }; } // anonymous namespace bool PhraseParser::process( Wordutator::word_vector_type& group, String const& str ) { duct::IO::imemstream stream{str.data(), str.size()}; if (initialize(stream)) { m_group=&group; do {} while (parse()); reset(); return true; } return false; } void PhraseParser::skip_whitespace() { while ( m_curchar!=duct::CHAR_EOF && s_set_whitespace.contains(m_curchar) ) { next_char(); } } void PhraseParser::reset() { duct::Parser::reset(); m_group=nullptr; } bool PhraseParser::parse() { skip_whitespace(); discern_token(); read_token(); handle_token(); if (TOK_EOF==m_token.get_type() || duct::CHAR_EOF==m_curchar) { return false; } return true; } void PhraseParser::discern_token() { m_token.reset(duct::NULL_TOKEN, false); m_token.set_position(m_line, m_column); switch (m_curchar) { case duct::CHAR_EOF : m_token.set_type(TOK_EOF); break; case duct::CHAR_OPENBRACE : m_token.set_type(TOK_WORD_SPAN); break; default: m_token.set_type(TOK_WORD); break; } } void PhraseParser::read_token() { switch (m_token.get_type()) { case TOK_WORD: read_word_token(); break; case TOK_WORD_SPAN: read_word_span_token(); break; case TOK_EOF: break; // Do nothing default: DUCT_ASSERT(false, "unhandled token"); } } void PhraseParser::handle_token() { switch (m_token.get_type()) { case TOK_WORD_SPAN: case TOK_WORD: if (!m_token.get_buffer().compare(s_set_whitespace)) { m_group->emplace_back( new Word(m_token.get_buffer().to_string<String>())); } break; default: break; } } void PhraseParser::read_word_token() { while (duct::CHAR_EOF!=m_curchar) { if (s_set_whitespace.contains(m_curchar)) { break; } else { m_token.get_buffer().push_back(m_curchar); } next_char(); } } void PhraseParser::read_word_span_token() { while (duct::CHAR_EOF!=m_curchar) { if (duct::CHAR_OPENBRACE==m_curchar) { // Ignore } else if (duct::CHAR_CLOSEBRACE==m_curchar) { next_char(); break; } else { m_token.get_buffer().push_back(m_curchar); } next_char(); } } <|endoftext|>
<commit_before>#include "PostProcessor.hpp" #if 1 //#ifdef WIN32 namespace Slic3r { //FIXME Ignore until we include boost::process void run_post_process_scripts(const std::string &path, const PrintConfig &config) { } } // namespace Slic3r #else #include <boost/process/system.hpp> namespace Slic3r { void run_post_process_scripts(const std::string &path, const PrintConfig &config) { if (config.post_process.values.empty()) return; config.setenv_(); for (std::string script: config.post_process.values) { // Ignore empty post processing script lines. boost::trim(script); if (script.empty()) continue; BOOST_LOG_TRIVIAL(info) << "Executing script " << script << " on file " << path; if (! boost::filesystem::exists(boost::filesystem::path(path))) throw std::runtime_exception(std::string("The configured post-processing script does not exist: ") + path); #ifndef WIN32 file_status fs = boost::filesystem::status(path); //FIXME test if executible by the effective UID / GID. // throw std::runtime_exception(std::string("The configured post-processing script is not executable: check permissions. ") + path)); #endif int result = 0; #ifdef WIN32 if (boost::iends_with(file, ".gcode")) { // The current process may be slic3r.exe or slic3r-console.exe. // Find the path of the process: wchar_t wpath_exe[_MAX_PATH + 1]; ::GetModuleFileNameW(nullptr, wpath_exe, _MAX_PATH); boost::filesystem::path path_exe(wpath_exe); // Replace it with the current perl interpreter. result = boost::process::system((path_exe.parent_path() / "perl5.24.0.exe").string(), script, output_file); } else #else result = boost::process::system(script, output_file); #endif if (result < 0) BOOST_LOG_TRIVIAL(error) << "Script " << script << " on file " << path << " failed. Negative error code returned."; } } } // namespace Slic3r #endif <commit_msg>Fixed post-processing (including perms check) on Unix<commit_after>#include "PostProcessor.hpp" #ifdef WIN32 namespace Slic3r { //FIXME Ignore until we include boost::process void run_post_process_scripts(const std::string &path, const PrintConfig &config) { } } // namespace Slic3r #else #include <boost/process/system.hpp> #ifndef WIN32 #include <sys/stat.h> //for getting filesystem UID/GID #include <unistd.h> //for getting current UID/GID #endif namespace Slic3r { void run_post_process_scripts(const std::string &path, const PrintConfig &config) { if (config.post_process.values.empty()) return; //config.setenv_(); auto gcode_file = boost::filesystem::path(path); if (!boost::filesystem::exists(gcode_file)) throw std::runtime_error(std::string("Post-processor can't find exported gcode file")); for (std::string script: config.post_process.values) { // Ignore empty post processing script lines. boost::trim(script); if (script.empty()) continue; BOOST_LOG_TRIVIAL(info) << "Executing script " << script << " on file " << path; if (! boost::filesystem::exists(boost::filesystem::path(script))) throw std::runtime_error(std::string("The configured post-processing script does not exist: ") + script); #ifndef WIN32 struct stat info; if (stat(script.c_str(), &info)) throw std::runtime_error(std::string("Cannot read information for post-processing script: ") + script); boost::filesystem::perms script_perms = boost::filesystem::status(script).permissions(); //if UID matches, check UID perm. else if GID matches, check GID perm. Otherwise check other perm. if (!(script_perms & ((info.st_uid == geteuid()) ? boost::filesystem::perms::owner_exe : ((info.st_gid == getegid()) ? boost::filesystem::perms::group_exe : boost::filesystem::perms::others_exe)))) throw std::runtime_error(std::string("The configured post-processing script is not executable: check permissions. ") + script); #endif int result = 0; #ifdef WIN32 if (boost::iends_with(file, ".gcode")) { // The current process may be slic3r.exe or slic3r-console.exe. // Find the path of the process: wchar_t wpath_exe[_MAX_PATH + 1]; ::GetModuleFileNameW(nullptr, wpath_exe, _MAX_PATH); boost::filesystem::path path_exe(wpath_exe); // Replace it with the current perl interpreter. result = boost::process::system((path_exe.parent_path() / "perl5.24.0.exe").string(), script, gcode_file); } else #else result = boost::process::system(script, gcode_file); #endif if (result < 0) BOOST_LOG_TRIVIAL(error) << "Script " << script << " on file " << path << " failed. Negative error code returned."; } } } // namespace Slic3r #endif <|endoftext|>
<commit_before>// This file is distributed under the BSD License. // See "license.txt" for details. // Copyright 2009-2010, Jonathan Turner ([email protected]) // and Jason Turner ([email protected]) // http://www.chaiscript.com #include <iostream> #include <list> #include <boost/algorithm/string/trim.hpp> #define _CRT_SECURE_NO_WARNINGS #include <chaiscript/chaiscript.hpp> #ifdef READLINE_AVAILABLE #include <readline/readline.h> #include <readline/history.h> #else void *cast_module_symbol(std::string (*t_path)()) { union cast_union { std::string (*in_ptr)(); void *out_ptr; }; cast_union c; c.in_ptr = t_path; return c.out_ptr; } std::string default_search_path() { #ifdef CHAISCRIPT_WINDOWS TCHAR path[2048]; int size = GetModuleFileName(0, path, sizeof(path)-1); std::string exepath(path, size); size_t secondtolastslash = exepath.rfind('\\', exepath.rfind('\\') - 1); if (secondtolastslash != std::string::npos) { return exepath.substr(0, secondtolastslash) + "\\lib\\chaiscript\\"; } else { return ""; } #else std::string exepath; std::vector<char> buf(2048); ssize_t size = -1; if ((size = readlink("/proc/self/exe", &buf.front(), buf.size())) != -1) { exepath = std::string(&buf.front(), size); } if (exepath.empty()) { if ((size = readlink("/proc/curproc/file", &buf.front(), buf.size())) != -1) { exepath = std::string(&buf.front(), size); } } if (exepath.empty()) { if ((size = readlink("/proc/self/path/a.out", &buf.front(), buf.size())) != -1) { exepath = std::string(&buf.front(), size); } } if (exepath.empty()) { Dl_info rInfo; memset( &rInfo, 0, sizeof(rInfo) ); if ( !dladdr(cast_module_symbol(&default_search_path), &rInfo) || !rInfo.dli_fname ) { return ""; } exepath = std::string(rInfo.dli_fname); } size_t secondtolastslash = exepath.rfind('/', exepath.rfind('/') - 1); if (secondtolastslash != std::string::npos) { return exepath.substr(0, secondtolastslash) + "/lib/chaiscript/"; } else { return ""; } #endif } char* readline(const char* p) { std::string retval; std::cout << p ; std::getline(std::cin, retval); #ifdef BOOST_MSVC return std::cin.eof() ? NULL : _strdup(retval.c_str()); #else return std::cin.eof() ? NULL : strdup(retval.c_str()); #endif } void add_history(const char*){} void using_history(){} #endif void help(int n) { if ( n >= 0 ) { std::cout << "ChaiScript evaluator. To evaluate an expression, type it and press <enter>." << std::endl; std::cout << "Additionally, you can inspect the runtime system using:" << std::endl; std::cout << " dump_system() - outputs all functions registered to the system" << std::endl; std::cout << " dump_object(x) - dumps information about the given symbol" << std::endl; } else { std::cout << "usage : chai [option]+" << std::endl; std::cout << "option:" << std::endl; std::cout << " -h | --help" << std::endl; std::cout << " -i | --interactive" << std::endl; std::cout << " -c | --command cmd" << std::endl; std::cout << " -v | --version" << std::endl; std::cout << " - --stdin" << std::endl; std::cout << " filepath" << std::endl; } } void version(int){ std::cout << "chai: compiled " << __TIME__ << " " << __DATE__ << std::endl; } bool throws_exception(const boost::function<void ()> &f) { try { f(); } catch (...) { return true; } return false; } chaiscript::exception::eval_error get_eval_error(const boost::function<void ()> &f) { try { f(); } catch (const chaiscript::exception::eval_error &e) { return e; } throw std::runtime_error("no exception throw"); } std::string get_next_command() { std::string retval("quit"); if ( ! std::cin.eof() ) { char *input_raw = readline("eval> "); if ( input_raw ) { add_history(input_raw); std::string val(input_raw); size_t pos = val.find_first_not_of("\t \n"); if (pos != std::string::npos) { val.erase(0, pos); } pos = val.find_last_not_of("\t \n"); if (pos != std::string::npos) { val.erase(pos+1, std::string::npos); } retval = val; ::free(input_raw); } } if( retval == "quit" || retval == "exit" || retval == "help" || retval == "version") { retval += "(0)"; } return retval; } // We have to wrap exit with our own because Clang has a hard time with // function pointers to functions with special attributes (system exit being marked NORETURN) void myexit(int return_val) { exit(return_val); } void interactive(chaiscript::ChaiScript& chai) { using_history(); for (;;) { std::string input = get_next_command(); try { // evaluate input chaiscript::Boxed_Value val = chai.eval(input); //Then, we try to print the result of the evaluation to the user if (!val.get_type_info().bare_equal(chaiscript::user_type<void>())) { try { std::cout << chai.eval<boost::function<std::string (const chaiscript::Boxed_Value &bv)> >("to_string")(val) << std::endl; } catch (...) {} //If we can't, do nothing } } catch (const chaiscript::exception::eval_error &ee) { std::cout << ee.what(); if (ee.call_stack.size() > 0) { std::cout << "during evaluation at (" << ee.call_stack[0]->start.line << ", " << ee.call_stack[0]->start.column << ")"; } std::cout << std::endl; } catch (const std::exception &e) { std::cout << e.what(); std::cout << std::endl; } } } int main(int argc, char *argv[]) { std::vector<std::string> usepaths; std::vector<std::string> modulepaths; // Disable deprecation warning for getenv call. #ifdef BOOST_MSVC #pragma warning(push) #pragma warning(disable : 4996) #endif const char *usepath = getenv("CHAI_USE_PATH"); const char *modulepath = getenv("CHAI_MODULE_PATH"); #ifdef BOOST_MSVC #pragma warning(pop) #endif usepaths.push_back(""); if (usepath) { usepaths.push_back(usepath); } std::string searchpath = default_search_path(); modulepaths.push_back(searchpath); modulepaths.push_back(""); if (modulepath) { modulepaths.push_back(modulepath); } chaiscript::ChaiScript chai(modulepaths,usepaths); chai.add(chaiscript::fun(&myexit), "exit"); chai.add(chaiscript::fun(&myexit), "quit"); chai.add(chaiscript::fun(&help), "help"); chai.add(chaiscript::fun(&version), "version"); chai.add(chaiscript::fun(&throws_exception), "throws_exception"); chai.add(chaiscript::fun(&get_eval_error), "get_eval_error"); for (int i = 0; i < argc; ++i) { if ( i == 0 && argc > 1 ) { ++i; } std::string arg( i ? argv[i] : "--interactive" ); enum { eInteractive , eCommand , eFile } mode = eCommand ; if ( arg == "-c" || arg == "--command" ) { if ( (i+1) >= argc ) { std::cout << "insufficient input following " << arg << std::endl; return EXIT_FAILURE; } else { arg = argv[++i]; } } else if ( arg == "-" || arg == "--stdin" ) { arg = "" ; std::string line; while ( std::getline(std::cin, line) ) { arg += line + '\n' ; } } else if ( arg == "-v" || arg == "--version" ) { arg = "version(0)" ; } else if ( arg == "-h" || arg == "--help" ) { arg = "help(-1)"; } else if ( arg == "-i" || arg == "--interactive" ) { mode = eInteractive ; } else if ( arg.find('-') == 0 ) { std::cout << "unrecognised argument " << arg << std::endl; return EXIT_FAILURE; } else { mode = eFile; } chaiscript::Boxed_Value val ; try { switch ( mode ) { case eInteractive : interactive(chai); break; case eCommand : val = chai.eval(arg); break; case eFile : val = chai.eval_file(arg); break; default : std::cout << "Unrecognized execution mode" << std::endl; return EXIT_FAILURE; } } catch (const chaiscript::exception::eval_error &ee) { std::cout << ee.pretty_print(); std::cout << std::endl; return EXIT_FAILURE; } catch (std::exception &e) { std::cout << e.what() << std::endl; return EXIT_FAILURE; } } return EXIT_SUCCESS; } <commit_msg>Fix build error on 4.x branch if readline is found<commit_after>// This file is distributed under the BSD License. // See "license.txt" for details. // Copyright 2009-2010, Jonathan Turner ([email protected]) // and Jason Turner ([email protected]) // http://www.chaiscript.com #include <iostream> #include <list> #include <boost/algorithm/string/trim.hpp> #define _CRT_SECURE_NO_WARNINGS #include <chaiscript/chaiscript.hpp> #ifdef READLINE_AVAILABLE #include <readline/readline.h> #include <readline/history.h> #else char* readline(const char* p) { std::string retval; std::cout << p ; std::getline(std::cin, retval); #ifdef BOOST_MSVC return std::cin.eof() ? NULL : _strdup(retval.c_str()); #else return std::cin.eof() ? NULL : strdup(retval.c_str()); #endif } void add_history(const char*){} void using_history(){} #endif void *cast_module_symbol(std::string (*t_path)()) { union cast_union { std::string (*in_ptr)(); void *out_ptr; }; cast_union c; c.in_ptr = t_path; return c.out_ptr; } std::string default_search_path() { #ifdef CHAISCRIPT_WINDOWS TCHAR path[2048]; int size = GetModuleFileName(0, path, sizeof(path)-1); std::string exepath(path, size); size_t secondtolastslash = exepath.rfind('\\', exepath.rfind('\\') - 1); if (secondtolastslash != std::string::npos) { return exepath.substr(0, secondtolastslash) + "\\lib\\chaiscript\\"; } else { return ""; } #else std::string exepath; std::vector<char> buf(2048); ssize_t size = -1; if ((size = readlink("/proc/self/exe", &buf.front(), buf.size())) != -1) { exepath = std::string(&buf.front(), size); } if (exepath.empty()) { if ((size = readlink("/proc/curproc/file", &buf.front(), buf.size())) != -1) { exepath = std::string(&buf.front(), size); } } if (exepath.empty()) { if ((size = readlink("/proc/self/path/a.out", &buf.front(), buf.size())) != -1) { exepath = std::string(&buf.front(), size); } } if (exepath.empty()) { Dl_info rInfo; memset( &rInfo, 0, sizeof(rInfo) ); if ( !dladdr(cast_module_symbol(&default_search_path), &rInfo) || !rInfo.dli_fname ) { return ""; } exepath = std::string(rInfo.dli_fname); } size_t secondtolastslash = exepath.rfind('/', exepath.rfind('/') - 1); if (secondtolastslash != std::string::npos) { return exepath.substr(0, secondtolastslash) + "/lib/chaiscript/"; } else { return ""; } #endif } void help(int n) { if ( n >= 0 ) { std::cout << "ChaiScript evaluator. To evaluate an expression, type it and press <enter>." << std::endl; std::cout << "Additionally, you can inspect the runtime system using:" << std::endl; std::cout << " dump_system() - outputs all functions registered to the system" << std::endl; std::cout << " dump_object(x) - dumps information about the given symbol" << std::endl; } else { std::cout << "usage : chai [option]+" << std::endl; std::cout << "option:" << std::endl; std::cout << " -h | --help" << std::endl; std::cout << " -i | --interactive" << std::endl; std::cout << " -c | --command cmd" << std::endl; std::cout << " -v | --version" << std::endl; std::cout << " - --stdin" << std::endl; std::cout << " filepath" << std::endl; } } void version(int){ std::cout << "chai: compiled " << __TIME__ << " " << __DATE__ << std::endl; } bool throws_exception(const boost::function<void ()> &f) { try { f(); } catch (...) { return true; } return false; } chaiscript::exception::eval_error get_eval_error(const boost::function<void ()> &f) { try { f(); } catch (const chaiscript::exception::eval_error &e) { return e; } throw std::runtime_error("no exception throw"); } std::string get_next_command() { std::string retval("quit"); if ( ! std::cin.eof() ) { char *input_raw = readline("eval> "); if ( input_raw ) { add_history(input_raw); std::string val(input_raw); size_t pos = val.find_first_not_of("\t \n"); if (pos != std::string::npos) { val.erase(0, pos); } pos = val.find_last_not_of("\t \n"); if (pos != std::string::npos) { val.erase(pos+1, std::string::npos); } retval = val; ::free(input_raw); } } if( retval == "quit" || retval == "exit" || retval == "help" || retval == "version") { retval += "(0)"; } return retval; } // We have to wrap exit with our own because Clang has a hard time with // function pointers to functions with special attributes (system exit being marked NORETURN) void myexit(int return_val) { exit(return_val); } void interactive(chaiscript::ChaiScript& chai) { using_history(); for (;;) { std::string input = get_next_command(); try { // evaluate input chaiscript::Boxed_Value val = chai.eval(input); //Then, we try to print the result of the evaluation to the user if (!val.get_type_info().bare_equal(chaiscript::user_type<void>())) { try { std::cout << chai.eval<boost::function<std::string (const chaiscript::Boxed_Value &bv)> >("to_string")(val) << std::endl; } catch (...) {} //If we can't, do nothing } } catch (const chaiscript::exception::eval_error &ee) { std::cout << ee.what(); if (ee.call_stack.size() > 0) { std::cout << "during evaluation at (" << ee.call_stack[0]->start.line << ", " << ee.call_stack[0]->start.column << ")"; } std::cout << std::endl; } catch (const std::exception &e) { std::cout << e.what(); std::cout << std::endl; } } } int main(int argc, char *argv[]) { std::vector<std::string> usepaths; std::vector<std::string> modulepaths; // Disable deprecation warning for getenv call. #ifdef BOOST_MSVC #pragma warning(push) #pragma warning(disable : 4996) #endif const char *usepath = getenv("CHAI_USE_PATH"); const char *modulepath = getenv("CHAI_MODULE_PATH"); #ifdef BOOST_MSVC #pragma warning(pop) #endif usepaths.push_back(""); if (usepath) { usepaths.push_back(usepath); } std::string searchpath = default_search_path(); modulepaths.push_back(searchpath); modulepaths.push_back(""); if (modulepath) { modulepaths.push_back(modulepath); } chaiscript::ChaiScript chai(modulepaths,usepaths); chai.add(chaiscript::fun(&myexit), "exit"); chai.add(chaiscript::fun(&myexit), "quit"); chai.add(chaiscript::fun(&help), "help"); chai.add(chaiscript::fun(&version), "version"); chai.add(chaiscript::fun(&throws_exception), "throws_exception"); chai.add(chaiscript::fun(&get_eval_error), "get_eval_error"); for (int i = 0; i < argc; ++i) { if ( i == 0 && argc > 1 ) { ++i; } std::string arg( i ? argv[i] : "--interactive" ); enum { eInteractive , eCommand , eFile } mode = eCommand ; if ( arg == "-c" || arg == "--command" ) { if ( (i+1) >= argc ) { std::cout << "insufficient input following " << arg << std::endl; return EXIT_FAILURE; } else { arg = argv[++i]; } } else if ( arg == "-" || arg == "--stdin" ) { arg = "" ; std::string line; while ( std::getline(std::cin, line) ) { arg += line + '\n' ; } } else if ( arg == "-v" || arg == "--version" ) { arg = "version(0)" ; } else if ( arg == "-h" || arg == "--help" ) { arg = "help(-1)"; } else if ( arg == "-i" || arg == "--interactive" ) { mode = eInteractive ; } else if ( arg.find('-') == 0 ) { std::cout << "unrecognised argument " << arg << std::endl; return EXIT_FAILURE; } else { mode = eFile; } chaiscript::Boxed_Value val ; try { switch ( mode ) { case eInteractive : interactive(chai); break; case eCommand : val = chai.eval(arg); break; case eFile : val = chai.eval_file(arg); break; default : std::cout << "Unrecognized execution mode" << std::endl; return EXIT_FAILURE; } } catch (const chaiscript::exception::eval_error &ee) { std::cout << ee.pretty_print(); std::cout << std::endl; return EXIT_FAILURE; } catch (std::exception &e) { std::cout << e.what() << std::endl; return EXIT_FAILURE; } } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* Copyright 2013-2014 Dietrich Epp. This file is part of Oubliette. Oubliette is licensed under the terms of the 2-clause BSD license. For more information, see LICENSE.txt. */ #include <SDL.h> #include <SDL_image.h> #include <cstdio> #include <cstdlib> #include <cstring> #include <unistd.h> #include <memory> #include "defs.hpp" #include "opengl.hpp" #include "rand.hpp" #include "game/state.hpp" namespace core { SDL_Window *window; SDL_GLContext context; __attribute__((noreturn)) void die(const char *reason) { std::fprintf(stderr, "Error: %s\n", reason); SDL_Quit(); std::exit(1); } __attribute__((noreturn)) void die_alloc() { die("Out of memory"); } void check_sdl_error(const char *file, int line) { const char *error = SDL_GetError(); if (*error) { std::fprintf(stderr, "SDL error: %s:%d: %s\n", file, line, error); SDL_ClearError(); } } __attribute__((noreturn)) void die_sdl(const char *file, int line, const char *msg) { const char *error = SDL_GetError(); if (*error) { std::fprintf(stderr, "Error: %s:%d: %s: %s\n", file, line, msg, error); } else { std::fprintf(stderr, "Error: %s:%d: %s\n", file, line, msg); } SDL_Quit(); std::exit(1); } struct gl_error { unsigned short code; const char name[30]; }; static const gl_error GLERRORS[] = { { 0x0500, "INVALID_ENUM" }, { 0x0501, "INVALID_VALUE" }, { 0x0502, "INVALID_OPERATION" }, { 0x0503, "STACK_OVERFLOW" }, { 0x0504, "STACK_UNDERFLOW" }, { 0x0505, "OUT_OF_MEMORY" }, { 0x0506, "INVALID_FRAMEBUFFER_OPERATION" }, { 0x8031, "TABLE_TOO_LARGE" }, }; void check_gl_error(const char *file, int line) { GLenum error; while ((error = glGetError())) { int i, n = sizeof(GLERRORS) / sizeof(*GLERRORS); for (i = 0; i < n; i++) { if (error == GLERRORS[i].code) { std::fprintf(stderr, "OpenGL error: %s:%d: GL_%s\n", file, line, GLERRORS[i].name); break; } } if (i == n) { std::fprintf(stderr, "OpenGL error: %s:%d: Unknown (0x%04x)\n", file, line, (unsigned) error); } } } void delay(int msec) { SDL_Delay(msec); } void swap_window() { SDL_GL_SwapWindow(window); } static void init_path() { int r = chdir("../data"); if (r) die("Could not find data directory."); } void init() { if (SDL_Init(SDL_INIT_VIDEO) < 0) die("Unable to initialize SDL"); int flags = IMG_INIT_PNG; int result = IMG_Init(flags); check_sdl_error(HERE); if ((result & flags) != flags) die("Unable to initialize SDL_image"); // SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); // SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); // SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, // SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); window = SDL_CreateWindow( "The Oubliette Within", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, IWIDTH, IHEIGHT, SDL_WINDOW_OPENGL); check_sdl_error(HERE); if (!window) die("Unable to create window"); context = SDL_GL_CreateContext(window); check_sdl_error(HERE); if (!context) die("Unable to create OpenGL context"); GLenum glewstatus = glewInit(); if (glewstatus != GLEW_OK) { std::fprintf(stderr, "GLEW error: %s\n", glewGetErrorString(glewstatus)); die("Could not initialize OpenGL."); } if (!GLEW_VERSION_2_1) die("OpenGL 2.1 is missing"); init_path(); rng::global.init(); } void term() { SDL_GL_DeleteContext(context); SDL_DestroyWindow(core::window); SDL_Quit(); } } using game::key; static bool decode_key(int scancode, key *k) { switch (scancode) { case SDL_SCANCODE_W: case SDL_SCANCODE_UP: *k = key::UP; return true; case SDL_SCANCODE_A: case SDL_SCANCODE_LEFT: *k = key::LEFT; return true; case SDL_SCANCODE_S: case SDL_SCANCODE_DOWN: *k = key::DOWN; return true; case SDL_SCANCODE_D: case SDL_SCANCODE_RIGHT: *k = key::RIGHT; return true; case SDL_SCANCODE_SPACE: case SDL_SCANCODE_RETURN: *k = key::SELECT; return true; case SDL_SCANCODE_TAB: case SDL_SCANCODE_PAGEDOWN: *k = key::NEXT; return true; case SDL_SCANCODE_PAGEUP: *k = key::PREV; return true; case SDL_SCANCODE_BACKSPACE: case SDL_SCANCODE_DELETE: *k = key::DELETE; return true; case SDL_SCANCODE_LSHIFT: case SDL_SCANCODE_RSHIFT: *k = key::SHIFT; return true; default: return false; } } int main(int argc, char *argv[]) { const char *start_level = "difficulty"; bool edit_mode = false; if (argc >= 3) { if (!std::strcmp(argv[1], "--edit") || !std::strcmp(argv[1], "-e")) { start_level = argv[2]; edit_mode = true; } else if (!std::strcmp(argv[1], "--start-at") || !std::strcmp(argv[1], "-s")) { start_level = argv[2]; } } const unsigned MIN_TICKS1 = 1000 / core::MAXFPS; const unsigned MIN_TICKS = MIN_TICKS1 > 0 ? MIN_TICKS1 : 1; core::init(); { bool do_quit = false; unsigned last_frame = SDL_GetTicks(); game::state gstate(edit_mode); gstate.set_level(start_level); while (!do_quit) { SDL_Event e; while (SDL_PollEvent(&e)) { switch (e.common.type) { case SDL_QUIT: do_quit = true; break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: gstate.mouse_click( e.button.x / core::SCALE, (core::IHEIGHT - 1 - e.button.y) / core::SCALE, e.common.type == SDL_MOUSEBUTTONDOWN ? e.button.button : -1); break; case SDL_MOUSEMOTION: gstate.mouse_move( e.motion.x / core::SCALE, (core::IHEIGHT - 1 - e.motion.y) / core::SCALE); break; case SDL_KEYDOWN: case SDL_KEYUP: key k; if (decode_key(e.key.keysym.scancode, &k)) gstate.event_key(k, e.common.type == SDL_KEYDOWN); break; } } gstate.draw(SDL_GetTicks()); core::swap_window(); unsigned now = SDL_GetTicks(); unsigned delta = now - last_frame; if (delta < MIN_TICKS) { SDL_Delay(MIN_TICKS - delta); now = SDL_GetTicks(); } last_frame = now; } } core::term(); return 0; } <commit_msg>Make default data path suitable for release<commit_after>/* Copyright 2013-2014 Dietrich Epp. This file is part of Oubliette. Oubliette is licensed under the terms of the 2-clause BSD license. For more information, see LICENSE.txt. */ #include <SDL.h> #include <SDL_image.h> #include <cstdio> #include <cstdlib> #include <cstring> #include <unistd.h> #include <memory> #include "defs.hpp" #include "opengl.hpp" #include "rand.hpp" #include "game/state.hpp" namespace core { SDL_Window *window; SDL_GLContext context; __attribute__((noreturn)) void die(const char *reason) { std::fprintf(stderr, "Error: %s\n", reason); SDL_Quit(); std::exit(1); } __attribute__((noreturn)) void die_alloc() { die("Out of memory"); } void check_sdl_error(const char *file, int line) { const char *error = SDL_GetError(); if (*error) { std::fprintf(stderr, "SDL error: %s:%d: %s\n", file, line, error); SDL_ClearError(); } } __attribute__((noreturn)) void die_sdl(const char *file, int line, const char *msg) { const char *error = SDL_GetError(); if (*error) { std::fprintf(stderr, "Error: %s:%d: %s: %s\n", file, line, msg, error); } else { std::fprintf(stderr, "Error: %s:%d: %s\n", file, line, msg); } SDL_Quit(); std::exit(1); } struct gl_error { unsigned short code; const char name[30]; }; static const gl_error GLERRORS[] = { { 0x0500, "INVALID_ENUM" }, { 0x0501, "INVALID_VALUE" }, { 0x0502, "INVALID_OPERATION" }, { 0x0503, "STACK_OVERFLOW" }, { 0x0504, "STACK_UNDERFLOW" }, { 0x0505, "OUT_OF_MEMORY" }, { 0x0506, "INVALID_FRAMEBUFFER_OPERATION" }, { 0x8031, "TABLE_TOO_LARGE" }, }; void check_gl_error(const char *file, int line) { GLenum error; while ((error = glGetError())) { int i, n = sizeof(GLERRORS) / sizeof(*GLERRORS); for (i = 0; i < n; i++) { if (error == GLERRORS[i].code) { std::fprintf(stderr, "OpenGL error: %s:%d: GL_%s\n", file, line, GLERRORS[i].name); break; } } if (i == n) { std::fprintf(stderr, "OpenGL error: %s:%d: Unknown (0x%04x)\n", file, line, (unsigned) error); } } } void delay(int msec) { SDL_Delay(msec); } void swap_window() { SDL_GL_SwapWindow(window); } static void init_path(const char *data_dir) { int r = chdir(data_dir); if (r) die("Could not find data directory."); } void init() { if (SDL_Init(SDL_INIT_VIDEO) < 0) die("Unable to initialize SDL"); int flags = IMG_INIT_PNG; int result = IMG_Init(flags); check_sdl_error(HERE); if ((result & flags) != flags) die("Unable to initialize SDL_image"); // SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); // SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); // SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, // SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); window = SDL_CreateWindow( "The Oubliette Within", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, IWIDTH, IHEIGHT, SDL_WINDOW_OPENGL); check_sdl_error(HERE); if (!window) die("Unable to create window"); context = SDL_GL_CreateContext(window); check_sdl_error(HERE); if (!context) die("Unable to create OpenGL context"); GLenum glewstatus = glewInit(); if (glewstatus != GLEW_OK) { std::fprintf(stderr, "GLEW error: %s\n", glewGetErrorString(glewstatus)); die("Could not initialize OpenGL."); } if (!GLEW_VERSION_2_1) die("OpenGL 2.1 is missing"); rng::global.init(); } void term() { SDL_GL_DeleteContext(context); SDL_DestroyWindow(core::window); SDL_Quit(); } } using game::key; static bool decode_key(int scancode, key *k) { switch (scancode) { case SDL_SCANCODE_W: case SDL_SCANCODE_UP: *k = key::UP; return true; case SDL_SCANCODE_A: case SDL_SCANCODE_LEFT: *k = key::LEFT; return true; case SDL_SCANCODE_S: case SDL_SCANCODE_DOWN: *k = key::DOWN; return true; case SDL_SCANCODE_D: case SDL_SCANCODE_RIGHT: *k = key::RIGHT; return true; case SDL_SCANCODE_SPACE: case SDL_SCANCODE_RETURN: *k = key::SELECT; return true; case SDL_SCANCODE_TAB: case SDL_SCANCODE_PAGEDOWN: *k = key::NEXT; return true; case SDL_SCANCODE_PAGEUP: *k = key::PREV; return true; case SDL_SCANCODE_BACKSPACE: case SDL_SCANCODE_DELETE: *k = key::DELETE; return true; case SDL_SCANCODE_LSHIFT: case SDL_SCANCODE_RSHIFT: *k = key::SHIFT; return true; default: return false; } } int main(int argc, char *argv[]) { const char *start_level = "difficulty"; const char *data_dir = "Data"; bool edit_mode = false; int i = 1; while (i < argc) { const char *a = argv[i]; if (a[0] != '-') { start_level = a; i++; } else if (!std::strcmp(a, "-d") || !std::strcmp(a, "--dir")) { i++; if (i >= argc) { std::fprintf(stderr, "Warning: --dir/-d needs an argument\n"); continue; } data_dir = argv[i]; i++; } else if (!std::strcmp(a, "--edit") || !std::strcmp(a, "-e")) { edit_mode = true; i++; } else if (std::strlen(a) >= 4 && !std::memcmp(a, "-psn", 4)) { i++; } else { std::fprintf(stderr, "Warning: unknown argument: %s\n", a); i++; } } const unsigned MIN_TICKS1 = 1000 / core::MAXFPS; const unsigned MIN_TICKS = MIN_TICKS1 > 0 ? MIN_TICKS1 : 1; core::init_path(data_dir); core::init(); { bool do_quit = false; unsigned last_frame = SDL_GetTicks(); game::state gstate(edit_mode); gstate.set_level(start_level); while (!do_quit) { SDL_Event e; while (SDL_PollEvent(&e)) { switch (e.common.type) { case SDL_QUIT: do_quit = true; break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: gstate.mouse_click( e.button.x / core::SCALE, (core::IHEIGHT - 1 - e.button.y) / core::SCALE, e.common.type == SDL_MOUSEBUTTONDOWN ? e.button.button : -1); break; case SDL_MOUSEMOTION: gstate.mouse_move( e.motion.x / core::SCALE, (core::IHEIGHT - 1 - e.motion.y) / core::SCALE); break; case SDL_KEYDOWN: case SDL_KEYUP: key k; if (decode_key(e.key.keysym.scancode, &k)) gstate.event_key(k, e.common.type == SDL_KEYDOWN); break; } } gstate.draw(SDL_GetTicks()); core::swap_window(); unsigned now = SDL_GetTicks(); unsigned delta = now - last_frame; if (delta < MIN_TICKS) { SDL_Delay(MIN_TICKS - delta); now = SDL_GetTicks(); } last_frame = now; } } core::term(); return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <cstdlib> #include <vector> #include <string> //getlogin() and gethostname(). #include <unistd.h> //perror. #include <stdio.h> //fork,wait and execvp. #include <sys/types.h> #include <sys/wait.h> //boost! #include "boost/algorithm/string.hpp" #include "boost/tokenizer.hpp" #include "boost/foreach.hpp" //that one class. #include "Command.h" using namespace std; using namespace boost; //execute command. void execute(const vector<string> & s); //replaces char in string. void replace_char(string &s, char o, char r); //takes a string and returns vector of parsed string. vector<string> parseInput(string s); //display vector. template<typename unit> void display_vector(vector<unit> v); //helper function that finds amount of character. int find_char_amount(const string s,char c); //removes comment from input. void remove_comment(string &s); int main() { //grab the login. char* login = getlogin(); //start a flag. bool login_check = true; if((!login) != 0) { //check flag. login_check = false; //output error. perror("Error: could not retrieve login name"); } //hold c-string for host name. char host[150]; //start another flag. bool host_check = true; //gets hostname while checking if it actually grabbed it. if(gethostname(host,sizeof(host)) != 0) { //check flag. host_check = false; //output error. perror("Error: could not rerieve host name."); } //warn user of upcoming trouble. if(login_check == false || host_check == false) cout << "Unable to display login and/or host information." << endl; //string to hold user input. string input; while(true) { //output login@hostname. if(login_check && host_check) cout << login << '@' << host << ' '; //bash money. cout << "$ "; //placeholder to tell its the program. cout << " (program) "; //geting input as a string. getline(cin,input); //remove extra white space. trim(input); //remove comments. remove_comment(input); //trim again just in case. trim(input); //break. if(input == "exit") exit(0); //testing parse. cout << "Testing parse" << endl; display_vector(parseInput(input)); //execute command. //execute(input); } cout << "End of program" << endl; return 0; } void execute(const vector<string> &s) { //c-string to hold command. char* args[2048]; //place and convert commands. for(unsigned int i = 0; i < s.size(); ++i) args[i] = (char*)s.at(i).c_str(); args[s.size()] = NULL; pid_t pid = fork(); if(pid == -1) { //fork didn't work. perror("fork"); } if(pid ==0) { if(execvp(args[0], args) == -1) { //execute didn't work. perror("execvp"); //break out of shadow realm. exit(1); } } if(pid > 0) { //wait for child to die. if(wait(0) == -1) { //didnt wait. perror("wait"); } } return; } vector<string> parseInput(string s) { //replace spaces. replace_char(s,' ','_'); //make temp vector to hold parsed strings. vector<string> temp; //create boost magic function. //char_separator<char> sep(" ;||&(){}\"", ";||&()[]\"", keep_empty_tokens); //test copy char_separator<char> sep(" ;||&&(){}", ";||&&()[]",keep_empty_tokens); //create boost magic holder thingy. tokenizer< char_separator<char> > cm(s,sep); //for each loop to grab each peice and push it into a vector. for(tokenizer< char_separator<char> >::iterator it = cm.begin(); it != cm.end(); ++it) if(*it != "") temp.push_back(*it); //return that vector. return temp; } void replace_char(string &s, char o, char r) { if(s.find("\"") != string::npos) for(unsigned int i = s.find("\""); i < s.find("\"",s.find("\"")+1);++i) if(s.at(i) == o) s.at(i) = r; return; } template<typename unit> void display_vector(vector<unit> v) { for(unsigned int i = 0; i < v.size(); ++i) cout << i+1 << ": " << v.at(i) << endl; return; } void remove_comment(string &s) { //just add a " to the end to avoid errors. if(find_char_amount(s,'\"') %2 != 0) s += '\"'; //delete everything! if(s.find("#") == 0) { s = ""; return; } //return if no comments. if(s.find("#") == string::npos) { return; } //if no comments then delets everything from hash forward. if(s.find("\"") == string::npos && s.find("#") != string::npos) { s = s.substr(0,s.find("#")); return; } //if comment before quote then delete. if(s.find("\"") > s.find("#")) { s = s.substr(0,s.find("#")); return; } //advanced situations. //get a vector to hold positions of quotes and hash. vector<int> quotePos; vector<int> hashPos; //grab pos. for(unsigned int i = 0; i < s.size(); ++i) { if(s.at(i) == '\"') quotePos.push_back(i); else if(s.at(i) == '#') hashPos.push_back(i); } //hold pos for hash. int i = 0; //checks to see if in middle. bool check = true; //pos of lone hash. int pos = 0; for(unsigned int j = 0; j < quotePos.size() - 1; j += 2) { if(hashPos.at(i) > quotePos.at(j) && hashPos.at(i) < quotePos.at(j+1)) { check = true; ++i; } else { check = false; pos = hashPos.at(i); } } if(!check) { s = s.substr(0,pos); return; } if(hashPos.at(hashPos.size()-1) > quotePos.at(quotePos.size()-1)) s = s.substr(0,hashPos.at(hashPos.size()-1)); return; } int find_char_amount(const string s, char c) { if(s.find(c) == string::npos) return 0; int count = 0; for(unsigned int i = 0; i < s.size(); ++i) if(s.at(i) == c) count++; return count; } <commit_msg>Added switch function to parse<commit_after>#include <iostream> #include <cstdlib> #include <vector> #include <string> //getlogin() and gethostname(). #include <unistd.h> //perror. #include <stdio.h> //fork,wait and execvp. #include <sys/types.h> #include <sys/wait.h> //boost! #include "boost/algorithm/string.hpp" #include "boost/tokenizer.hpp" #include "boost/foreach.hpp" //that one class. #include "Command.h" using namespace std; using namespace boost; //execute command. void execute(const vector<string> & s); //replaces char in string. void replace_char(string &s, char o, char r); //takes a string and returns vector of parsed string. vector<string> parseInput(string s); //display vector. template<typename unit> void display_vector(vector<unit> v); //helper function that finds amount of character. int find_char_amount(const string s,char c); //removes comment from input. void remove_comment(string &s); int main() { //grab the login. char* login = getlogin(); //start a flag. bool login_check = true; if((!login) != 0) { //check flag. login_check = false; //output error. perror("Error: could not retrieve login name"); } //hold c-string for host name. char host[150]; //start another flag. bool host_check = true; //gets hostname while checking if it actually grabbed it. if(gethostname(host,sizeof(host)) != 0) { //check flag. host_check = false; //output error. perror("Error: could not rerieve host name."); } //warn user of upcoming trouble. if(login_check == false || host_check == false) cout << "Unable to display login and/or host information." << endl; //string to hold user input. string input; while(true) { //output login@hostname. if(login_check && host_check) cout << login << '@' << host << ' '; //bash money. cout << "$ "; //placeholder to tell its the program. cout << " (program) "; //geting input as a string. getline(cin,input); //remove extra white space. trim(input); //remove comments. remove_comment(input); //trim again just in case. trim(input); //break. if(input == "exit") exit(0); //testing parse. cout << "Testing parse" << endl; display_vector(parseInput(input)); //execute command. //execute(input); } cout << "End of program" << endl; return 0; } void execute(const vector<string> &s) { //c-string to hold command. char* args[2048]; //place and convert commands. for(unsigned int i = 0; i < s.size(); ++i) args[i] = (char*)s.at(i).c_str(); args[s.size()] = NULL; pid_t pid = fork(); if(pid == -1) { //fork didn't work. perror("fork"); } if(pid ==0) { if(execvp(args[0], args) == -1) { //execute didn't work. perror("execvp"); //break out of shadow realm. exit(1); } } if(pid > 0) { //wait for child to die. if(wait(0) == -1) { //didnt wait. perror("wait"); } } return; } vector<string> parseInput(string s) { //replace spaces. replace_char(s,' ','_'); //make temp vector to hold parsed strings. vector<string> temp; //create boost magic function. //char_separator<char> sep(" ;||&(){}\"", ";||&()[]\"", keep_empty_tokens); //test copy char_separator<char> sep(" ;||&&(){}", ";||&&()[]",keep_empty_tokens); //create boost magic holder thingy. tokenizer< char_separator<char> > cm(s,sep); //for each loop to grab each peice and push it into a vector. for(tokenizer< char_separator<char> >::iterator it = cm.begin(); it != cm.end(); ++it) if(*it != "") temp.push_back(*it); //return that vector. return temp; } void replace_char(string &s, char o, char r) { //no quotes. if(s.find("\"") == string::npos) return; //vector to hold quote positions. vector<int> pos; //place positions of char into vector. for(unsigned int i = 0; i < s.size(); ++i) if(s.at(i) == '\"') pos.push_back(i); //count position. unsigned int count = 0; //replace. while(count < pos.size()) { for(int i = pos.at(count); i < pos.at(count+1); ++i) if(s.at(i) == o) s.at(i) = r; count++; count++; } // if(s.find("\"") != string::npos) // for(unsigned int i = s.find("\""); i < s.find("\"",s.find("\"")+1);++i) // if(s.at(i) == o) // s.at(i) = r; return; } template<typename unit> void display_vector(vector<unit> v) { for(unsigned int i = 0; i < v.size(); ++i) cout << i+1 << ": " << v.at(i) << endl; return; } void remove_comment(string &s) { //just add a " to the end to avoid errors. if(find_char_amount(s,'\"') %2 != 0) s += '\"'; //delete everything! if(s.find("#") == 0) { s = ""; return; } //return if no comments. if(s.find("#") == string::npos) { return; } //if no comments then delets everything from hash forward. if(s.find("\"") == string::npos && s.find("#") != string::npos) { s = s.substr(0,s.find("#")); return; } //if comment before quote then delete. if(s.find("\"") > s.find("#")) { s = s.substr(0,s.find("#")); return; } //advanced situations. //get a vector to hold positions of quotes and hash. vector<int> quotePos; vector<int> hashPos; //grab pos. for(unsigned int i = 0; i < s.size(); ++i) { if(s.at(i) == '\"') quotePos.push_back(i); else if(s.at(i) == '#') hashPos.push_back(i); } //hold pos for hash. int i = 0; //checks to see if in middle. bool check = true; //pos of lone hash. int pos = 0; for(unsigned int j = 0; j < quotePos.size() - 1; j += 2) { if(hashPos.at(i) > quotePos.at(j) && hashPos.at(i) < quotePos.at(j+1)) { check = true; ++i; } else { check = false; pos = hashPos.at(i); } } if(!check) { s = s.substr(0,pos); return; } if(hashPos.at(hashPos.size()-1) > quotePos.at(quotePos.size()-1)) s = s.substr(0,hashPos.at(hashPos.size()-1)); return; } int find_char_amount(const string s, char c) { if(s.find(c) == string::npos) return 0; int count = 0; for(unsigned int i = 0; i < s.size(); ++i) if(s.at(i) == c) count++; return count; } <|endoftext|>
<commit_before>#include <stdio.h> #include <fcntl.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <assert.h> #include <unistd.h> #include <fstream> #include <iostream> #include <time.h> #include "bcm_host.h" #include "GLES2/gl2.h" #include "EGL/egl.h" #include "EGL/eglext.h" #include "shader.h" #include "inotify-cxx.h" typedef struct { uint32_t screen_width; uint32_t screen_height; // OpenGL|ES objects EGLDisplay display; EGLSurface surface; EGLContext context; GLuint buf; Shader shader; } CUBE_STATE_T; static CUBE_STATE_T _state, *state=&_state; #define check() assert(glGetError() == 0) static void init_ogl(CUBE_STATE_T *state){ int32_t success = 0; EGLBoolean result; EGLint num_config; static EGL_DISPMANX_WINDOW_T nativewindow; DISPMANX_ELEMENT_HANDLE_T dispman_element; DISPMANX_DISPLAY_HANDLE_T dispman_display; DISPMANX_UPDATE_HANDLE_T dispman_update; VC_RECT_T dst_rect; VC_RECT_T src_rect; static const EGLint attribute_list[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_NONE }; static const EGLint context_attributes[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; EGLConfig config; // get an EGL display connection state->display = eglGetDisplay(EGL_DEFAULT_DISPLAY); assert(state->display!=EGL_NO_DISPLAY); check(); // initialize the EGL display connection result = eglInitialize(state->display, NULL, NULL); assert(EGL_FALSE != result); check(); // get an appropriate EGL frame buffer configuration result = eglChooseConfig(state->display, attribute_list, &config, 1, &num_config); assert(EGL_FALSE != result); check(); // get an appropriate EGL frame buffer configuration result = eglBindAPI(EGL_OPENGL_ES_API); assert(EGL_FALSE != result); check(); // create an EGL rendering context state->context = eglCreateContext(state->display, config, EGL_NO_CONTEXT, context_attributes); assert(state->context!=EGL_NO_CONTEXT); check(); // create an EGL window surface success = graphics_get_display_size(0 /* LCD */, &state->screen_width, &state->screen_height); assert( success >= 0 ); dst_rect.x = 0; dst_rect.y = 0; dst_rect.width = state->screen_width; dst_rect.height = state->screen_height; src_rect.x = 0; src_rect.y = 0; src_rect.width = state->screen_width << 16; src_rect.height = state->screen_height << 16; dispman_display = vc_dispmanx_display_open( 0 /* LCD */); dispman_update = vc_dispmanx_update_start( 0 ); dispman_element = vc_dispmanx_element_add ( dispman_update, dispman_display, 0/*layer*/, &dst_rect, 0/*src*/, &src_rect, DISPMANX_PROTECTION_NONE, 0 /*alpha*/, 0/*clamp*/, 0/*transform*/); nativewindow.element = dispman_element; nativewindow.width = state->screen_width; nativewindow.height = state->screen_height; vc_dispmanx_update_submit_sync( dispman_update ); check(); state->surface = eglCreateWindowSurface( state->display, config, &nativewindow, NULL ); assert(state->surface != EGL_NO_SURFACE); check(); // connect the context to the surface result = eglMakeCurrent(state->display, state->surface, state->surface, state->context); assert(EGL_FALSE != result); check(); // Set background color and clear buffers glClearColor(0.15f, 0.25f, 0.35f, 1.0f); glClear( GL_COLOR_BUFFER_BIT ); check(); } static bool loadFromPath(const std::string& path, std::string* into) { std::ifstream file; std::string buffer; file.open(path.c_str()); if(!file.is_open()) return false; while(!file.eof()) { getline(file, buffer); (*into) += buffer + "\n"; } file.close(); return true; } static void draw(CUBE_STATE_T *state, GLfloat cx, GLfloat cy){ // Now render to the main frame buffer glBindFramebuffer(GL_FRAMEBUFFER,0); // Clear the background (not really necessary I suppose) glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); check(); glBindBuffer(GL_ARRAY_BUFFER, state->buf); check(); state->shader.use(); check(); state->shader.sendUniform("u_time",((float)clock())/CLOCKS_PER_SEC); state->shader.sendUniform("u_mouse",cx, cy); state->shader.sendUniform("u_resolution",state->screen_width, state->screen_height); check(); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); check(); glBindBuffer(GL_ARRAY_BUFFER, 0); glFlush(); glFinish(); check(); eglSwapBuffers(state->display, state->surface); check(); } static int get_mouse(CUBE_STATE_T *state, int *outx, int *outy){ static int fd = -1; const int width=state->screen_width, height=state->screen_height; static int x=800, y=400; const int XSIGN = 1<<4, YSIGN = 1<<5; if (fd<0) { fd = open("/dev/input/mouse0",O_RDONLY|O_NONBLOCK); } if (fd>=0) { struct {char buttons, dx, dy; } m; while (1) { int bytes = read(fd, &m, sizeof m); if (bytes < (int)sizeof m) goto _exit; if (m.buttons&8) { break; // This bit should always be set } read(fd, &m, 1); // Try to sync up again } if (m.buttons&3) return m.buttons&3; x+=m.dx; y+=m.dy; if (m.buttons&XSIGN) x-=256; if (m.buttons&YSIGN) y-=256; if (x<0) x=0; if (y<0) y=0; if (x>width) x=width; if (y>height) y=height; } _exit: if (outx) *outx = x; if (outy) *outy = y; return 0; } //============================================================================== int main(int argc, char **argv){ Inotify notify; InotifyWatch watch(std::string(argv[1]), IN_ALL_EVENTS); notify.Add(watch); for (;;) { notify.WaitForEvents(); size_t count = notify.GetEventCount(); while (count > 0) { InotifyEvent event; bool got_event = notify.GetEvent(&event); if (got_event) { std::string mask_str; event.DumpTypes(mask_str); std::string filename = event.GetName(); std::cout << "[watch " << std::string(argv[1]) << "] "; std::cout << "event mask: \"" << mask_str << "\", "; std::cout << "filename: \"" << filename << "\"" << std::endl; } count--; } } return 0; int terminate = 0; GLfloat cx, cy; bcm_host_init(); // Clear application state memset( state, 0, sizeof( *state ) ); // Start OGLES init_ogl(state); // init_shaders(state, std::string(argv[1]) ); // Build shader; // std::string fragSource; std::string vertSource = "attribute vec4 a_position;" "varying vec2 v_texcoord;" "void main(void) {" " gl_Position = a_position;" " v_texcoord = a_position.xy*0.5+0.5;" "}"; if(!loadFromPath(std::string(argv[1]), &fragSource)) { return; } state->shader.build(fragSource,vertSource); // Make Quad // static const GLfloat vertex_data[] = { -1.0,-1.0,1.0,1.0, 1.0,-1.0,1.0,1.0, 1.0,1.0,1.0,1.0, -1.0,1.0,1.0,1.0 }; GLint posAttribut = state->shader.getAttribLocation("a_position"); glClearColor ( 0.0, 1.0, 1.0, 1.0 ); glGenBuffers(1, &state->buf); check(); // Prepare viewport glViewport ( 0, 0, state->screen_width, state->screen_height ); check(); // Upload vertex data to a buffer glBindBuffer(GL_ARRAY_BUFFER, state->buf); glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW); glVertexAttribPointer(posAttribut, 4, GL_FLOAT, 0, 16, 0); glEnableVertexAttribArray(posAttribut); check(); while (!terminate){ int x, y, b; b = get_mouse(state, &x, &y); if (b) break; draw(state, x, y); } return 0; } <commit_msg>forking structure<commit_after>#include <stdio.h> #include <fcntl.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <assert.h> #include <unistd.h> #include <fstream> #include <iostream> #include <time.h> #include <unistd.h> #include "bcm_host.h" #include "GLES2/gl2.h" #include "EGL/egl.h" #include "EGL/eglext.h" #include "shader.h" #include "inotify-cxx.h" typedef struct { uint32_t screen_width; uint32_t screen_height; // OpenGL|ES objects EGLDisplay display; EGLSurface surface; EGLContext context; GLuint buf; Shader shader; } CUBE_STATE_T; static CUBE_STATE_T _state, *state=&_state; #define check() assert(glGetError() == 0) static void init_ogl(CUBE_STATE_T *state){ int32_t success = 0; EGLBoolean result; EGLint num_config; static EGL_DISPMANX_WINDOW_T nativewindow; DISPMANX_ELEMENT_HANDLE_T dispman_element; DISPMANX_DISPLAY_HANDLE_T dispman_display; DISPMANX_UPDATE_HANDLE_T dispman_update; VC_RECT_T dst_rect; VC_RECT_T src_rect; static const EGLint attribute_list[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_NONE }; static const EGLint context_attributes[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; EGLConfig config; // get an EGL display connection state->display = eglGetDisplay(EGL_DEFAULT_DISPLAY); assert(state->display!=EGL_NO_DISPLAY); check(); // initialize the EGL display connection result = eglInitialize(state->display, NULL, NULL); assert(EGL_FALSE != result); check(); // get an appropriate EGL frame buffer configuration result = eglChooseConfig(state->display, attribute_list, &config, 1, &num_config); assert(EGL_FALSE != result); check(); // get an appropriate EGL frame buffer configuration result = eglBindAPI(EGL_OPENGL_ES_API); assert(EGL_FALSE != result); check(); // create an EGL rendering context state->context = eglCreateContext(state->display, config, EGL_NO_CONTEXT, context_attributes); assert(state->context!=EGL_NO_CONTEXT); check(); // create an EGL window surface success = graphics_get_display_size(0 /* LCD */, &state->screen_width, &state->screen_height); assert( success >= 0 ); dst_rect.x = 0; dst_rect.y = 0; dst_rect.width = state->screen_width; dst_rect.height = state->screen_height; src_rect.x = 0; src_rect.y = 0; src_rect.width = state->screen_width << 16; src_rect.height = state->screen_height << 16; dispman_display = vc_dispmanx_display_open( 0 /* LCD */); dispman_update = vc_dispmanx_update_start( 0 ); dispman_element = vc_dispmanx_element_add ( dispman_update, dispman_display, 0/*layer*/, &dst_rect, 0/*src*/, &src_rect, DISPMANX_PROTECTION_NONE, 0 /*alpha*/, 0/*clamp*/, 0/*transform*/); nativewindow.element = dispman_element; nativewindow.width = state->screen_width; nativewindow.height = state->screen_height; vc_dispmanx_update_submit_sync( dispman_update ); check(); state->surface = eglCreateWindowSurface( state->display, config, &nativewindow, NULL ); assert(state->surface != EGL_NO_SURFACE); check(); // connect the context to the surface result = eglMakeCurrent(state->display, state->surface, state->surface, state->context); assert(EGL_FALSE != result); check(); // Set background color and clear buffers glClearColor(0.15f, 0.25f, 0.35f, 1.0f); glClear( GL_COLOR_BUFFER_BIT ); check(); } static bool loadFromPath(const std::string& path, std::string* into) { std::ifstream file; std::string buffer; file.open(path.c_str()); if(!file.is_open()) return false; while(!file.eof()) { getline(file, buffer); (*into) += buffer + "\n"; } file.close(); return true; } static void draw(CUBE_STATE_T *state, GLfloat cx, GLfloat cy){ // Now render to the main frame buffer glBindFramebuffer(GL_FRAMEBUFFER,0); // Clear the background (not really necessary I suppose) glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); check(); glBindBuffer(GL_ARRAY_BUFFER, state->buf); check(); state->shader.use(); check(); state->shader.sendUniform("u_time",((float)clock())/CLOCKS_PER_SEC); state->shader.sendUniform("u_mouse",cx, cy); state->shader.sendUniform("u_resolution",state->screen_width, state->screen_height); check(); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); check(); glBindBuffer(GL_ARRAY_BUFFER, 0); glFlush(); glFinish(); check(); eglSwapBuffers(state->display, state->surface); check(); } static int get_mouse(CUBE_STATE_T *state, int *outx, int *outy){ static int fd = -1; const int width=state->screen_width, height=state->screen_height; static int x=800, y=400; const int XSIGN = 1<<4, YSIGN = 1<<5; if (fd<0) { fd = open("/dev/input/mouse0",O_RDONLY|O_NONBLOCK); } if (fd>=0) { struct {char buttons, dx, dy; } m; while (1) { int bytes = read(fd, &m, sizeof m); if (bytes < (int)sizeof m) goto _exit; if (m.buttons&8) { break; // This bit should always be set } read(fd, &m, 1); // Try to sync up again } if (m.buttons&3) return m.buttons&3; x+=m.dx; y+=m.dy; if (m.buttons&XSIGN) x-=256; if (m.buttons&YSIGN) y-=256; if (x<0) x=0; if (y<0) y=0; if (x>width) x=width; if (y>height) y=height; } _exit: if (outx) *outx = x; if (outy) *outy = y; return 0; } void drawThread() { while (!terminate){ int x, y, b; b = get_mouse(state, &x, &y); if (b) break; draw(state, x, y); } } void watchThread(const std::string& file) { Inotify notify; InotifyWatch watch(file, IN_MODIFY); notify.Add(watch); for (;;) { notify.WaitForEvents(); size_t count = notify.GetEventCount(); while (count > 0) { InotifyEvent event; bool got_event = notify.GetEvent(&event); if (got_event) { std::string mask_str; event.DumpTypes(mask_str); std::string filename = event.GetName(); std::cout << "[watch " << file << "] "; std::cout << "event mask: \"" << mask_str << "\", "; std::cout << "filename: \"" << filename << "\"" << endl; } count--; } } } void init(const std::string& fragFile) { int terminate = 0; GLfloat cx, cy; bcm_host_init(); // Clear application state memset( state, 0, sizeof( *state ) ); // Start OGLES init_ogl(state); // Build shader; // std::string fragSource; std::string vertSource = "attribute vec4 a_position;" "varying vec2 v_texcoord;" "void main(void) {" " gl_Position = a_position;" " v_texcoord = a_position.xy*0.5+0.5;" "}"; if(!loadFromPath(fragFile, &fragSource)) { return; } state->shader.build(fragSource,vertSource); // Make Quad // static const GLfloat vertex_data[] = { -1.0,-1.0,1.0,1.0, 1.0,-1.0,1.0,1.0, 1.0,1.0,1.0,1.0, -1.0,1.0,1.0,1.0 }; GLint posAttribut = state->shader.getAttribLocation("a_position"); glClearColor ( 0.0, 1.0, 1.0, 1.0 ); glGenBuffers(1, &state->buf); check(); // Prepare viewport glViewport ( 0, 0, state->screen_width, state->screen_height ); check(); // Upload vertex data to a buffer glBindBuffer(GL_ARRAY_BUFFER, state->buf); glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW); glVertexAttribPointer(posAttribut, 4, GL_FLOAT, 0, 16, 0); glEnableVertexAttribArray(posAttribut); check(); } //============================================================================== int main(int argc, char **argv){ std::string fragFile(argv[1]); pid_t pid = fork(); switch(pid) { case -1: //error break; case 0: // child { watchThread(fragFile); } break; default: { init(fragFile); drawThread(); } break; } return 0; } <|endoftext|>
<commit_before>/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** main.cpp ** ** V4L2 RTSP streamer ** ** H264 capture using V4L2 ** RTSP using live555 ** ** -------------------------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <signal.h> #include <sys/ioctl.h> #include <sstream> // libv4l2 #include <linux/videodev2.h> #include <libv4l2.h> // live555 #include <BasicUsageEnvironment.hh> #include <GroupsockHelper.hh> // project #include "logger.h" #include "V4l2Device.h" #include "V4l2Capture.h" #include "V4l2Output.h" #include "H264_V4l2DeviceSource.h" #include "ServerMediaSubsession.h" // ----------------------------------------- // signal handler // ----------------------------------------- char quit = 0; void sighandler(int n) { printf("SIGINT\n"); quit =1; } // ----------------------------------------- // add an RTSP session // ----------------------------------------- void addSession(RTSPServer* rtspServer, const std::string & sessionName, ServerMediaSubsession *subSession) { UsageEnvironment& env(rtspServer->envir()); ServerMediaSession* sms = ServerMediaSession::createNew(env, sessionName.c_str()); if (sms != NULL) { sms->addSubsession(subSession); rtspServer->addServerMediaSession(sms); char* url = rtspServer->rtspURL(sms); if (url != NULL) { LOG(NOTICE) << "Play this stream using the URL \"" << url << "\""; delete[] url; } } } // ----------------------------------------- // entry point // ----------------------------------------- int main(int argc, char** argv) { // default parameters const char *dev_name = "/dev/video0"; int format = V4L2_PIX_FMT_H264; int width = 640; int height = 480; int queueSize = 10; int fps = 25; unsigned short rtspPort = 8554; unsigned short rtspOverHTTPPort = 0; bool multicast = false; int verbose = 0; std::string outputFile; bool useMmap = true; std::string url = "unicast"; std::string murl = "multicast"; bool useThread = true; std::string maddr; bool repeatConfig = true; int timeout = 65; // decode parameters int c = 0; while ((c = getopt (argc, argv, "v::Q:O:" "I:P:T:m:u:M:ct:" "rsF:W:H:" "h")) != -1) { switch (c) { case 'v': verbose = 1; if (optarg && *optarg=='v') verbose++; break; case 'Q': queueSize = atoi(optarg); break; case 'O': outputFile = optarg; break; // RTSP/RTP case 'I': ReceivingInterfaceAddr = inet_addr(optarg); break; case 'P': rtspPort = atoi(optarg); break; case 'T': rtspOverHTTPPort = atoi(optarg); break; case 'u': url = optarg; break; case 'm': multicast = true; murl = optarg; break; case 'M': multicast = true; maddr = optarg; break; case 'c': repeatConfig = false; break; case 't': timeout = atoi(optarg); break; // V4L2 case 'r': useMmap = false; break; case 's': useThread = false; break; case 'F': fps = atoi(optarg); break; case 'W': width = atoi(optarg); break; case 'H': height = atoi(optarg); break; case 'h': default: { std::cout << argv[0] << " [-v[v]][-m] [-P RTSP port][-P RTSP/HTTP port][-Q queueSize] [-M] [-t] [-W width] [-H height] [-F fps] [-O file] [device]" << std::endl; std::cout << "\t -v : verbose" << std::endl; std::cout << "\t -vv : very verbose" << std::endl; std::cout << "\t -Q length: Number of frame queue (default "<< queueSize << ")" << std::endl; std::cout << "\t -O output: Copy captured frame to a file or a V4L2 device" << std::endl; std::cout << "\t RTSP options :" << std::endl; std::cout << "\t -I addr : RTSP interface (default autodetect)" << std::endl; std::cout << "\t -P port : RTSP port (default "<< rtspPort << ")" << std::endl; std::cout << "\t -T port : RTSP over HTTP port (default "<< rtspOverHTTPPort << ")" << std::endl; std::cout << "\t -u url : unicast url (default " << url << ")" << std::endl; std::cout << "\t -m url : multicast url (default " << murl << ")" << std::endl; std::cout << "\t -M addr : multicast group (default is a random address)" << std::endl; std::cout << "\t -c : don't repeat config (default repeat config before IDR frame)" << std::endl; std::cout << "\t -t secs : RTCP expiration timeout (default " << timeout << ")" << std::endl; std::cout << "\t V4L2 options :" << std::endl; std::cout << "\t -r : V4L2 capture using read interface (default use memory mapped buffers)" << std::endl; std::cout << "\t -s : V4L2 capture using live555 mainloop (default use a reader thread)" << std::endl; std::cout << "\t -F fps : V4L2 capture framerate (default "<< fps << ")" << std::endl; std::cout << "\t -W width : V4L2 capture width (default "<< width << ")" << std::endl; std::cout << "\t -H height: V4L2 capture height (default "<< height << ")" << std::endl; std::cout << "\t device : V4L2 capture device (default "<< dev_name << ")" << std::endl; exit(0); } } } std::list<std::string> devList; while (optind<argc) { devList.push_back(argv[optind]); optind++; } if (devList.empty()) { devList.push_back(dev_name); } // split multicast info std::istringstream is(maddr); std::string ip; getline(is, ip, ':'); std::string port; getline(is, port, ':'); unsigned short rtpPortNum = 20000; if (!port.empty()) { rtpPortNum = atoi(port.c_str()); } unsigned short rtcpPortNum = rtpPortNum+1; unsigned char ttl = 5; // init logger initLogger(verbose); // create live555 environment TaskScheduler* scheduler = BasicTaskScheduler::createNew(); UsageEnvironment* env = BasicUsageEnvironment::createNew(*scheduler); // create RTSP server UserAuthenticationDatabase* authDB = NULL; RTSPServer* rtspServer = RTSPServer::createNew(*env, rtspPort, authDB, timeout); if (rtspServer == NULL) { LOG(ERROR) << "Failed to create RTSP server: " << env->getResultMsg(); } else { // set http tunneling if (rtspOverHTTPPort) { rtspServer->setUpTunnelingOverHTTP(rtspOverHTTPPort); } std::list<std::string>::iterator devIt; for ( devIt=devList.begin() ; devIt!=devList.end() ; ++devIt) { std::string deviceName(*devIt); // Init capture LOG(NOTICE) << "Create V4L2 Source..." << deviceName; V4L2DeviceParameters param(deviceName.c_str(),format,width,height,fps, verbose); V4l2Capture* videoCapture = V4l2DeviceFactory::CreateVideoCapure(param, useMmap); if (videoCapture) { V4L2DeviceParameters outparam(outputFile.c_str(), videoCapture->getFormat(), videoCapture->getWidth(), videoCapture->getHeight(), 0,verbose); V4l2Output out(outparam); LOG(NOTICE) << "Start V4L2 Capture..." << deviceName; videoCapture->captureStart(); V4L2DeviceSource* videoES = H264_V4L2DeviceSource::createNew(*env, param, videoCapture, out.getFd(), queueSize, useThread, repeatConfig); if (videoES == NULL) { LOG(FATAL) << "Unable to create source for device " << deviceName; delete videoCapture; } else { // extend buffer size if needed if (videoCapture->getBufferSize() > OutPacketBuffer::maxSize) { OutPacketBuffer::maxSize = videoCapture->getBufferSize(); } StreamReplicator* replicator = StreamReplicator::createNew(*env, videoES, false); std::string baseUrl; if (devList.size() > 1) { baseUrl = basename(deviceName.c_str()); baseUrl.append("/"); } // Create Multicast Session if (multicast) { struct in_addr destinationAddress; destinationAddress.s_addr = chooseRandomIPv4SSMAddress(*env); if (!ip.empty()) { destinationAddress.s_addr = inet_addr(ip.c_str()); } LOG(NOTICE) << "RTP address " << inet_ntoa(destinationAddress) << ":" << rtpPortNum; LOG(NOTICE) << "RTCP address " << inet_ntoa(destinationAddress) << ":" << rtcpPortNum; addSession(rtspServer, baseUrl+murl, MulticastServerMediaSubsession::createNew(*env,destinationAddress, Port(rtpPortNum), Port(rtcpPortNum), ttl, replicator,format)); if (!ip.empty()) { rtpPortNum++; rtcpPortNum++; } } // Create Unicast Session addSession(rtspServer, baseUrl+url, UnicastServerMediaSubsession::createNew(*env,replicator,format)); } } } // main loop signal(SIGINT,sighandler); env->taskScheduler().doEventLoop(&quit); LOG(NOTICE) << "Exiting...."; Medium::close(rtspServer); } env->reclaim(); delete scheduler; return 0; } <commit_msg>always increment mulicast port<commit_after>/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** main.cpp ** ** V4L2 RTSP streamer ** ** H264 capture using V4L2 ** RTSP using live555 ** ** -------------------------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <signal.h> #include <sys/ioctl.h> #include <sstream> // libv4l2 #include <linux/videodev2.h> #include <libv4l2.h> // live555 #include <BasicUsageEnvironment.hh> #include <GroupsockHelper.hh> // project #include "logger.h" #include "V4l2Device.h" #include "V4l2Capture.h" #include "V4l2Output.h" #include "H264_V4l2DeviceSource.h" #include "ServerMediaSubsession.h" // ----------------------------------------- // signal handler // ----------------------------------------- char quit = 0; void sighandler(int n) { printf("SIGINT\n"); quit =1; } // ----------------------------------------- // add an RTSP session // ----------------------------------------- void addSession(RTSPServer* rtspServer, const std::string & sessionName, ServerMediaSubsession *subSession) { UsageEnvironment& env(rtspServer->envir()); ServerMediaSession* sms = ServerMediaSession::createNew(env, sessionName.c_str()); if (sms != NULL) { sms->addSubsession(subSession); rtspServer->addServerMediaSession(sms); char* url = rtspServer->rtspURL(sms); if (url != NULL) { LOG(NOTICE) << "Play this stream using the URL \"" << url << "\""; delete[] url; } } } // ----------------------------------------- // entry point // ----------------------------------------- int main(int argc, char** argv) { // default parameters const char *dev_name = "/dev/video0"; int format = V4L2_PIX_FMT_H264; int width = 640; int height = 480; int queueSize = 10; int fps = 25; unsigned short rtspPort = 8554; unsigned short rtspOverHTTPPort = 0; bool multicast = false; int verbose = 0; std::string outputFile; bool useMmap = true; std::string url = "unicast"; std::string murl = "multicast"; bool useThread = true; std::string maddr; bool repeatConfig = true; int timeout = 65; // decode parameters int c = 0; while ((c = getopt (argc, argv, "v::Q:O:" "I:P:T:m:u:M:ct:" "rsF:W:H:" "h")) != -1) { switch (c) { case 'v': verbose = 1; if (optarg && *optarg=='v') verbose++; break; case 'Q': queueSize = atoi(optarg); break; case 'O': outputFile = optarg; break; // RTSP/RTP case 'I': ReceivingInterfaceAddr = inet_addr(optarg); break; case 'P': rtspPort = atoi(optarg); break; case 'T': rtspOverHTTPPort = atoi(optarg); break; case 'u': url = optarg; break; case 'm': multicast = true; murl = optarg; break; case 'M': multicast = true; maddr = optarg; break; case 'c': repeatConfig = false; break; case 't': timeout = atoi(optarg); break; // V4L2 case 'r': useMmap = false; break; case 's': useThread = false; break; case 'F': fps = atoi(optarg); break; case 'W': width = atoi(optarg); break; case 'H': height = atoi(optarg); break; case 'h': default: { std::cout << argv[0] << " [-v[v]][-m] [-P RTSP port][-P RTSP/HTTP port][-Q queueSize] [-M] [-t] [-W width] [-H height] [-F fps] [-O file] [device]" << std::endl; std::cout << "\t -v : verbose" << std::endl; std::cout << "\t -vv : very verbose" << std::endl; std::cout << "\t -Q length: Number of frame queue (default "<< queueSize << ")" << std::endl; std::cout << "\t -O output: Copy captured frame to a file or a V4L2 device" << std::endl; std::cout << "\t RTSP options :" << std::endl; std::cout << "\t -I addr : RTSP interface (default autodetect)" << std::endl; std::cout << "\t -P port : RTSP port (default "<< rtspPort << ")" << std::endl; std::cout << "\t -T port : RTSP over HTTP port (default "<< rtspOverHTTPPort << ")" << std::endl; std::cout << "\t -u url : unicast url (default " << url << ")" << std::endl; std::cout << "\t -m url : multicast url (default " << murl << ")" << std::endl; std::cout << "\t -M addr : multicast group:port (default is random_address:20000)" << std::endl; std::cout << "\t -c : don't repeat config (default repeat config before IDR frame)" << std::endl; std::cout << "\t -t secs : RTCP expiration timeout (default " << timeout << ")" << std::endl; std::cout << "\t V4L2 options :" << std::endl; std::cout << "\t -r : V4L2 capture using read interface (default use memory mapped buffers)" << std::endl; std::cout << "\t -s : V4L2 capture using live555 mainloop (default use a reader thread)" << std::endl; std::cout << "\t -F fps : V4L2 capture framerate (default "<< fps << ")" << std::endl; std::cout << "\t -W width : V4L2 capture width (default "<< width << ")" << std::endl; std::cout << "\t -H height: V4L2 capture height (default "<< height << ")" << std::endl; std::cout << "\t device : V4L2 capture device (default "<< dev_name << ")" << std::endl; exit(0); } } } std::list<std::string> devList; while (optind<argc) { devList.push_back(argv[optind]); optind++; } if (devList.empty()) { devList.push_back(dev_name); } // init logger initLogger(verbose); // create live555 environment TaskScheduler* scheduler = BasicTaskScheduler::createNew(); UsageEnvironment* env = BasicUsageEnvironment::createNew(*scheduler); // split multicast info std::istringstream is(maddr); std::string ip; getline(is, ip, ':'); struct in_addr destinationAddress; destinationAddress.s_addr = chooseRandomIPv4SSMAddress(*env); if (!ip.empty()) { destinationAddress.s_addr = inet_addr(ip.c_str()); } std::string port; getline(is, port, ':'); unsigned short rtpPortNum = 20000; if (!port.empty()) { rtpPortNum = atoi(port.c_str()); } unsigned short rtcpPortNum = rtpPortNum+1; unsigned char ttl = 5; // create RTSP server UserAuthenticationDatabase* authDB = NULL; RTSPServer* rtspServer = RTSPServer::createNew(*env, rtspPort, authDB, timeout); if (rtspServer == NULL) { LOG(ERROR) << "Failed to create RTSP server: " << env->getResultMsg(); } else { // set http tunneling if (rtspOverHTTPPort) { rtspServer->setUpTunnelingOverHTTP(rtspOverHTTPPort); } std::list<std::string>::iterator devIt; for ( devIt=devList.begin() ; devIt!=devList.end() ; ++devIt) { std::string deviceName(*devIt); // Init capture LOG(NOTICE) << "Create V4L2 Source..." << deviceName; V4L2DeviceParameters param(deviceName.c_str(),format,width,height,fps, verbose); V4l2Capture* videoCapture = V4l2DeviceFactory::CreateVideoCapure(param, useMmap); if (videoCapture) { V4L2DeviceParameters outparam(outputFile.c_str(), videoCapture->getFormat(), videoCapture->getWidth(), videoCapture->getHeight(), 0,verbose); V4l2Output out(outparam); LOG(NOTICE) << "Start V4L2 Capture..." << deviceName; videoCapture->captureStart(); V4L2DeviceSource* videoES = H264_V4L2DeviceSource::createNew(*env, param, videoCapture, out.getFd(), queueSize, useThread, repeatConfig); if (videoES == NULL) { LOG(FATAL) << "Unable to create source for device " << deviceName; delete videoCapture; } else { // extend buffer size if needed if (videoCapture->getBufferSize() > OutPacketBuffer::maxSize) { OutPacketBuffer::maxSize = videoCapture->getBufferSize(); } StreamReplicator* replicator = StreamReplicator::createNew(*env, videoES, false); std::string baseUrl; if (devList.size() > 1) { baseUrl = basename(deviceName.c_str()); baseUrl.append("/"); } // Create Multicast Session if (multicast) { LOG(NOTICE) << "RTP address " << inet_ntoa(destinationAddress) << ":" << rtpPortNum; LOG(NOTICE) << "RTCP address " << inet_ntoa(destinationAddress) << ":" << rtcpPortNum; addSession(rtspServer, baseUrl+murl, MulticastServerMediaSubsession::createNew(*env,destinationAddress, Port(rtpPortNum), Port(rtcpPortNum), ttl, replicator,format)); // increment ports for next sessions rtpPortNum+=2; rtcpPortNum+=2; } // Create Unicast Session addSession(rtspServer, baseUrl+url, UnicastServerMediaSubsession::createNew(*env,replicator,format)); } } } // main loop signal(SIGINT,sighandler); env->taskScheduler().doEventLoop(&quit); LOG(NOTICE) << "Exiting...."; Medium::close(rtspServer); } env->reclaim(); delete scheduler; return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include <pugixml.hpp> using namespace std; namespace xml = pugi; const string str_xml = "<html>" "<body>" "</body>" "</html>" ; int main(void) { xml::xml_document doc; doc.load(str_xml.c_str()); cout << doc.child("body") << '\n'; return 0; } <commit_msg>Updates sample code.<commit_after>#include <iostream> #include <sstream> #include <pugixml.hpp> using namespace std; namespace xml = pugi; const string str_xml = "<html>" "<body>" "<p>Hello world</p>" "</body>" "</html>" ; int main(void) { xml::xml_document doc; doc.load(str_xml.c_str()); cout << doc.child("html").child("body").child("p").first_child() .value() << '\n'; return 0; } <|endoftext|>
<commit_before>// Copyright (c) Burator 2014-2015 #include <QDir> #include <QFile> #include <QImage> #include <QDebug> #include <QString> #include <QFileInfo> #include <QByteArray> #include <QStringList> #include <QCoreApplication> #include <QCommandLineParser> #include "Util.h" #include "Types.h" #include "Global.h" #include "Version.h" #include "FaceDetector.h" B_USE_NAMESPACE // Show console output. static const bool showOutput = true; // Show debug/info output. static const bool showDebug = true; void msgHandler(QtMsgType type, const QMessageLogContext &ctx, const QString &msg); int main(int argc, char **argv) { QCoreApplication app(argc, argv); QCoreApplication::setApplicationName("Blurator"); QCoreApplication::setApplicationVersion(versionString()); qInstallMessageHandler(msgHandler); QCommandLineParser parser; parser.setApplicationDescription("Blur license plates and faces."); parser.addHelpOption(); parser.addVersionOption(); parser.addPositionalArgument("paths", "Paths to images or folders.", "paths.."); // Face detection option QCommandLineOption detectFaces(QStringList() << "f" << "faces", "Detect faces."); parser.addOption(detectFaces); // License plate detection option QCommandLineOption detectPlates(QStringList() << "p" << "plates", "Detect license plates."); parser.addOption(detectPlates); // Reply "yes" to everything option QCommandLineOption replyYes(QStringList() << "y" << "yes", "Automatically reply \"yes\" to all questions."); parser.addOption(replyYes); // Reply "no" to everything option QCommandLineOption replyNo(QStringList() << "n" << "no", "Automatically reply \"no\" to all questions."); parser.addOption(replyNo); // No-backup file option QCommandLineOption noBackupFile(QStringList() << "no-backup", "Don't store a backup of the original image."); parser.addOption(noBackupFile); parser.process(app); const QStringList args = parser.positionalArguments(); // Check optional command line options bool dFaces = parser.isSet(detectFaces); bool dPlates = parser.isSet(detectPlates); bool rYes = parser.isSet(replyYes); bool rNo = parser.isSet(replyNo); bool noBackup = parser.isSet(noBackupFile); // Ensure the arguments are passed. if (args.isEmpty()) { qCritical() << "Must provide paths to images!"; return -1; } if (!dPlates && !dFaces) { qCritical() << "Must choose to detect plates and/or faces!"; return -1; } if (rYes && rNo) { qCritical() << "Can't both say yes and no to everything!"; return -1; } // If non-null then the boolean value means reply "yes" for true and // "no" for false. BoolPtr autoReplyYes(nullptr); if (rYes || rNo) { autoReplyYes.reset(new bool); *autoReplyYes = rYes; } // Find all images from the arguments. From folders we only take the // top-level images. QStringList images; foreach (const QString &path, args) { QFileInfo fi(path); if (!fi.exists()) { qCritical() << "File does not exist:" << path; return -1; } if (fi.isFile() && Util::isSupportedImage(path)) { images << path; } else if (fi.isDir()) { QDir dir(path); QStringList files = dir.entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::Readable); foreach (const QString &file, files) { if (Util::isSupportedImage(file)) { images << dir.absoluteFilePath(file); } } } } if (images.isEmpty()) { qCritical() << "Found no supported, existing images to process!"; return -1; } qDebug() << "Found" << images.size() << images; if (noBackup) { qWarning() << "Warning no backup files will be created!"; } foreach (const QString &path, images) { qDebug() << "Processing" << path; if (dFaces) { QFile f(path); if (!f.open(QIODevice::ReadOnly)) { qCritical() << "Could not read from image file!"; return -1; } QByteArray imageData = f.readAll(); f.close(); MatPtr image = Util::imageToMat(imageData); if (image == nullptr) { qCritical() << "Invalid image!"; return -1; } FaceDetector detector; if (!detector.isValid()) { qCritical() << "Could not setup facial detector."; return -1; } QList<FacePtr> faces = detector.detect(image); if (faces.isEmpty()) { qDebug() << "Did not find any faces!"; continue; } qDebug() << "Found" << faces.size() << "face(s)."; qDebug() << faces; // Render face overlays to an image file to visualize the result. if (!faces.isEmpty()) { QImage overlay = QImage::fromData(imageData); Util::drawFaces(overlay, faces); // Save original to backup file. if (!noBackup) { QString bpath = Util::getBackupPath(path); if (QFile::copy(path, bpath)) { qDebug() << "Saved backup to" << bpath; } else { qWarning() << "Could not save backup to" << bpath; if (!Util::askProceed("Do you want to proceed?", autoReplyYes.get())) { qWarning() << "Aborting.."; return -1; } } } if (overlay.save(path)) { qDebug() << "Saved face overlays to" << path; } else { qCritical() << "Could not save overlays"; } } } // TODO: Plate detection if (dPlates) { qCritical() << "Plate detection not implemented yet!"; return -1; } } return 0; } void msgHandler(QtMsgType type, const QMessageLogContext &ctx, const QString &msg) { if (!showOutput) return; QTextStream stream(stdout); switch (type) { case QtDebugMsg: if (showDebug) { if (QString(msg) == "") { stream << endl; return; } stream << "(I) " << msg << endl; } break; case QtWarningMsg: stream << "(W) " << msg << endl; break; case QtCriticalMsg: stream << "(E) " << msg << endl; break; case QtFatalMsg: stream << "(F) " << msg << endl; abort(); } } <commit_msg>Fixed #13: Folders are ignored and only files are accepted.<commit_after>// Copyright (c) Burator 2014-2015 #include <QDir> #include <QFile> #include <QImage> #include <QDebug> #include <QString> #include <QFileInfo> #include <QByteArray> #include <QStringList> #include <QCoreApplication> #include <QCommandLineParser> #include "Util.h" #include "Types.h" #include "Global.h" #include "Version.h" #include "FaceDetector.h" B_USE_NAMESPACE // Show console output. static const bool showOutput = true; // Show debug/info output. static const bool showDebug = true; void msgHandler(QtMsgType type, const QMessageLogContext &ctx, const QString &msg); int main(int argc, char **argv) { QCoreApplication app(argc, argv); QCoreApplication::setApplicationName("Blurator"); QCoreApplication::setApplicationVersion(versionString()); qInstallMessageHandler(msgHandler); QCommandLineParser parser; parser.setApplicationDescription("Blur license plates and faces."); parser.addHelpOption(); parser.addVersionOption(); parser.addPositionalArgument("paths", "Paths to images.", "paths.."); // Face detection option QCommandLineOption detectFaces(QStringList() << "f" << "faces", "Detect faces."); parser.addOption(detectFaces); // License plate detection option QCommandLineOption detectPlates(QStringList() << "p" << "plates", "Detect license plates."); parser.addOption(detectPlates); // Reply "yes" to everything option QCommandLineOption replyYes(QStringList() << "y" << "yes", "Automatically reply \"yes\" to all questions."); parser.addOption(replyYes); // Reply "no" to everything option QCommandLineOption replyNo(QStringList() << "n" << "no", "Automatically reply \"no\" to all questions."); parser.addOption(replyNo); // No-backup file option QCommandLineOption noBackupFile(QStringList() << "no-backup", "Don't store a backup of the original image."); parser.addOption(noBackupFile); parser.process(app); const QStringList args = parser.positionalArguments(); // Check optional command line options bool dFaces = parser.isSet(detectFaces); bool dPlates = parser.isSet(detectPlates); bool rYes = parser.isSet(replyYes); bool rNo = parser.isSet(replyNo); bool noBackup = parser.isSet(noBackupFile); // Ensure the arguments are passed. if (args.isEmpty()) { qCritical() << "Must provide paths to images!"; return -1; } if (!dPlates && !dFaces) { qCritical() << "Must choose to detect plates and/or faces!"; return -1; } if (rYes && rNo) { qCritical() << "Can't both say yes and no to everything!"; return -1; } // If non-null then the boolean value means reply "yes" for true and // "no" for false. BoolPtr autoReplyYes(nullptr); if (rYes || rNo) { autoReplyYes.reset(new bool); *autoReplyYes = rYes; } // Find all images from the arguments. QStringList images; foreach (const QString &path, args) { QFileInfo fi(path); if (!fi.exists()) { qWarning() << "Ignoring nonexistent file" << path; continue; } if (fi.isFile() && Util::isSupportedImage(path)) { images << path; } else if (fi.isDir()) { qWarning() << "Ignoring folder" << path; } } if (images.isEmpty()) { qCritical() << "Found no supported images to process!"; return -1; } qDebug() << images.size() << "image files to process.."; if (noBackup) { qWarning() << "Warning no backup files will be created!"; } foreach (const QString &path, images) { qDebug() << "Processing" << path; if (dFaces) { QFile f(path); if (!f.open(QIODevice::ReadOnly)) { qCritical() << "Could not read from image file!"; return -1; } QByteArray imageData = f.readAll(); f.close(); MatPtr image = Util::imageToMat(imageData); if (image == nullptr) { qCritical() << "Invalid image!"; return -1; } FaceDetector detector; if (!detector.isValid()) { qCritical() << "Could not setup facial detector."; return -1; } QList<FacePtr> faces = detector.detect(image); if (faces.isEmpty()) { qDebug() << "Did not find any faces!"; continue; } qDebug() << "Found" << faces.size() << "face(s)."; qDebug() << faces; // Render face overlays to an image file to visualize the result. if (!faces.isEmpty()) { QImage overlay = QImage::fromData(imageData); Util::drawFaces(overlay, faces); // Save original to backup file. if (!noBackup) { QString bpath = Util::getBackupPath(path); if (QFile::copy(path, bpath)) { qDebug() << "Saved backup to" << bpath; } else { qWarning() << "Could not save backup to" << bpath; if (!Util::askProceed("Do you want to proceed?", autoReplyYes.get())) { qWarning() << "Aborting.."; return -1; } } } if (overlay.save(path)) { qDebug() << "Saved face overlays to" << path; } else { qCritical() << "Could not save overlays"; } } } // TODO: Plate detection if (dPlates) { qCritical() << "Plate detection not implemented yet!"; return -1; } } return 0; } void msgHandler(QtMsgType type, const QMessageLogContext &ctx, const QString &msg) { if (!showOutput) return; QTextStream stream(stdout); switch (type) { case QtDebugMsg: if (showDebug) { if (QString(msg) == "") { stream << endl; return; } stream << "(I) " << msg << endl; } break; case QtWarningMsg: stream << "(W) " << msg << endl; break; case QtCriticalMsg: stream << "(E) " << msg << endl; break; case QtFatalMsg: stream << "(F) " << msg << endl; abort(); } } <|endoftext|>
<commit_before>#include "myapplication.h" #include "eventdispatcher_libevent.h" int main(int argc, char** argv) { #if QT_VERSION >= 0x050000 QCoreApplication::setEventDispatcher(new EventDispatcherLibEvent()); #elif QT_VERSION >= 0x040600 EventDispatcherLibEvent e; #endif QCoreApplication::setApplicationName(QLatin1String("Proxy")); QCoreApplication::setOrganizationName(QLatin1String("Goldbar Enterprises")); QCoreApplication::setOrganizationDomain(QLatin1String("goldbar.net")); #if QT_VERSION >= 0x040400 QCoreApplication::setApplicationVersion(QLatin1String("0.0.1")); #endif MyApplication app(argc, argv); return app.exec(); } <commit_msg>Use libeventdispatcher with 4.5<commit_after>#include "myapplication.h" #include "eventdispatcher_libevent.h" int main(int argc, char** argv) { #if QT_VERSION >= 0x050000 QCoreApplication::setEventDispatcher(new EventDispatcherLibEvent()); #elif QT_VERSION >= 0x040500 EventDispatcherLibEvent e; #endif QCoreApplication::setApplicationName(QLatin1String("Proxy")); QCoreApplication::setOrganizationName(QLatin1String("Goldbar Enterprises")); QCoreApplication::setOrganizationDomain(QLatin1String("goldbar.net")); #if QT_VERSION >= 0x040400 QCoreApplication::setApplicationVersion(QLatin1String("0.0.1")); #endif MyApplication app(argc, argv); return app.exec(); } <|endoftext|>
<commit_before>//============================================================================ // Name : ParticleApp.cpp // Author : Viktor Gomeniuk // Version : // Copyright : // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <math.h> #include <SDL2/SDL.h> #include "Screen.h" using namespace particleapp; int main(int argc, char** argv) { Screen screen; if (!screen.init()){ return 1; } while(true){ // Main application loop // Update particles // Draw particles // Check for messages/events // Change color over time from 0 to 255 (use different multiplier for each RGB channel) int deltaTime = SDL_GetTicks(); int red = (1 + sin(deltaTime * 0.0001)) * 128; int green = (1 + sin(deltaTime * 0.0002)) * 128; int blue = (1 + sin(deltaTime * 0.0003)) * 128; for(int y = 0; y < Screen::SCREEN_HEIGHT; ++y){ for (int x = 0; x < Screen::SCREEN_WIDTH; ++x){ screen.setPixel(x, y, red, green, blue); } } screen.update(); // Process pending events if (!screen.processEvents()){ break; } } // Clean up screen.close(); return 0; } <commit_msg>Draw particles on screen with random animation and color change.<commit_after>//============================================================================ // Name : ParticleApp.cpp // Author : Viktor Gomeniuk // Version : // Copyright : // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <memory> #include <math.h> #include <stdlib.h> #include <time.h> #include <SDL2/SDL.h> #include "Screen.h" #include "Swarm.h" #include "Particle.h" using namespace particleapp; int main(int argc, char** argv) { // Initialize random generator (used in Particles) std::srand(time(nullptr)); Screen screen; if (!screen.init()){ return 1; } Swarm swarm; while(true){ // Main application loop // Update particles screen.clear(); swarm.update(); // Change color over time from 0 to 255 (use different multiplier for each RGB channel) int deltaTime = SDL_GetTicks(); int red = (1 + sin(deltaTime * 0.0001)) * 128; int green = (1 + sin(deltaTime * 0.0002)) * 128; int blue = (1 + sin(deltaTime * 0.0003)) * 128; // Draw particles const Particle * const pParticles = swarm.getParticles(); for (int i = 0; i < Swarm::NPARTICLES; ++i) { Particle particle = pParticles[i]; particle.update(); int x = (particle.m_x + 1) * Screen::SCREEN_WIDTH / 2; int y = (particle.m_y + 1) * Screen::SCREEN_HEIGHT / 2; screen.setPixel(x, y, red, green, blue); } // for(int y = 0; y < Screen::SCREEN_HEIGHT; ++y){ // for (int x = 0; x < Screen::SCREEN_WIDTH; ++x){ // screen.setPixel(x, y, red, green, blue); // } // } screen.update(); // Process pending events if (!screen.processEvents()){ delete [] pParticles; // TODO break; } } // Clean up screen.close(); return 0; } <|endoftext|>
<commit_before>#include "SDL.h" #include "SDL_opengl.h" #include <cmath> const float kPi = 4.0f * std::atan(1.0f); const float kPlayerForwardSpeed = 0.4f; const float kPlayerTurnSpeed = 10.0f; float playerX = 0.0f, playerY = 0.0f, playerFace = 0.0f; float playerMove(float d) { playerX += d * cos(playerFace * (kPi / 180.0f)); playerY += d * sin(playerFace * (kPi / 180.0f)); } float playerTurn(float a) { playerFace += a; if (playerFace >= 360.0f) playerFace -= 360.0f; else if (playerFace < 0.0f) playerFace += 360.0f; } void drawScene(void) { int x, y; glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-0.1f, 0.1f, -0.075f, 0.075f, 0.1f, 100.0f); glRotatef(-90.0f, 1.0f, 0.0f, 0.0f); glRotatef(90.0f - playerFace, 0.0f, 0.0f, 1.0f); glTranslatef(-playerX, -playerY, -1.0f); glMatrixMode(GL_MODELVIEW); glBegin(GL_TRIANGLES); for (x = -5; x <= 5; ++x) { for (y = -5; y <= 5; ++y) { if (x == 1 && y == 0) glColor3f(0.0f, 1.0f, 0.0f); else glColor3f(1.0f, 0.0f, 0.0f); glVertex3f(2*x - 0.5f, 2*y - 0.7f, 0.0f); glVertex3f(2*x + 0.5f, 2*y - 0.7f, 0.0f); glVertex3f(2*x + 0.0f, 2*y + 0.7f, 0.0f); } } glEnd(); SDL_GL_SwapBuffers(); } void handleKey(SDL_keysym *key) { switch (key->sym) { case SDLK_ESCAPE: SDL_Quit(); exit(0); break; case SDLK_UP: case SDLK_w: playerMove(kPlayerForwardSpeed); break; case SDLK_DOWN: case SDLK_s: playerMove(-kPlayerForwardSpeed); break; case SDLK_LEFT: case SDLK_a: playerTurn(kPlayerTurnSpeed); break; case SDLK_RIGHT: case SDLK_d: playerTurn(-kPlayerTurnSpeed); break; default: break; } } int main(int argc, char *argv[]) { SDL_Surface *screen = NULL; bool done = false; SDL_Event event; int flags; if (SDL_Init(SDL_INIT_VIDEO) < 0) { fprintf(stderr, "Could not initialize SDL: %s\n", SDL_GetError()); exit(1); } flags = SDL_OPENGL | SDL_GL_DOUBLEBUFFER; screen = SDL_SetVideoMode(640, 480, 32, flags); if (!screen) { fprintf(stderr, "Could not initialize video: %s\n", SDL_GetError()); SDL_Quit(); exit(1); } glClearColor(0.0f, 0.0f, 0.0f, 0.0f); while (!done) { drawScene(); while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: handleKey(&event.key.keysym); break; case SDL_QUIT: done = true; break; } } } SDL_Quit(); return 0; } <commit_msg>Added gradient for sky.<commit_after>#include "SDL.h" #include "SDL_opengl.h" #include <cmath> const float kPi = 4.0f * std::atan(1.0f); const float kPlayerForwardSpeed = 0.4f; const float kPlayerTurnSpeed = 10.0f; float playerX = 0.0f, playerY = 0.0f, playerFace = 0.0f; const float kGridSpacing = 2.0f; const int kGridSize = 8; float playerMove(float d) { playerX += d * cos(playerFace * (kPi / 180.0f)); playerY += d * sin(playerFace * (kPi / 180.0f)); } float playerTurn(float a) { playerFace += a; if (playerFace >= 360.0f) playerFace -= 360.0f; else if (playerFace < 0.0f) playerFace += 360.0f; } struct gradient_point { float pos; unsigned char color[3]; }; const gradient_point sky[] = { { -0.50f, { 0, 0, 51 } }, { -0.02f, { 0, 0, 0 } }, { 0.00f, { 102, 204, 255 } }, { 0.20f, { 51, 0, 255 } }, { 0.70f, { 0, 0, 0 } } }; void drawSky(void) { int i; glPushAttrib(GL_CURRENT_BIT); glBegin(GL_TRIANGLE_STRIP); glColor3ubv(sky[0].color); glVertex3f(-2.0f, 1.0f, -1.0f); glVertex3f( 2.0f, 1.0f, -1.0f); for (i = 0; i < sizeof(sky) / sizeof(*sky); ++i) { glColor3ubv(sky[i].color); glVertex3f(-2.0f, 1.0f, sky[i].pos); glVertex3f( 2.0f, 1.0f, sky[i].pos); } glVertex3f(-2.0f, 0.0f, 1.0f); glVertex3f( 2.0f, 0.0f, 1.0f); glEnd(); glPopAttrib(); } void drawGround(void) { int i; glColor3ub(51, 0, 255); glBegin(GL_LINES); for (i = -kGridSize; i <= kGridSize; ++i) { glVertex3f(i * kGridSpacing, -kGridSize * kGridSpacing, 0.0f); glVertex3f(i * kGridSpacing, kGridSize * kGridSpacing, 0.0f); glVertex3f(-kGridSize * kGridSpacing, i * kGridSpacing, 0.0f); glVertex3f( kGridSize * kGridSpacing, i * kGridSpacing, 0.0f); } glEnd(); } void drawScene(void) { glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-0.1f, 0.1f, -0.075f, 0.075f, 0.1f, 100.0f); glRotatef(-90.0f, 1.0f, 0.0f, 0.0f); drawSky(); glRotatef(90.0f - playerFace, 0.0f, 0.0f, 1.0f); glTranslatef(-playerX, -playerY, -1.0f); glMatrixMode(GL_MODELVIEW); drawGround(); SDL_GL_SwapBuffers(); } void handleKey(SDL_keysym *key) { switch (key->sym) { case SDLK_ESCAPE: SDL_Quit(); exit(0); break; case SDLK_UP: case SDLK_w: playerMove(kPlayerForwardSpeed); break; case SDLK_DOWN: case SDLK_s: playerMove(-kPlayerForwardSpeed); break; case SDLK_LEFT: case SDLK_a: playerTurn(kPlayerTurnSpeed); break; case SDLK_RIGHT: case SDLK_d: playerTurn(-kPlayerTurnSpeed); break; default: break; } } int main(int argc, char *argv[]) { SDL_Surface *screen = NULL; bool done = false; SDL_Event event; int flags; if (SDL_Init(SDL_INIT_VIDEO) < 0) { fprintf(stderr, "Could not initialize SDL: %s\n", SDL_GetError()); exit(1); } flags = SDL_OPENGL | SDL_GL_DOUBLEBUFFER; screen = SDL_SetVideoMode(640, 480, 32, flags); if (!screen) { fprintf(stderr, "Could not initialize video: %s\n", SDL_GetError()); SDL_Quit(); exit(1); } printf( "Vendor: %s\n" "Renderer: %s\n" "Version: %s\n" "Extensions: %s\n", glGetString(GL_VENDOR), glGetString(GL_RENDERER), glGetString(GL_VERSION), glGetString(GL_EXTENSIONS)); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); while (!done) { drawScene(); while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: handleKey(&event.key.keysym); break; case SDL_QUIT: done = true; break; } } } SDL_Quit(); return 0; } <|endoftext|>
<commit_before>#include "model.h" #include "helper.h" #include "interface.h" #include "shapes.h" #include "raycast.h" #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/euler_angles.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/ext.hpp> #include <imgui.h> #include <imgui_impl_glfw.h> #include <iostream> #include <fstream> #include <math.h> #include <vector> #include <sstream> #include <limits> #include <glm/gtx/string_cast.hpp> #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) #undef near #undef far #endif void key_callback(GLFWwindow*, int, int, int, int); void framebuffer_size_callback(GLFWwindow* window, int width, int height); void mouse_button_callback(GLFWwindow* window, int button, int action, int mods); bool imgChanged = false, genImg = true; // struct Raycast // { // size_t width, height; // float dx, dy, near, far; // Raycast(size_t _width, size_t _height, float _near, float _far) : width(_width), height(_height), near(_near), far(_far) { // dx = 1/_width; // dy = 1/_height; // } // }; int main(void) { GLFWwindow* window; std::vector<std::unique_ptr<tnw::Model>> models; // Initialize the library if (!glfwInit()) return 1; // Create a windowed mode window and its OpenGL context window = glfwCreateWindow(640, 480, "Sickle", NULL, NULL); swidth = 640; sheight = 480; if (!window) { glfwTerminate(); return 1; } // Make the window's context current glfwMakeContextCurrent(window); // Init ImGui ImGui_ImplGlfw_Init(window, true); // Disable .ini ImGui::GetIO().IniFilename = nullptr; //Opções de OpenGL glClearColor(0.,0.,0.,0.); glEnable(GL_LINE_SMOOTH); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); glFrontFace(GL_CCW); glShadeModel(GL_SMOOTH); GLuint tex; glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); //Camera initalization IsometricCamera camera; auto w = 41; auto h = 40; // Raycast rc(w,h,1,-100); genImg = true; //Set callbacks glfwSetKeyCallback(window, key_callback); glfwSetMouseButtonCallback(window, mouse_button_callback); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // camera.aspect = 480/640.; MainMenu mainMenu(models,camera); std::vector<tnw::Shape*> scene; tnw::Shape *obj1 = new tnw::Sphere(glm::vec3(0,0,-1),1); scene.push_back(obj1); scene.push_back(new tnw::Box(glm::vec3(4,1,-3),1,1,1)); tnw::Raycast raycast(scene, camera, w, h, tex); // Loop until the user closes the window while (!glfwWindowShouldClose(window)) { ImGui_ImplGlfw_NewFrame(); ImGui::SetNextWindowSize(ImVec2(350,350), ImGuiSetCond_FirstUseEver); // mainMenu.draw(); // Render here glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // if (genImg) { // std::cout << "Generating image...\n"; // std::flush(std::cout); // // std::cout << "Generating image..."; // // std::flush(std::cout); // genImg = false; // for (size_t i = 0; i < rc.width; ++i) { // for (size_t j = 0; j < rc.height; ++j) { // auto nx = -2.f*(1.f/2.f - float(i+1)/rc.width); // auto ny = 2.f*(1.f/2.f - float(j+1)/rc.height); // auto x = -2.f*(1.f/2.f - float(i)/rc.width); // auto y = 2.f*(1.f/2.f - float(j)/rc.height); // float pospixx = x+nx/2; // float pospixy = y+ny/2; // glm::vec3 a(pospixx, pospixy, rc.near); // glm::vec3 b(pospixx, pospixy, rc.far); // // std::cout << glm::to_string(a) << std::endl; // tnw::Ray r = tnw::Ray(a,b); // float minInter = rc.far; // int drawIndice = -1; // for (size_t k = 0; k < scene.size(); k++) { // tnw::IntersectionList ilist = scene[k]->intersect_ray(r); // if (ilist.size() >= 2) { // if (minInter < std::abs(std::get<1>(ilist[0]))) { // minInter = std::abs(std::get<1>(ilist[0])); // drawIndice = k; // } // } // } // if (drawIndice >= 0) { // // std::cout << "\ni: " << i << " j: " << j << " drawIndice: " << drawIndice; // // tnw::IntersectionList ilist = scene[0]->intersect_ray(r); // // std::cout << "\nilist size: " << ilist.size(); // // std::cout << "\na: " << glm::to_string(a) << "\nb: " << glm::to_string(b) << "\n"; // img(i,j) = std::make_tuple(0,0,0); // } // } // } // glTexSubImage2D(GL_TEXTURE_2D, 0 ,0, 0, rc.width, rc.height, GL_RGB, GL_FLOAT, img); // std::cout << " generated image\n"; // std::flush(std::cout); // } glBegin(GL_QUADS); glTexCoord2d(0, 1); glVertex2f(-1.,-1.); glTexCoord2d(1, 1); glVertex2f( 1.,-1.); glTexCoord2d(1, 0); glVertex2f( 1., 1.); glTexCoord2d(0, 0); glVertex2f(-1., 1.); glEnd(); ImGui::Render(); glfwSwapBuffers(window); // Poll for and process events glfwPollEvents(); } ImGui_ImplGlfw_Shutdown(); glfwTerminate(); glDeleteTextures(1, &tex); return 0; } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { glfwSetWindowShouldClose(window, GLFW_TRUE); } else ImGui_ImplGlFw_KeyCallback(window, key, scancode, action, mods); } void framebuffer_size_callback(GLFWwindow* window, int width, int height) { camera.aspect = height/((float)width); glViewport(0,0,width,height); } void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) { if (button == GLFW_MOUSE_BUTTON_LEFT) { } } <commit_msg>Tirando coisas da main que podem dar conflito<commit_after>#include "model.h" #include "helper.h" #include "interface.h" #include "shapes.h" #include "raycast.h" #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/euler_angles.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/ext.hpp> #include <imgui.h> #include <imgui_impl_glfw.h> #include <iostream> #include <fstream> #include <math.h> #include <vector> #include <sstream> #include <limits> #include <glm/gtx/string_cast.hpp> #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) #undef near #undef far #endif void key_callback(GLFWwindow*, int, int, int, int); void framebuffer_size_callback(GLFWwindow* window, int width, int height); void mouse_button_callback(GLFWwindow* window, int button, int action, int mods); //Camera initalization IsometricCamera camera; int main(void) { GLFWwindow* window; std::vector<std::unique_ptr<tnw::Model>> models; // Initialize the library if (!glfwInit()) return 1; // Create a windowed mode window and its OpenGL context window = glfwCreateWindow(640, 480, "Sickle", NULL, NULL); if (!window) { glfwTerminate(); return 1; } // Make the window's context current glfwMakeContextCurrent(window); // Init ImGui ImGui_ImplGlfw_Init(window, true); // Disable .ini ImGui::GetIO().IniFilename = nullptr; //Opções de OpenGL glClearColor(0.,0.,0.,0.); glEnable(GL_LINE_SMOOTH); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); glFrontFace(GL_CCW); glShadeModel(GL_SMOOTH); GLuint tex; glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); //Set callbacks glfwSetKeyCallback(window, key_callback); glfwSetMouseButtonCallback(window, mouse_button_callback); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // camera.aspect = 480/640.; MainMenu mainMenu(models,camera); // Loop until the user closes the window while (!glfwWindowShouldClose(window)) { ImGui_ImplGlfw_NewFrame(); ImGui::SetNextWindowSize(ImVec2(350,350), ImGuiSetCond_FirstUseEver); mainMenu.draw(); // Render here glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glBegin(GL_QUADS); glTexCoord2d(0, 1); glVertex2f(-1.,-1.); glTexCoord2d(1, 1); glVertex2f( 1.,-1.); glTexCoord2d(1, 0); glVertex2f( 1., 1.); glTexCoord2d(0, 0); glVertex2f(-1., 1.); glEnd(); ImGui::Render(); glfwSwapBuffers(window); // Poll for and process events glfwPollEvents(); } ImGui_ImplGlfw_Shutdown(); glfwTerminate(); glDeleteTextures(1, &tex); return 0; } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { glfwSetWindowShouldClose(window, GLFW_TRUE); } else ImGui_ImplGlFw_KeyCallback(window, key, scancode, action, mods); } void framebuffer_size_callback(GLFWwindow* window, int width, int height) { camera.aspect = height/((float)width); glViewport(0,0,width,height); } void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) { if (button == GLFW_MOUSE_BUTTON_LEFT) { } } <|endoftext|>
<commit_before>#include<limits> #include<string> #include<geGL/geGL.h> #include<geDE/geDE.h> #include<geDE/Kernel.h> #include<geUtil/CopyArgumentManager2VariableRegister.h> #include<geUtil/ArgumentManager/ArgumentManager.h> #include<geAd/SDLWindow/SDLWindow.h> #include<geCore/Text.h> #include<AntTweakBar.h> #include"../include/VariableRegisterManipulator.h" #include<assimp/cimport.h> #include<assimp/scene.h> #include<assimp/postprocess.h> struct Data{ std::shared_ptr<ge::de::TypeRegister> typeRegister = nullptr; std::shared_ptr<ge::de::FunctionRegister> functionRegister = nullptr; std::shared_ptr<ge::de::NameRegister> nameRegister = nullptr; std::shared_ptr<ge::de::VariableRegister> variableRegister = nullptr; ge::de::Kernel kernel; std::shared_ptr<ge::gl::opengl::FunctionProvider> gl = nullptr; std::shared_ptr<ge::util::SDLEventProc> mainLoop = nullptr; std::shared_ptr<ge::util::SDLWindow> window = nullptr; std::shared_ptr<ge::gl::VertexArray> emptyVAO = nullptr; std::shared_ptr<VariableRegisterManipulator> variableManipulator = nullptr; static void init(Data*data); static void deinit(Data*data); class IdleCallback: public ge::util::CallbackInterface{ public: Data*data; IdleCallback(Data*data){this->data = data;} virtual void operator()()override; virtual ~IdleCallback(){} }; class WindowEventCallback: public ge::util::EventCallbackInterface{ public: Data*data; WindowEventCallback(Data*data){this->data = data;} virtual bool operator()(ge::util::EventDataPointer const&)override; virtual ~WindowEventCallback(){} }; class WindowEventHandler: public ge::util::EventHandlerInterface{ public: Data*data; WindowEventHandler(Data*data){this->data = data;} virtual bool operator()(ge::util::EventDataPointer const&)override; virtual ~WindowEventHandler(){} }; std::shared_ptr<ge::de::Resource>model = nullptr; std::shared_ptr<ge::de::Resource>program = nullptr; std::shared_ptr<ge::de::Function>prg = nullptr; }; namespace ge{ namespace de{ template<> std::string TypeRegister::getTypeKeyword<aiScene const*>(){ return "AssimpScene"; } template<> std::string TypeRegister::getTypeKeyword<std::shared_ptr<ge::gl::Shader>>(){ return "SharedShader"; } template<> std::string TypeRegister::getTypeKeyword<std::shared_ptr<ge::gl::Program>>(){ return "SharedProgram"; } } } aiScene const*assimpLoader(std::string name){ aiScene const* model = aiImportFile(name.c_str(),aiProcess_Triangulate|aiProcess_GenNormals|aiProcess_SortByPType); return model; } std::string concatenate(std::string a,std::string b){ return a+b; } std::string shaderSourceLoader( std::string version, std::string defines, std::string dir, std::string fileNames){ std::cout<<"("<<version<<"#"<<defines<<"#"<<dir<<"#"<<fileNames<<")"<<std::endl; std::stringstream ss; ss<<version; ss<<defines; size_t pos=0; do{ size_t newPos = fileNames.find("\n",pos); if(newPos == std::string::npos){ auto fileName = fileNames.substr(pos); ss<<ge::core::loadTextFile(dir+fileName); break; } auto fileName = fileNames.substr(pos,newPos-pos); ss<<ge::core::loadTextFile(dir+fileName); pos = newPos+1; }while(true); return ss.str(); } std::shared_ptr<ge::gl::Shader>createShader(GLenum type,std::string source){ return std::make_shared<ge::gl::Shader>(type,source); } std::shared_ptr<ge::gl::Program>createProgram2( std::shared_ptr<ge::gl::Shader>s0, std::shared_ptr<ge::gl::Shader>s1){ return std::make_shared<ge::gl::Program>(s0,s1); } int main(int argc,char*argv[]){ //std::cout<<shaderSourceLoader("#version 450\n","","shaders/","vertex.vp\nfragment.fp"); //return 0; Data data; data.typeRegister = std::make_shared<ge::de::TypeRegister>(); data.nameRegister = std::make_shared<ge::de::NameRegister>(); data.functionRegister = std::make_shared<ge::de::FunctionRegister>(data.typeRegister,data.nameRegister); ge::de::registerStdFunctions(data.functionRegister); data.variableRegister = std::make_shared<ge::de::VariableRegister>("*"); auto argm = std::make_shared<ge::util::ArgumentManager>(argc-1,argv+1); ge::util::copyArgumentManager2VariableRegister(data.variableRegister,*argm,data.functionRegister); std::cout<<data.variableRegister->toStr(0,data.typeRegister)<<std::endl; data.mainLoop = std::make_shared<ge::util::SDLEventProc>(true); data.mainLoop->setIdleCallback(std::make_shared<Data::IdleCallback>(&data)); data.mainLoop->setEventHandler(std::make_shared<Data::WindowEventHandler>(&data)); data.window = std::make_shared<ge::util::SDLWindow>(); data.window->createContext("rendering",450u,ge::util::SDLWindow::CORE,ge::util::SDLWindow::DEBUG); data.window->setEventCallback(SDL_WINDOWEVENT,std::make_shared<Data::WindowEventCallback>(&data)); data.mainLoop->addWindow("primaryWindow",data.window); data.init(&data); (*data.mainLoop)(); data.deinit(&data); return EXIT_SUCCESS; } void Data::IdleCallback::operator()(){ this->data->gl->glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); this->data->emptyVAO->bind(); (*this->data->prg)(); (*(std::shared_ptr<ge::gl::Program>*)*this->data->program)->use(); this->data->gl->glDrawArrays(GL_TRIANGLE_STRIP,0,3); this->data->emptyVAO->unbind(); TwDraw(); this->data->window->swap(); } bool Data::WindowEventCallback::operator()(ge::util::EventDataPointer const&event){ auto sdlEventData = (ge::util::SDLEventData const*)(event); if(sdlEventData->event.window.event==SDL_WINDOWEVENT_CLOSE){ this->data->mainLoop->removeWindow("primaryWindow"); return true; } return false; } bool Data::WindowEventHandler::operator()(ge::util::EventDataPointer const&event){ auto sdlEventData = (ge::util::SDLEventData const*)(event); bool handledByAnt = TwEventSDL(&sdlEventData->event,SDL_MAJOR_VERSION,SDL_MINOR_VERSION); if(handledByAnt)return true; return false; } void Data::init(Data*data){ data->window->makeCurrent("rendering"); ge::gl::init(std::make_shared<ge::gl::opengl::DefaultLoader>((ge::gl::opengl::GET_PROC_ADDRESS)SDL_GL_GetProcAddress)); data->gl = ge::gl::opengl::getDefaultFunctionProvider(); ge::gl::setHighDebugMessage(); data->gl->glEnable(GL_DEPTH_TEST); data->gl->glDepthFunc(GL_LEQUAL); data->gl->glDisable(GL_CULL_FACE); data->gl->glClearColor(0,1,0,1); data->emptyVAO = std::make_shared<ge::gl::VertexArray>(); TwInit(TW_OPENGL_CORE,nullptr); TwWindowSize(data->window->getWidth(),data->window->getHeight()); data->variableManipulator = std::make_shared<VariableRegisterManipulator>(data->variableRegister); //so part data->typeRegister->addAtomicType( "AssimpScene", sizeof(aiScene const*), nullptr, [](void*ptr){aiReleaseImport(*((aiScene const**)ptr));}); data->typeRegister->addAtomicType( "SharedShader", sizeof(std::shared_ptr<ge::gl::Shader>), [](void*ptr){new(ptr)std::shared_ptr<ge::gl::Shader>;}, [](void*ptr){((std::shared_ptr<ge::gl::Shader>*)ptr)->~shared_ptr();}); data->typeRegister->addAtomicType( "SharedProgram", sizeof(std::shared_ptr<ge::gl::Program>), [](void*ptr){new(ptr)std::shared_ptr<ge::gl::Program>;}, [](void*ptr){((std::shared_ptr<ge::gl::Program>*)ptr)->~shared_ptr();}); ge::de::registerBasicFunction(data->functionRegister,"assimpLoader" ,assimpLoader ); auto fid = ge::de::registerBasicFunction(data->functionRegister,"shaderSourceLoader",shaderSourceLoader); data->nameRegister->setFceInputName(fid,0,"version"); data->nameRegister->setFceInputName(fid,1,"defines"); data->nameRegister->setFceInputName(fid,2,"dir"); data->nameRegister->setFceInputName(fid,3,"fileNames"); data->nameRegister->setFceOutputName(fid,"source"); fid = ge::de::registerBasicFunction(data->functionRegister,"createShader" ,createShader ); data->nameRegister->setFceInputName(fid,0,"type"); data->nameRegister->setFceInputName(fid,1,"source"); data->nameRegister->setFceOutputName(fid,"sharedShader"); fid = ge::de::registerBasicFunction(data->functionRegister,"createProgram2" ,createProgram2 ); data->nameRegister->setFceInputName(fid,0,"shader0"); data->nameRegister->setFceInputName(fid,1,"shader1"); data->nameRegister->setFceOutputName(fid,"sharedProgram"); //script part data->model = data->typeRegister->sharedResource("AssimpScene"); auto fceLoader = data->functionRegister->sharedFunction("assimpLoader"); fceLoader->bindInput(data->functionRegister,0,data->variableRegister->getVariable("modelFile")); fceLoader->bindOutput(data->functionRegister,data->model); (*fceLoader)(); std::cout<<(*((aiScene const**)*data->model))->mNumMeshes<<std::endl; auto version = data->functionRegister->sharedFunction("Nullary"); version->bindOutput(data->functionRegister,data->typeRegister->sharedResource("string")); *(std::string*)*version->getOutputData() = "#version 450\n"; auto vp = data->functionRegister->sharedFunction("Nullary"); vp->bindOutput(data->functionRegister,data->typeRegister->sharedResource("string")); *(std::string*)*vp->getOutputData() = "vertex.vp"; auto fp = data->functionRegister->sharedFunction("Nullary"); fp->bindOutput(data->functionRegister,data->typeRegister->sharedResource("string")); *(std::string*)*fp->getOutputData() = "fragment.fp"; auto defines = data->functionRegister->sharedFunction("Nullary"); defines->bindOutput(data->functionRegister,data->typeRegister->sharedResource("string")); *(std::string*)*defines->getOutputData() = ""; auto vpl = data->functionRegister->sharedFunction("shaderSourceLoader"); vpl->bindInput(data->functionRegister,0,version); vpl->bindInput(data->functionRegister,1,defines); vpl->bindInput(data->functionRegister,2,data->variableRegister->getVariable("shaderDirectory")); vpl->bindInput(data->functionRegister,3,vp); vpl->bindOutput(data->functionRegister,data->typeRegister->sharedResource("string")); auto fpl = data->functionRegister->sharedFunction("shaderSourceLoader"); fpl->bindInput(data->functionRegister,0,version); fpl->bindInput(data->functionRegister,1,defines); fpl->bindInput(data->functionRegister,2,data->variableRegister->getVariable("shaderDirectory")); fpl->bindInput(data->functionRegister,3,fp); fpl->bindOutput(data->functionRegister,data->typeRegister->sharedResource("string")); auto vpen = data->functionRegister->sharedFunction("Nullary"); vpen->bindOutput(data->functionRegister,data->typeRegister->sharedResource("u32")); *(GLenum*)*vpen->getOutputData() = GL_VERTEX_SHADER; auto fpen = data->functionRegister->sharedFunction("Nullary"); fpen->bindOutput(data->functionRegister,data->typeRegister->sharedResource("u32")); *(GLenum*)*fpen->getOutputData() = GL_FRAGMENT_SHADER; auto vpc = data->functionRegister->sharedFunction("createShader"); vpc->bindInput(data->functionRegister,0,vpen); vpc->bindInput(data->functionRegister,1,vpl); vpc->bindOutput(data->functionRegister,data->typeRegister->sharedResource("SharedShader")); auto fpc = data->functionRegister->sharedFunction("createShader"); fpc->bindInput(data->functionRegister,0,fpen); fpc->bindInput(data->functionRegister,1,fpl); fpc->bindOutput(data->functionRegister,data->typeRegister->sharedResource("SharedShader")); data->prg = data->functionRegister->sharedFunction("createProgram2"); data->prg->bindInput(data->functionRegister,0,vpc); data->prg->bindInput(data->functionRegister,1,fpc); data->program = data->typeRegister->sharedResource("SharedProgram"); data->prg->bindOutput(data->functionRegister,data->program); //data->model = nullptr; //fceLoader->bindOutput(data->functionRegister,nullptr); } void Data::deinit(Data*data){ (void)data; data->variableManipulator = nullptr; data->model = nullptr; TwTerminate(); } <commit_msg>Added kernel<commit_after>#include<limits> #include<string> #include<geGL/geGL.h> #include<geDE/geDE.h> #include<geDE/Kernel.h> #include<geUtil/CopyArgumentManager2VariableRegister.h> #include<geUtil/ArgumentManager/ArgumentManager.h> #include<geAd/SDLWindow/SDLWindow.h> #include<geCore/Text.h> #include<AntTweakBar.h> #include"../include/VariableRegisterManipulator.h" #include<assimp/cimport.h> #include<assimp/scene.h> #include<assimp/postprocess.h> struct Data{ ge::de::Kernel kernel; std::shared_ptr<ge::gl::opengl::FunctionProvider> gl = nullptr; std::shared_ptr<ge::util::SDLEventProc> mainLoop = nullptr; std::shared_ptr<ge::util::SDLWindow> window = nullptr; std::shared_ptr<ge::gl::VertexArray> emptyVAO = nullptr; std::shared_ptr<VariableRegisterManipulator> variableManipulator = nullptr; static void init(Data*data); static void deinit(Data*data); class IdleCallback: public ge::util::CallbackInterface{ public: Data*data; IdleCallback(Data*data){this->data = data;} virtual void operator()()override; virtual ~IdleCallback(){} }; class WindowEventCallback: public ge::util::EventCallbackInterface{ public: Data*data; WindowEventCallback(Data*data){this->data = data;} virtual bool operator()(ge::util::EventDataPointer const&)override; virtual ~WindowEventCallback(){} }; class WindowEventHandler: public ge::util::EventHandlerInterface{ public: Data*data; WindowEventHandler(Data*data){this->data = data;} virtual bool operator()(ge::util::EventDataPointer const&)override; virtual ~WindowEventHandler(){} }; std::shared_ptr<ge::de::Resource>model = nullptr; std::shared_ptr<ge::de::Function>prg = nullptr; }; namespace ge{ namespace de{ template<> std::string TypeRegister::getTypeKeyword<aiScene const*>(){ return "AssimpScene"; } template<> std::string TypeRegister::getTypeKeyword<std::shared_ptr<ge::gl::Shader>>(){ return "SharedShader"; } template<> std::string TypeRegister::getTypeKeyword<std::shared_ptr<ge::gl::Program>>(){ return "SharedProgram"; } } } aiScene const*assimpLoader(std::string name){ aiScene const* model = aiImportFile(name.c_str(),aiProcess_Triangulate|aiProcess_GenNormals|aiProcess_SortByPType); return model; } std::string concatenate(std::string a,std::string b){ return a+b; } std::string shaderSourceLoader( std::string version, std::string defines, std::string dir, std::string fileNames){ std::cout<<"("<<version<<"#"<<defines<<"#"<<dir<<"#"<<fileNames<<")"<<std::endl; std::stringstream ss; ss<<version; ss<<defines; size_t pos=0; do{ size_t newPos = fileNames.find("\n",pos); if(newPos == std::string::npos){ auto fileName = fileNames.substr(pos); ss<<ge::core::loadTextFile(dir+fileName); break; } auto fileName = fileNames.substr(pos,newPos-pos); ss<<ge::core::loadTextFile(dir+fileName); pos = newPos+1; }while(true); return ss.str(); } std::shared_ptr<ge::gl::Shader>createVertexShader(std::string source){ return std::make_shared<ge::gl::Shader>(GL_VERTEX_SHADER,source); } std::shared_ptr<ge::gl::Shader>createFragmentShader(std::string source){ return std::make_shared<ge::gl::Shader>(GL_FRAGMENT_SHADER,source); } std::shared_ptr<ge::gl::Program>createProgram2( std::shared_ptr<ge::gl::Shader>s0, std::shared_ptr<ge::gl::Shader>s1){ return std::make_shared<ge::gl::Program>(s0,s1); } int main(int argc,char*argv[]){ //std::cout<<shaderSourceLoader("#version 450\n","","shaders/","vertex.vp\nfragment.fp"); //return 0; Data data; /* data.typeRegister = std::make_shared<ge::de::TypeRegister>(); data.nameRegister = std::make_shared<ge::de::NameRegister>(); data.functionRegister = std::make_shared<ge::de::FunctionRegister>(data.typeRegister,data.nameRegister); ge::de::registerStdFunctions(data.functionRegister); data.variableRegister = std::make_shared<ge::de::VariableRegister>("*"); */ auto argm = std::make_shared<ge::util::ArgumentManager>(argc-1,argv+1); ge::util::copyArgumentManager2VariableRegister(data.kernel.variableRegister,*argm,data.kernel.functionRegister); std::cout<<data.kernel.variableRegister->toStr(0,data.kernel.typeRegister)<<std::endl; data.mainLoop = std::make_shared<ge::util::SDLEventProc>(true); data.mainLoop->setIdleCallback(std::make_shared<Data::IdleCallback>(&data)); data.mainLoop->setEventHandler(std::make_shared<Data::WindowEventHandler>(&data)); data.window = std::make_shared<ge::util::SDLWindow>(); data.window->createContext("rendering",450u,ge::util::SDLWindow::CORE,ge::util::SDLWindow::DEBUG); data.window->setEventCallback(SDL_WINDOWEVENT,std::make_shared<Data::WindowEventCallback>(&data)); data.mainLoop->addWindow("primaryWindow",data.window); data.init(&data); (*data.mainLoop)(); data.deinit(&data); return EXIT_SUCCESS; } void Data::IdleCallback::operator()(){ this->data->gl->glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); this->data->emptyVAO->bind(); (*this->data->prg)(); (*(std::shared_ptr<ge::gl::Program>*)*this->data->prg->getOutputData())->use(); this->data->gl->glDrawArrays(GL_TRIANGLE_STRIP,0,3); this->data->emptyVAO->unbind(); TwDraw(); this->data->window->swap(); } bool Data::WindowEventCallback::operator()(ge::util::EventDataPointer const&event){ auto sdlEventData = (ge::util::SDLEventData const*)(event); if(sdlEventData->event.window.event==SDL_WINDOWEVENT_CLOSE){ this->data->mainLoop->removeWindow("primaryWindow"); return true; } return false; } bool Data::WindowEventHandler::operator()(ge::util::EventDataPointer const&event){ auto sdlEventData = (ge::util::SDLEventData const*)(event); bool handledByAnt = TwEventSDL(&sdlEventData->event,SDL_MAJOR_VERSION,SDL_MINOR_VERSION); if(handledByAnt)return true; return false; } void Data::init(Data*data){ data->window->makeCurrent("rendering"); ge::gl::init(std::make_shared<ge::gl::opengl::DefaultLoader>((ge::gl::opengl::GET_PROC_ADDRESS)SDL_GL_GetProcAddress)); data->gl = ge::gl::opengl::getDefaultFunctionProvider(); ge::gl::setHighDebugMessage(); data->gl->glEnable(GL_DEPTH_TEST); data->gl->glDepthFunc(GL_LEQUAL); data->gl->glDisable(GL_CULL_FACE); data->gl->glClearColor(0,1,0,1); data->emptyVAO = std::make_shared<ge::gl::VertexArray>(); TwInit(TW_OPENGL_CORE,nullptr); TwWindowSize(data->window->getWidth(),data->window->getHeight()); auto &kernel = data->kernel; data->variableManipulator = std::make_shared<VariableRegisterManipulator>(kernel.variableRegister); //so part kernel.addAtomicType( "AssimpScene", sizeof(aiScene const*), nullptr, [](void*ptr){aiReleaseImport(*((aiScene const**)ptr));}); kernel.addAtomicType( "SharedShader", sizeof(std::shared_ptr<ge::gl::Shader>), [](void*ptr){new(ptr)std::shared_ptr<ge::gl::Shader>;}, [](void*ptr){((std::shared_ptr<ge::gl::Shader>*)ptr)->~shared_ptr();}); kernel.addAtomicType( "SharedProgram", sizeof(std::shared_ptr<ge::gl::Program>), [](void*ptr){new(ptr)std::shared_ptr<ge::gl::Program>;}, [](void*ptr){((std::shared_ptr<ge::gl::Program>*)ptr)->~shared_ptr();}); kernel.addFunction({"assimpLoader"},assimpLoader); kernel.addFunction({"shaderSourceLoader","source","version","defines","dir","fileNames"},shaderSourceLoader); kernel.addFunction({"createVertexShader","sharedShader","source"},createVertexShader); kernel.addFunction({"createFragmentShader","sharedShader","source"},createFragmentShader); kernel.addFunction({"createProgram2","shaderProgram","shader0","shader1"},createProgram2); //script part auto fceLoader = kernel.createFunction("assimpLoader",{"modelFile"},"AssimpScene"); (*fceLoader)(); std::cout<<(*((aiScene const**)*fceLoader->getOutputData()))->mNumMeshes<<std::endl; kernel.addVariable("program.version",std::string("#version 450\n")); kernel.addVariable("program.vertexShader",std::string("vertex.vp")); kernel.addVariable("program.fragmentShader",std::string("fragment.fp")); kernel.addVariable("program.defines",std::string("")); auto vpl = kernel.createFunction("shaderSourceLoader",{"program.version","program.defines","shaderDirectory","program.vertexShader"},"string"); auto fpl = kernel.createFunction("shaderSourceLoader",{"program.version","program.defines","shaderDirectory","program.fragmentShader"},"string"); auto vpc = kernel.createFunction("createVertexShader",{vpl},"SharedShader"); auto fpc = kernel.createFunction("createFragmentShader",{fpl},"SharedShader"); data->prg = kernel.createFunction("createProgram2",{vpc,fpc},"SharedProgram"); } void Data::deinit(Data*data){ (void)data; data->variableManipulator = nullptr; data->model = nullptr; TwTerminate(); } <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved. // Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // @Authors // Peng Xiao, [email protected] // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other oclMaterials provided with the distribution. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #include <iomanip> #include "precomp.hpp" using namespace cv; using namespace cv::ocl; using namespace std; #if !defined HAVE_CLAMDFFT void cv::ocl::dft(const oclMat&, oclMat&, Size, int) { CV_Error(CV_StsNotImplemented, "OpenCL DFT is not implemented"); } namespace cv { namespace ocl { void fft_teardown(){} }} #else #include "clAmdFft.h" namespace cv { namespace ocl { void fft_setup(); void fft_teardown(); enum FftType { C2R = 1, // complex to complex R2C = 2, // real to opencl HERMITIAN_INTERLEAVED C2C = 3 // opencl HERMITIAN_INTERLEAVED to real }; struct FftPlan { protected: clAmdFftPlanHandle plHandle; FftPlan& operator=(const FftPlan&); public: FftPlan(Size _dft_size, int _src_step, int _dst_step, int _flags, FftType _type); ~FftPlan(); inline clAmdFftPlanHandle getPlanHandle() { return plHandle; } const Size dft_size; const int src_step, dst_step; const int flags; const FftType type; }; class PlanCache { protected: PlanCache(); ~PlanCache(); friend class auto_ptr<PlanCache>; static auto_ptr<PlanCache> planCache; bool started; vector<FftPlan *> planStore; clAmdFftSetupData *setupData; public: friend void fft_setup(); friend void fft_teardown(); static PlanCache* getPlanCache() { if( NULL == planCache.get()) planCache.reset(new PlanCache()); return planCache.get(); } // return a baked plan-> // if there is one matched plan, return it // if not, bake a new one, put it into the planStore and return it. static FftPlan* getPlan(Size _dft_size, int _src_step, int _dst_step, int _flags, FftType _type); // remove a single plan from the store // return true if the plan is successfully removed // else static bool removePlan(clAmdFftPlanHandle ); }; } } auto_ptr<PlanCache> PlanCache::planCache; void cv::ocl::fft_setup() { PlanCache& pCache = *PlanCache::getPlanCache(); if(pCache.started) { return; } pCache.setupData = new clAmdFftSetupData; openCLSafeCall(clAmdFftInitSetupData( pCache.setupData )); pCache.started = true; } void cv::ocl::fft_teardown() { PlanCache& pCache = *PlanCache::getPlanCache(); if(!pCache.started) { return; } delete pCache.setupData; for(size_t i = 0; i < pCache.planStore.size(); i ++) { delete pCache.planStore[i]; } pCache.planStore.clear(); openCLSafeCall( clAmdFftTeardown( ) ); pCache.started = false; } // bake a new plan cv::ocl::FftPlan::FftPlan(Size _dft_size, int _src_step, int _dst_step, int _flags, FftType _type) : plHandle(0), dft_size(_dft_size), src_step(_src_step), dst_step(_dst_step), flags(_flags), type(_type) { fft_setup(); bool is_1d_input = (_dft_size.height == 1); int is_row_dft = flags & DFT_ROWS; int is_scaled_dft = flags & DFT_SCALE; int is_inverse = flags & DFT_INVERSE; //clAmdFftResultLocation place; clAmdFftLayout inLayout; clAmdFftLayout outLayout; clAmdFftDim dim = is_1d_input || is_row_dft ? CLFFT_1D : CLFFT_2D; size_t batchSize = is_row_dft ? dft_size.height : 1; size_t clLengthsIn[ 3 ] = {1, 1, 1}; size_t clStridesIn[ 3 ] = {1, 1, 1}; //size_t clLengthsOut[ 3 ] = {1, 1, 1}; size_t clStridesOut[ 3 ] = {1, 1, 1}; clLengthsIn[0] = dft_size.width; clLengthsIn[1] = is_row_dft ? 1 : dft_size.height; clStridesIn[0] = 1; clStridesOut[0] = 1; switch(_type) { case C2C: inLayout = CLFFT_COMPLEX_INTERLEAVED; outLayout = CLFFT_COMPLEX_INTERLEAVED; clStridesIn[1] = src_step / sizeof(std::complex<float>); clStridesOut[1] = clStridesIn[1]; break; case R2C: inLayout = CLFFT_REAL; outLayout = CLFFT_HERMITIAN_INTERLEAVED; clStridesIn[1] = src_step / sizeof(float); clStridesOut[1] = dst_step / sizeof(std::complex<float>); break; case C2R: inLayout = CLFFT_HERMITIAN_INTERLEAVED; outLayout = CLFFT_REAL; clStridesIn[1] = src_step / sizeof(std::complex<float>); clStridesOut[1] = dst_step / sizeof(float); break; default: //std::runtime_error("does not support this convertion!"); cout << "Does not support this convertion!" << endl; throw exception(); break; } clStridesIn[2] = is_row_dft ? clStridesIn[1] : dft_size.width * clStridesIn[1]; clStridesOut[2] = is_row_dft ? clStridesOut[1] : dft_size.width * clStridesOut[1]; openCLSafeCall( clAmdFftCreateDefaultPlan( &plHandle, Context::getContext()->impl->clContext, dim, clLengthsIn ) ); openCLSafeCall( clAmdFftSetResultLocation( plHandle, CLFFT_OUTOFPLACE ) ); openCLSafeCall( clAmdFftSetLayout( plHandle, inLayout, outLayout ) ); openCLSafeCall( clAmdFftSetPlanBatchSize( plHandle, batchSize ) ); openCLSafeCall( clAmdFftSetPlanInStride ( plHandle, dim, clStridesIn ) ); openCLSafeCall( clAmdFftSetPlanOutStride ( plHandle, dim, clStridesOut ) ); openCLSafeCall( clAmdFftSetPlanDistance ( plHandle, clStridesIn[ dim ], clStridesOut[ dim ]) ); float scale_ = is_scaled_dft ? 1.f / _dft_size.area() : 1.f; openCLSafeCall( clAmdFftSetPlanScale ( plHandle, is_inverse ? CLFFT_BACKWARD : CLFFT_FORWARD, scale_ ) ); //ready to bake openCLSafeCall( clAmdFftBakePlan( plHandle, 1, &(Context::getContext()->impl->clCmdQueue), NULL, NULL ) ); } cv::ocl::FftPlan::~FftPlan() { openCLSafeCall( clAmdFftDestroyPlan( &plHandle ) ); } cv::ocl::PlanCache::PlanCache() : started(false), planStore(vector<cv::ocl::FftPlan *>()), setupData(NULL) { } cv::ocl::PlanCache::~PlanCache() { fft_teardown(); } FftPlan* cv::ocl::PlanCache::getPlan(Size _dft_size, int _src_step, int _dst_step, int _flags, FftType _type) { PlanCache& pCache = *PlanCache::getPlanCache(); vector<FftPlan *>& pStore = pCache.planStore; // go through search for(size_t i = 0; i < pStore.size(); i ++) { FftPlan *plan = pStore[i]; if( plan->dft_size.width == _dft_size.width && plan->dft_size.height == _dft_size.height && plan->flags == _flags && plan->src_step == _src_step && plan->dst_step == _dst_step && plan->type == _type ) { return plan; } } // no baked plan is found FftPlan *newPlan = new FftPlan(_dft_size, _src_step, _dst_step, _flags, _type); pStore.push_back(newPlan); return newPlan; } bool cv::ocl::PlanCache::removePlan(clAmdFftPlanHandle plHandle) { PlanCache& pCache = *PlanCache::getPlanCache(); vector<FftPlan *>& pStore = pCache.planStore; for(size_t i = 0; i < pStore.size(); i ++) { if(pStore[i]->getPlanHandle() == plHandle) { pStore.erase(pStore.begin() + i); delete pStore[i]; return true; } } return false; } void cv::ocl::dft(const oclMat &src, oclMat &dst, Size dft_size, int flags) { if(dft_size == Size(0, 0)) { dft_size = src.size(); } // check if the given dft size is of optimal dft size CV_Assert(dft_size.area() == getOptimalDFTSize(dft_size.area())); // the two flags are not compatible CV_Assert( !((flags & DFT_SCALE) && (flags & DFT_ROWS)) ); // similar assertions with cuda module CV_Assert(src.type() == CV_32F || src.type() == CV_32FC2); //bool is_1d_input = (src.rows == 1); //int is_row_dft = flags & DFT_ROWS; //int is_scaled_dft = flags & DFT_SCALE; int is_inverse = flags & DFT_INVERSE; bool is_complex_input = src.channels() == 2; bool is_complex_output = !(flags & DFT_REAL_OUTPUT); // We don't support real-to-real transform CV_Assert(is_complex_input || is_complex_output); FftType type = (FftType)(is_complex_input << 0 | is_complex_output << 1); switch(type) { case C2C: dst.create(src.rows, src.cols, CV_32FC2); break; case R2C: dst.create(src.rows, src.cols / 2 + 1, CV_32FC2); break; case C2R: CV_Assert(dft_size.width / 2 + 1 == src.cols && dft_size.height == src.rows); dst.create(src.rows, dft_size.width, CV_32FC1); break; default: //std::runtime_error("does not support this convertion!"); cout << "Does not support this convertion!" << endl; throw exception(); break; } clAmdFftPlanHandle plHandle = PlanCache::getPlan(dft_size, src.step, dst.step, flags, type)->getPlanHandle(); //get the buffersize size_t buffersize = 0; openCLSafeCall( clAmdFftGetTmpBufSize(plHandle, &buffersize ) ); //allocate the intermediate buffer // TODO, bind this with the current FftPlan cl_mem clMedBuffer = NULL; if (buffersize) { cl_int medstatus; clMedBuffer = clCreateBuffer ( src.clCxt->impl->clContext, CL_MEM_READ_WRITE, buffersize, 0, &medstatus); openCLSafeCall( medstatus ); } openCLSafeCall( clAmdFftEnqueueTransform( plHandle, is_inverse ? CLFFT_BACKWARD : CLFFT_FORWARD, 1, &src.clCxt->impl->clCmdQueue, 0, NULL, NULL, (cl_mem *)&src.data, (cl_mem *)&dst.data, clMedBuffer ) ); openCLSafeCall( clFinish(src.clCxt->impl->clCmdQueue) ); if(clMedBuffer) { openCLFree(clMedBuffer); } //fft_teardown(); } #endif <commit_msg>Fix ocl::dft the compile warning on Linux<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved. // Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // @Authors // Peng Xiao, [email protected] // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other oclMaterials provided with the distribution. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #include <iomanip> #include "precomp.hpp" using namespace cv; using namespace cv::ocl; using namespace std; #if !defined HAVE_CLAMDFFT void cv::ocl::dft(const oclMat&, oclMat&, Size, int) { CV_Error(CV_StsNotImplemented, "OpenCL DFT is not implemented"); } namespace cv { namespace ocl { void fft_teardown(); }} void cv::ocl::fft_teardown(){} #else #include "clAmdFft.h" namespace cv { namespace ocl { void fft_setup(); void fft_teardown(); enum FftType { C2R = 1, // complex to complex R2C = 2, // real to opencl HERMITIAN_INTERLEAVED C2C = 3 // opencl HERMITIAN_INTERLEAVED to real }; struct FftPlan { protected: clAmdFftPlanHandle plHandle; FftPlan& operator=(const FftPlan&); public: FftPlan(Size _dft_size, int _src_step, int _dst_step, int _flags, FftType _type); ~FftPlan(); inline clAmdFftPlanHandle getPlanHandle() { return plHandle; } const Size dft_size; const int src_step, dst_step; const int flags; const FftType type; }; class PlanCache { protected: PlanCache(); ~PlanCache(); friend class auto_ptr<PlanCache>; static auto_ptr<PlanCache> planCache; bool started; vector<FftPlan *> planStore; clAmdFftSetupData *setupData; public: friend void fft_setup(); friend void fft_teardown(); static PlanCache* getPlanCache() { if( NULL == planCache.get()) planCache.reset(new PlanCache()); return planCache.get(); } // return a baked plan-> // if there is one matched plan, return it // if not, bake a new one, put it into the planStore and return it. static FftPlan* getPlan(Size _dft_size, int _src_step, int _dst_step, int _flags, FftType _type); // remove a single plan from the store // return true if the plan is successfully removed // else static bool removePlan(clAmdFftPlanHandle ); }; } } auto_ptr<PlanCache> PlanCache::planCache; void cv::ocl::fft_setup() { PlanCache& pCache = *PlanCache::getPlanCache(); if(pCache.started) { return; } pCache.setupData = new clAmdFftSetupData; openCLSafeCall(clAmdFftInitSetupData( pCache.setupData )); pCache.started = true; } void cv::ocl::fft_teardown() { PlanCache& pCache = *PlanCache::getPlanCache(); if(!pCache.started) { return; } delete pCache.setupData; for(size_t i = 0; i < pCache.planStore.size(); i ++) { delete pCache.planStore[i]; } pCache.planStore.clear(); openCLSafeCall( clAmdFftTeardown( ) ); pCache.started = false; } // bake a new plan cv::ocl::FftPlan::FftPlan(Size _dft_size, int _src_step, int _dst_step, int _flags, FftType _type) : plHandle(0), dft_size(_dft_size), src_step(_src_step), dst_step(_dst_step), flags(_flags), type(_type) { fft_setup(); bool is_1d_input = (_dft_size.height == 1); int is_row_dft = flags & DFT_ROWS; int is_scaled_dft = flags & DFT_SCALE; int is_inverse = flags & DFT_INVERSE; //clAmdFftResultLocation place; clAmdFftLayout inLayout; clAmdFftLayout outLayout; clAmdFftDim dim = is_1d_input || is_row_dft ? CLFFT_1D : CLFFT_2D; size_t batchSize = is_row_dft ? dft_size.height : 1; size_t clLengthsIn[ 3 ] = {1, 1, 1}; size_t clStridesIn[ 3 ] = {1, 1, 1}; //size_t clLengthsOut[ 3 ] = {1, 1, 1}; size_t clStridesOut[ 3 ] = {1, 1, 1}; clLengthsIn[0] = dft_size.width; clLengthsIn[1] = is_row_dft ? 1 : dft_size.height; clStridesIn[0] = 1; clStridesOut[0] = 1; switch(_type) { case C2C: inLayout = CLFFT_COMPLEX_INTERLEAVED; outLayout = CLFFT_COMPLEX_INTERLEAVED; clStridesIn[1] = src_step / sizeof(std::complex<float>); clStridesOut[1] = clStridesIn[1]; break; case R2C: inLayout = CLFFT_REAL; outLayout = CLFFT_HERMITIAN_INTERLEAVED; clStridesIn[1] = src_step / sizeof(float); clStridesOut[1] = dst_step / sizeof(std::complex<float>); break; case C2R: inLayout = CLFFT_HERMITIAN_INTERLEAVED; outLayout = CLFFT_REAL; clStridesIn[1] = src_step / sizeof(std::complex<float>); clStridesOut[1] = dst_step / sizeof(float); break; default: //std::runtime_error("does not support this convertion!"); cout << "Does not support this convertion!" << endl; throw exception(); break; } clStridesIn[2] = is_row_dft ? clStridesIn[1] : dft_size.width * clStridesIn[1]; clStridesOut[2] = is_row_dft ? clStridesOut[1] : dft_size.width * clStridesOut[1]; openCLSafeCall( clAmdFftCreateDefaultPlan( &plHandle, Context::getContext()->impl->clContext, dim, clLengthsIn ) ); openCLSafeCall( clAmdFftSetResultLocation( plHandle, CLFFT_OUTOFPLACE ) ); openCLSafeCall( clAmdFftSetLayout( plHandle, inLayout, outLayout ) ); openCLSafeCall( clAmdFftSetPlanBatchSize( plHandle, batchSize ) ); openCLSafeCall( clAmdFftSetPlanInStride ( plHandle, dim, clStridesIn ) ); openCLSafeCall( clAmdFftSetPlanOutStride ( plHandle, dim, clStridesOut ) ); openCLSafeCall( clAmdFftSetPlanDistance ( plHandle, clStridesIn[ dim ], clStridesOut[ dim ]) ); float scale_ = is_scaled_dft ? 1.f / _dft_size.area() : 1.f; openCLSafeCall( clAmdFftSetPlanScale ( plHandle, is_inverse ? CLFFT_BACKWARD : CLFFT_FORWARD, scale_ ) ); //ready to bake openCLSafeCall( clAmdFftBakePlan( plHandle, 1, &(Context::getContext()->impl->clCmdQueue), NULL, NULL ) ); } cv::ocl::FftPlan::~FftPlan() { openCLSafeCall( clAmdFftDestroyPlan( &plHandle ) ); } cv::ocl::PlanCache::PlanCache() : started(false), planStore(vector<cv::ocl::FftPlan *>()), setupData(NULL) { } cv::ocl::PlanCache::~PlanCache() { fft_teardown(); } FftPlan* cv::ocl::PlanCache::getPlan(Size _dft_size, int _src_step, int _dst_step, int _flags, FftType _type) { PlanCache& pCache = *PlanCache::getPlanCache(); vector<FftPlan *>& pStore = pCache.planStore; // go through search for(size_t i = 0; i < pStore.size(); i ++) { FftPlan *plan = pStore[i]; if( plan->dft_size.width == _dft_size.width && plan->dft_size.height == _dft_size.height && plan->flags == _flags && plan->src_step == _src_step && plan->dst_step == _dst_step && plan->type == _type ) { return plan; } } // no baked plan is found FftPlan *newPlan = new FftPlan(_dft_size, _src_step, _dst_step, _flags, _type); pStore.push_back(newPlan); return newPlan; } bool cv::ocl::PlanCache::removePlan(clAmdFftPlanHandle plHandle) { PlanCache& pCache = *PlanCache::getPlanCache(); vector<FftPlan *>& pStore = pCache.planStore; for(size_t i = 0; i < pStore.size(); i ++) { if(pStore[i]->getPlanHandle() == plHandle) { pStore.erase(pStore.begin() + i); delete pStore[i]; return true; } } return false; } void cv::ocl::dft(const oclMat &src, oclMat &dst, Size dft_size, int flags) { if(dft_size == Size(0, 0)) { dft_size = src.size(); } // check if the given dft size is of optimal dft size CV_Assert(dft_size.area() == getOptimalDFTSize(dft_size.area())); // the two flags are not compatible CV_Assert( !((flags & DFT_SCALE) && (flags & DFT_ROWS)) ); // similar assertions with cuda module CV_Assert(src.type() == CV_32F || src.type() == CV_32FC2); //bool is_1d_input = (src.rows == 1); //int is_row_dft = flags & DFT_ROWS; //int is_scaled_dft = flags & DFT_SCALE; int is_inverse = flags & DFT_INVERSE; bool is_complex_input = src.channels() == 2; bool is_complex_output = !(flags & DFT_REAL_OUTPUT); // We don't support real-to-real transform CV_Assert(is_complex_input || is_complex_output); FftType type = (FftType)(is_complex_input << 0 | is_complex_output << 1); switch(type) { case C2C: dst.create(src.rows, src.cols, CV_32FC2); break; case R2C: dst.create(src.rows, src.cols / 2 + 1, CV_32FC2); break; case C2R: CV_Assert(dft_size.width / 2 + 1 == src.cols && dft_size.height == src.rows); dst.create(src.rows, dft_size.width, CV_32FC1); break; default: //std::runtime_error("does not support this convertion!"); cout << "Does not support this convertion!" << endl; throw exception(); break; } clAmdFftPlanHandle plHandle = PlanCache::getPlan(dft_size, src.step, dst.step, flags, type)->getPlanHandle(); //get the buffersize size_t buffersize = 0; openCLSafeCall( clAmdFftGetTmpBufSize(plHandle, &buffersize ) ); //allocate the intermediate buffer // TODO, bind this with the current FftPlan cl_mem clMedBuffer = NULL; if (buffersize) { cl_int medstatus; clMedBuffer = clCreateBuffer ( src.clCxt->impl->clContext, CL_MEM_READ_WRITE, buffersize, 0, &medstatus); openCLSafeCall( medstatus ); } openCLSafeCall( clAmdFftEnqueueTransform( plHandle, is_inverse ? CLFFT_BACKWARD : CLFFT_FORWARD, 1, &src.clCxt->impl->clCmdQueue, 0, NULL, NULL, (cl_mem *)&src.data, (cl_mem *)&dst.data, clMedBuffer ) ); openCLSafeCall( clFinish(src.clCxt->impl->clCmdQueue) ); if(clMedBuffer) { openCLFree(clMedBuffer); } //fft_teardown(); } #endif <|endoftext|>
<commit_before>#include <Game.hpp> int main(int argc, char* argv[]); int main(int argc, char* argv[]){ if (argc <= 1) { Game game; game.launch(); } else{ Game game("res/", std::string(argv[1]) + '/', "ducks/"); game.launch(); } return 0; } <commit_msg>adding --version argument<commit_after>#include <Game.hpp> #include <string> int main(int argc, char* argv[]); int main(int argc, char* argv[]){ if (argc <= 1) { Game game; game.launch(); } else{ if (std::string(argv[1]) == "--version") { std::cout << "PapraGame v0.3" << std::endl << "Copyright c 2016 TiWinDeTea (https://github.com/TiWinDeTea)" << std::endl << std::endl << "Covered Software is provided under this License on an \"as is\"" << std::endl << "basis, without warranty of any kind, either expressed, implied, or" << std::endl << "statutory, including, without limitation, warranties that the" << std::endl << "Covered Software is free of defects, merchantable, fit for a" << std::endl << "particular purpose or non-infringing. The entire risk as to the" << std::endl << "quality and performance of the Covered Software is with You." << std::endl << "Should any Covered Software prove defective in any respect, You" << std::endl << "(not any Contributor) assume the cost of any necessary servicing," << std::endl << "repair, or correction. This disclaimer of warranty constitutes an" << std::endl << "essential part of this License. No use of any Covered Software is" << std::endl << "authorized under this License except under this disclaimer." << std::endl << std::endl << "Game currently under development" << std::endl; } else{ Game game("res/", std::string(argv[1]) + '/', "ducks/"); game.launch(); } } return 0; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Solutions Commercial License Agreement provided ** with the Software or, alternatively, in accordance with the terms ** contained in a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** Please note Third Party Software included with Qt Solutions may impose ** additional restrictions and it is the user's responsibility to ensure ** that they have met the licensing requirements of the GPL, LGPL, or Qt ** Solutions Commercial license and the relevant license of the Third ** Party Software they are using. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtDeclarative/qdeclarativeextensionplugin.h> #include <QtDeclarative/qdeclarative.h> #include "qdeclarativehapticseffect.h" #include "qdeclarativefileeffect.h" #include "qdeclarativethemeeffect.h" #include "qdeclarativefeedback.h" /*! \qmlclass Feedback \brief The Feedback object defines a number of constants \ingroup qml-feedback-api This element is part of the \bold{QtMobility.feedback 1.1} module. There are several predefined enumerations and constants provided in this object. \snippet doc/src/snippets/declarative/declarative-feedback.qml Base Effect \sa FileEffect, ThemeEffect, HapticsEffect, {QFeedbackEffect} */ /*! \qmlclass FeedbackEffect QFeedbackEffect \brief The FeedbackEffect element is the base class for all feedback effects. \ingroup qml-feedback-api This element is part of the \bold{QtMobility.feedback 1.1} module. You can't create one of these elements directly, but several other elements inherit the methods and properties of these elements. \snippet doc/src/snippets/declarative/declarative-feedback.qml Base Effect \sa FileEffect, ThemeEffect, HapticsEffect, {QFeedbackEffect} */ /*! \qmlproperty int FeedbackEffect::duration The duration of the effect, in milliseconds. This is 0 for effects of unknown duration, or Feedback.Infinite for effects that don't stop. */ /*! \qmlproperty url FeedbackEffect::state This is the current state of the effect. It is one of: \list \o \l Feedback.Stopped \o \l Feedback.Loading \o \l Feedback.Running \o \l Feedback.Paused \endlist */ /*! \qmlmethod FeedbackEffect::start() Start playback of this effect. */ /*! \qmlmethod FeedbackEffect::stop() Stops playback of this effect. */ /*! \qmlmethod FeedbackEffect::pause() Pause playback of this effect. Not all devices or effects can pause feedback playback. */ /*! \qmlsignal FeedbackEffect::error(Feedback::ErrorType) This signal is emitted when an error occurs during playback of an effect. */ /*! \qmlclass FileEffect \brief The FileEffect element represents feedback data stored in a file. \ingroup qml-feedback-api \inherits FeedbackEffect This element is part of the \bold{QtMobility.feedback 1.1} module. \snippet doc/src/snippets/declarative/declarative-feedback.qml File Effect \sa HapticsEffect, {QFeedbackActuator} */ /*! \qmlproperty bool FileEffect::running This property is true if this feedback effect is running. */ /*! \qmlproperty bool FileEffect::paused This property is true if this feedback effect is paused. */ /*! \qmlproperty bool FileEffect::loaded This property is true if this feedback effect is loaded. */ /*! \qmlproperty url FileEffect::source This property stores the url for the feedback data. */ /*! \qmlclass HapticsEffect \brief The HapticsEffect element represents a custom haptic feedback effect. \ingroup qml-feedback-api \inherits FeedbackEffect This element is part of the \bold{QtMobility.feedback 1.1} module. This class closely corresponds to the C++ \l QFeedbackHapticsEffect class. \snippet doc/src/snippets/declarative/declarative-feedback.qml Haptics Effect \sa Actuator, {QFeedbackHapticsEffect} */ /*! \qmlproperty int HapticsEffect::duration The duration of the main part of the haptics effect, in milliseconds. */ /*! \qmlproperty double HapticsEffect::intensity The intensity of the main part of the haptics effect, from 0.0 to 1.0. */ /*! \qmlproperty int HapticsEffect::attackTime The duration of the attack (fade-in) part of the haptics effect. */ /*! \qmlproperty double HapticsEffect::attackIntensity The intensity of the attack (fade-in) part of the haptics effect, from 0.0 to 1.0. */ /*! \qmlproperty int HapticsEffect::fadeTime The duration of the fade-out part of the haptics effect. */ /*! \qmlproperty double HapticsEffect::fadeIntensity The intensity of the fade-out part of the haptics effect, from 0.0 to 1.0. */ /*! \qmlproperty int HapticsEffect::period The period of the haptics effect. If the period is zero, the effect will not repeat. If it is non-zero, the effect will repeat every period milliseconds. */ /*! \qmlproperty Actuator HapticsEffect::actuator The actuator that is used for playing this effect. \sa Actuator */ /*! \qmlclass Actuator QFeedbackActuator \brief The Actuator element represents a feedback actuator. \ingroup qml-feedback-api This element is part of the \bold{QtMobility.feedback 1.1} module. The Actuator class maps directly to the QFeedbackActuator C++ class, and can be used with HapticsEffect elements. \snippet doc/src/snippets/declarative/declarative-feedback.qml Actuator \sa HapticsEffect, {QFeedbackActuator} */ /*! \qmlclass ThemeEffect \brief The ThemeEffect element represents a themed feedback effect. \ingroup qml-feedback-api This element is part of the \bold{QtMobility.feedback 1.1} module. This element is used for playing feedback effects that follow the system theme. The actual feedback might be haptic, audio or some other method. \snippet doc/src/snippets/declarative/declarative-feedback.qml Theme */ /*! \qmlproperty bool ThemeEffect::supported This property is true if the system supports themed feedback effects. */ /*! \qmlproperty ThemeEffect ThemeEffect::effect This property holds the specific themed effect type to play. */ /*! \qmlmethod ThemeEffect::play() Call this to play the themed effect. */ class QFeedbackDeclarativeModule : public QDeclarativeExtensionPlugin { Q_OBJECT public: virtual void registerTypes(const char *uri) { Q_ASSERT(QLatin1String(uri) == QLatin1String("QtMobility.feedback")); qmlRegisterUncreatableType<QDeclarativeFeedback>("QtMobility.feedback", 1, 1, "Feedback", "Feedback is a namespace"); // It's not really qmlRegisterType<QFeedbackActuator>("QtMobility.feedback", 1, 1, "Actuator"); qmlRegisterType<QDeclarativeFileEffect>("QtMobility.feedback", 1, 1, "FileEffect"); qmlRegisterType<QDeclarativeHapticsEffect>("QtMobility.feedback", 1, 1, "HapticsEffect"); qmlRegisterType<QDeclarativeThemeEffect>("QtMobility.feedback", 1, 1, "ThemeEffect"); } }; #include "moc_qdeclarativethemeeffect.cpp" #include "moc_qdeclarativefeedback.cpp" #include "feedback.moc" Q_EXPORT_PLUGIN2(declarative_feedback, QT_PREPEND_NAMESPACE(QFeedbackDeclarativeModule)); <commit_msg>Document the enums too.<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Solutions Commercial License Agreement provided ** with the Software or, alternatively, in accordance with the terms ** contained in a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** Please note Third Party Software included with Qt Solutions may impose ** additional restrictions and it is the user's responsibility to ensure ** that they have met the licensing requirements of the GPL, LGPL, or Qt ** Solutions Commercial license and the relevant license of the Third ** Party Software they are using. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtDeclarative/qdeclarativeextensionplugin.h> #include <QtDeclarative/qdeclarative.h> #include "qdeclarativehapticseffect.h" #include "qdeclarativefileeffect.h" #include "qdeclarativethemeeffect.h" #include "qdeclarativefeedback.h" /*! \qmlclass Feedback \brief The Feedback object defines a number of constants \ingroup qml-feedback-api This element is part of the \bold{QtMobility.feedback 1.1} module. There are several predefined enumerations and constants provided in this object. \snippet doc/src/snippets/declarative/declarative-feedback.qml Base Effect \sa FileEffect, ThemeEffect, HapticsEffect, {QFeedbackEffect} */ /*! \qmlclass FeedbackEffect QFeedbackEffect \brief The FeedbackEffect element is the base class for all feedback effects. \ingroup qml-feedback-api This element is part of the \bold{QtMobility.feedback 1.1} module. You can't create one of these elements directly, but several other elements inherit the methods and properties of these elements. \snippet doc/src/snippets/declarative/declarative-feedback.qml Base Effect \sa FileEffect, ThemeEffect, HapticsEffect, {QFeedbackEffect} */ /*! \qmlproperty int FeedbackEffect::duration The duration of the effect, in milliseconds. This is 0 for effects of unknown duration, or Feedback.Infinite for effects that don't stop. */ /*! \qmlproperty FeedbackEffect::State FeedbackEffect::state This is the current state of the effect. It is one of: \list \o \l Feedback.Stopped - the effect is not playing \o \l Feedback.Loading - the effect is being loaded \o \l Feedback.Running - the effect is playing \o \l Feedback.Paused - the effect was being played, but is now paused. \endlist */ /*! \qmlmethod FeedbackEffect::start() Start playback of this effect. */ /*! \qmlmethod FeedbackEffect::stop() Stops playback of this effect. */ /*! \qmlmethod FeedbackEffect::pause() Pause playback of this effect. Not all devices or effects can pause feedback playback. */ /*! \qmlsignal FeedbackEffect::error(Feedback::ErrorType) This signal is emitted when an error occurs during playback of an effect. The error is one of the following values: \list \o \l Feedback.UnknownError - An unknown error occurred \o \l Feedback.DeviceBusy - The device resource is already being used. \endlist \sa QFeedbackEffect::ErrorType */ /*! \qmlproper QFeedbackEffect::ErrorType This enum describes the possible errors happening on the effect. \value UnknownError An unknown error occurred. \value DeviceBusy The feedback could not start because the device is busy. \sa error() */ /*! \qmlclass FileEffect \brief The FileEffect element represents feedback data stored in a file. \ingroup qml-feedback-api \inherits FeedbackEffect This element is part of the \bold{QtMobility.feedback 1.1} module. \snippet doc/src/snippets/declarative/declarative-feedback.qml File Effect \sa HapticsEffect, {QFeedbackActuator} */ /*! \qmlproperty bool FileEffect::running This property is true if this feedback effect is running. */ /*! \qmlproperty bool FileEffect::paused This property is true if this feedback effect is paused. */ /*! \qmlproperty bool FileEffect::loaded This property is true if this feedback effect is loaded. */ /*! \qmlproperty url FileEffect::source This property stores the url for the feedback data. */ /*! \qmlclass HapticsEffect \brief The HapticsEffect element represents a custom haptic feedback effect. \ingroup qml-feedback-api \inherits FeedbackEffect This element is part of the \bold{QtMobility.feedback 1.1} module. This class closely corresponds to the C++ \l QFeedbackHapticsEffect class. \snippet doc/src/snippets/declarative/declarative-feedback.qml Haptics Effect \sa Actuator, {QFeedbackHapticsEffect} */ /*! \qmlproperty int HapticsEffect::duration The duration of the main part of the haptics effect, in milliseconds. */ /*! \qmlproperty double HapticsEffect::intensity The intensity of the main part of the haptics effect, from 0.0 to 1.0. */ /*! \qmlproperty int HapticsEffect::attackTime The duration of the attack (fade-in) part of the haptics effect. */ /*! \qmlproperty double HapticsEffect::attackIntensity The intensity of the attack (fade-in) part of the haptics effect, from 0.0 to 1.0. */ /*! \qmlproperty int HapticsEffect::fadeTime The duration of the fade-out part of the haptics effect. */ /*! \qmlproperty double HapticsEffect::fadeIntensity The intensity of the fade-out part of the haptics effect, from 0.0 to 1.0. */ /*! \qmlproperty int HapticsEffect::period The period of the haptics effect. If the period is zero, the effect will not repeat. If it is non-zero, the effect will repeat every period milliseconds. */ /*! \qmlproperty Actuator HapticsEffect::actuator The actuator that is used for playing this effect. \sa Actuator */ /*! \qmlclass Actuator QFeedbackActuator \brief The Actuator element represents a feedback actuator. \ingroup qml-feedback-api This element is part of the \bold{QtMobility.feedback 1.1} module. The Actuator class maps directly to the QFeedbackActuator C++ class, and can be used with HapticsEffect elements. \snippet doc/src/snippets/declarative/declarative-feedback.qml Actuator \sa HapticsEffect, {QFeedbackActuator} */ /*! \qmlclass ThemeEffect \brief The ThemeEffect element represents a themed feedback effect. \ingroup qml-feedback-api This element is part of the \bold{QtMobility.feedback 1.1} module. This element is used for playing feedback effects that follow the system theme. The actual feedback might be haptic, audio or some other method. \snippet doc/src/snippets/declarative/declarative-feedback.qml Theme */ /*! \qmlproperty bool ThemeEffect::supported This property is true if the system supports themed feedback effects. */ /*! \qmlproperty ThemeEffect ThemeEffect::effect This property holds the specific themed effect type to play. It is one of: \list \o \l ThemeEffect.Basic - Generic feedback. \o \l ThemeEffect.Sensitive - Generic sensitive feedback. \o \l ThemeEffect.BasicButton - Feedback for interacting with a button (e.g. pressing). \o \l ThemeEffect.SensitiveButton - Sensitive feedback for interacting with a button (e.g. auto repeat). \o \l ThemeEffect.BasicKeypad - Feedback for interacting with a keypad button. \o \l ThemeEffect.SensitiveKeypad - Sensitive feedback for interacting with a keypad button. \o \l ThemeEffect.BasicSlider - Feedback for moving a slider. \o \l ThemeEffect.SensitiveSlider - Sensitive feedback for moving a slider. \o \l ThemeEffect.BasicItem - Feedback when interacting with a list or grid item. \o \l ThemeEffect.SensitiveItem - Sensitive feedback when interacting with a list or grid item. \o \l ThemeEffect.ItemScroll - Feedback when scrolling a list or grid item view. \o \l ThemeEffect.ItemPick - Feedback when selecting an item to move in a list or grid view. \o \l ThemeEffect.ItemDrop - Feedback when dropping an item in a list or grid view. \o \l ThemeEffect.ItemMoveOver - Feedback when moving an item in a list or grid view. \o \l ThemeEffect.BounceEffect - Feedback for a bounce effect. \o \l ThemeEffect.CheckBox - Feedback for selecting a checkbox. \o \l ThemeEffect.MultipleCheckBox - Feedback for selecting checkboxes of multiple items. \o \l ThemeEffect.Editor - Feedback for interacting with an editor. \o \l ThemeEffect.TextSelection - Feedback for selecting text. \o \l ThemeEffect.BlankSelection - Feedback for a blank selection. \o \l ThemeEffect.LineSelection - Feedback for selecting a line. \o \l ThemeEffect.EmptyLineSelection - Feedback for selecting an empty line. \o \l ThemeEffect.PopUp - Generic feedback for interacting with a popup. \o \l ThemeEffect.PopupOpen - Generic feedback when a popup opens. \o \l ThemeEffect.PopupClose - Generic feedback when a popup closes. \o \l ThemeEffect.Flick - Generic feedback when starting a flick gesture. \o \l ThemeEffect.StopFlick - Generic feedback when stopping a flick. \o \l ThemeEffect.MultiPointTouchActivate - Generic feedback when a touch gesture with more than one point is started. \o \l ThemeEffect.RotateStep - Feedback when rotating using a gesture. \o \l ThemeEffect.LongPress - Feedback for a long press (or tap and hold) gesture. \o \l ThemeEffect.PositiveTacticon - Generic feedback for notification of a successful operation. \o \l ThemeEffect.NeutralTacticon - Generic feedback for notification. \o \l ThemeEffect.NegativeTacticon - Generic feedback for notification of a failed operation. \endlist \sa QFeedbackEffect::ThemeEffect */ /*! \qmlmethod ThemeEffect::play() Call this to play the themed effect. */ class QFeedbackDeclarativeModule : public QDeclarativeExtensionPlugin { Q_OBJECT public: virtual void registerTypes(const char *uri) { Q_ASSERT(QLatin1String(uri) == QLatin1String("QtMobility.feedback")); qmlRegisterUncreatableType<QDeclarativeFeedback>("QtMobility.feedback", 1, 1, "Feedback", "Feedback is a namespace"); // It's not really qmlRegisterType<QFeedbackActuator>("QtMobility.feedback", 1, 1, "Actuator"); qmlRegisterType<QDeclarativeFileEffect>("QtMobility.feedback", 1, 1, "FileEffect"); qmlRegisterType<QDeclarativeHapticsEffect>("QtMobility.feedback", 1, 1, "HapticsEffect"); qmlRegisterType<QDeclarativeThemeEffect>("QtMobility.feedback", 1, 1, "ThemeEffect"); } }; #include "moc_qdeclarativethemeeffect.cpp" #include "moc_qdeclarativefeedback.cpp" #include "feedback.moc" Q_EXPORT_PLUGIN2(declarative_feedback, QT_PREPEND_NAMESPACE(QFeedbackDeclarativeModule)); <|endoftext|>
<commit_before>// builds all boost.asio source as a separate compilation unit #include <boost/version.hpp> #ifndef BOOST_ASIO_SOURCE #define BOOST_ASIO_SOURCE #endif #if BOOST_VERSION >= 104500 #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HEADER_ONLY) # error Do not compile Asio library source with BOOST_ASIO_HEADER_ONLY defined #endif #include <boost/asio/impl/error.ipp> #include <boost/asio/impl/io_service.ipp> #include <boost/asio/impl/serial_port_base.ipp> #include <boost/asio/detail/impl/descriptor_ops.ipp> #include <boost/asio/detail/impl/dev_poll_reactor.ipp> #include <boost/asio/detail/impl/epoll_reactor.ipp> #include <boost/asio/detail/impl/eventfd_select_interrupter.ipp> #if BOOST_VERSION >= 104700 #include <boost/asio/detail/impl/handler_tracking.ipp> #include <boost/asio/detail/impl/signal_set_service.ipp> #include <boost/asio/detail/impl/win_static_mutex.ipp> #endif #include <boost/asio/detail/impl/kqueue_reactor.ipp> #include <boost/asio/detail/impl/pipe_select_interrupter.ipp> #include <boost/asio/detail/impl/posix_event.ipp> #include <boost/asio/detail/impl/posix_mutex.ipp> #include <boost/asio/detail/impl/posix_thread.ipp> #include <boost/asio/detail/impl/posix_tss_ptr.ipp> #include <boost/asio/detail/impl/reactive_descriptor_service.ipp> #include <boost/asio/detail/impl/reactive_serial_port_service.ipp> #include <boost/asio/detail/impl/reactive_socket_service_base.ipp> #include <boost/asio/detail/impl/resolver_service_base.ipp> #include <boost/asio/detail/impl/select_reactor.ipp> #include <boost/asio/detail/impl/service_registry.ipp> #include <boost/asio/detail/impl/socket_ops.ipp> #include <boost/asio/detail/impl/socket_select_interrupter.ipp> #include <boost/asio/detail/impl/strand_service.ipp> #include <boost/asio/detail/impl/task_io_service.ipp> #include <boost/asio/detail/impl/throw_error.ipp> //#include <boost/asio/detail/impl/timer_queue.ipp> #include <boost/asio/detail/impl/timer_queue_set.ipp> #include <boost/asio/detail/impl/win_iocp_handle_service.ipp> #include <boost/asio/detail/impl/win_iocp_io_service.ipp> #include <boost/asio/detail/impl/win_iocp_serial_port_service.ipp> #include <boost/asio/detail/impl/win_iocp_socket_service_base.ipp> #include <boost/asio/detail/impl/win_event.ipp> #include <boost/asio/detail/impl/win_mutex.ipp> #include <boost/asio/detail/impl/win_thread.ipp> #include <boost/asio/detail/impl/win_tss_ptr.ipp> #include <boost/asio/detail/impl/winsock_init.ipp> #include <boost/asio/ip/impl/address.ipp> #include <boost/asio/ip/impl/address_v4.ipp> #include <boost/asio/ip/impl/address_v6.ipp> #include <boost/asio/ip/impl/host_name.ipp> #include <boost/asio/ip/detail/impl/endpoint.ipp> #include <boost/asio/local/detail/impl/endpoint.ipp> #if BOOST_VERSION >= 104900 #include <boost/asio/detail/impl/win_object_handle_service.ipp> #endif #elif BOOST_VERSION >= 104400 #include <boost/asio/impl/src.cpp> #endif <commit_msg>attempt to make separate compilation of boost.asio work on windows, mac and linux without pulling in a dependency on boost.date_time. This is a hack until boost.asio has an option to disable use of boost.date_time<commit_after>// builds all boost.asio source as a separate compilation unit #include <boost/version.hpp> #ifndef BOOST_ASIO_SOURCE #define BOOST_ASIO_SOURCE #endif #ifdef _MSC_VER // on windows; including timer_queue.hpp results in an // actual link-time dependency on boost.date_time, even // though it's never referenced. So, avoid that on windows. // on Mac OS X and Linux, not including it results in // missing symbols. For some reason, this current setup // works, at least across windows, Linux and Mac OS X. // In the future this hack can be fixed by disabling // use of boost.date_time in boost.asio #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HEADER_ONLY) # error Do not compile Asio library source with BOOST_ASIO_HEADER_ONLY defined #endif #include <boost/asio/impl/error.ipp> #include <boost/asio/impl/io_service.ipp> #include <boost/asio/impl/serial_port_base.ipp> #include <boost/asio/detail/impl/descriptor_ops.ipp> #include <boost/asio/detail/impl/dev_poll_reactor.ipp> #include <boost/asio/detail/impl/epoll_reactor.ipp> #include <boost/asio/detail/impl/eventfd_select_interrupter.ipp> #if BOOST_VERSION >= 104700 #include <boost/asio/detail/impl/handler_tracking.ipp> #include <boost/asio/detail/impl/signal_set_service.ipp> #include <boost/asio/detail/impl/win_static_mutex.ipp> #endif #include <boost/asio/detail/impl/kqueue_reactor.ipp> #include <boost/asio/detail/impl/pipe_select_interrupter.ipp> #include <boost/asio/detail/impl/posix_event.ipp> #include <boost/asio/detail/impl/posix_mutex.ipp> #include <boost/asio/detail/impl/posix_thread.ipp> #include <boost/asio/detail/impl/posix_tss_ptr.ipp> #include <boost/asio/detail/impl/reactive_descriptor_service.ipp> #include <boost/asio/detail/impl/reactive_serial_port_service.ipp> #include <boost/asio/detail/impl/reactive_socket_service_base.ipp> #include <boost/asio/detail/impl/resolver_service_base.ipp> #include <boost/asio/detail/impl/select_reactor.ipp> #include <boost/asio/detail/impl/service_registry.ipp> #include <boost/asio/detail/impl/socket_ops.ipp> #include <boost/asio/detail/impl/socket_select_interrupter.ipp> #include <boost/asio/detail/impl/strand_service.ipp> #include <boost/asio/detail/impl/task_io_service.ipp> #include <boost/asio/detail/impl/throw_error.ipp> //#include <boost/asio/detail/impl/timer_queue.ipp> #include <boost/asio/detail/impl/timer_queue_set.ipp> #include <boost/asio/detail/impl/win_iocp_handle_service.ipp> #include <boost/asio/detail/impl/win_iocp_io_service.ipp> #include <boost/asio/detail/impl/win_iocp_serial_port_service.ipp> #include <boost/asio/detail/impl/win_iocp_socket_service_base.ipp> #include <boost/asio/detail/impl/win_event.ipp> #include <boost/asio/detail/impl/win_mutex.ipp> #include <boost/asio/detail/impl/win_thread.ipp> #include <boost/asio/detail/impl/win_tss_ptr.ipp> #include <boost/asio/detail/impl/winsock_init.ipp> #include <boost/asio/ip/impl/address.ipp> #include <boost/asio/ip/impl/address_v4.ipp> #include <boost/asio/ip/impl/address_v6.ipp> #include <boost/asio/ip/impl/host_name.ipp> #include <boost/asio/ip/detail/impl/endpoint.ipp> #include <boost/asio/local/detail/impl/endpoint.ipp> #if BOOST_VERSION >= 104900 #include <boost/asio/detail/impl/win_object_handle_service.ipp> #endif #else // _MSC_VER #if BOOST_VERSION >= 104500 #include <boost/asio/impl/src.hpp> #elif BOOST_VERSION >= 104400 #include <boost/asio/impl/src.cpp> #endif #endif <|endoftext|>
<commit_before>#ifdef __APPLE__ #include <SDL2/SDL.h> #elif _WIN32 #define SDL_MAIN_HANDLED #include <SDL.h> #include <stdio.h> #endif #define SCREEN_WIDTH 400 #define SCREEN_HEIGHT 225 #define GAME_WIDTH 256 #define GAME_HEIGHT 144 int main(int argc, char* argv[]) { SDL_version compiled; SDL_version linked; SDL_VERSION(&compiled); SDL_GetVersion(&linked); printf("We compiled against SDL version %d.%d.%d ...\n", compiled.major, compiled.minor, compiled.patch); printf("We are linking against SDL version %d.%d.%d.\n", linked.major, linked.minor, linked.patch); SDL_Init(SDL_INIT_VIDEO); SDL_Window *window = SDL_CreateWindow( "unamed-dungeon-crawler", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH*2, SCREEN_HEIGHT*2, 0 ); SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0); SDL_Texture *texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, SCREEN_WIDTH, SCREEN_HEIGHT); // SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear"); // make the scaled rendering look smoother. // SDL_RenderSetLogicalSize(renderer, SCREEN_WIDTH*4, SCREEN_HEIGHT*4); //SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "ERROR", SDL_GetError(), window); SDL_Surface *screen = SDL_CreateRGBSurface(0, SCREEN_WIDTH, SCREEN_HEIGHT, 32, 0, 0, 0, 0); SDL_Surface *game = SDL_CreateRGBSurface(0, GAME_WIDTH, GAME_HEIGHT, 32, 0, 0, 0, 0); SDL_Surface *testSurface = SDL_LoadBMP("test.bmp"); SDL_Surface *borderSurface = SDL_LoadBMP("border.bmp"); bool quit = false; SDL_Event e; //SDL_Rect pos = { 0,40,100,100 }; while (!quit) { while (SDL_PollEvent(&e) != 0) { const Uint8 *state = SDL_GetKeyboardState(NULL); if (e.type == SDL_QUIT) { quit = true; } if (state[SDL_SCANCODE_LEFT]) { //DestR.x -= 1; } if (state[SDL_SCANCODE_RIGHT]) { //DestR.x += 1; } } //clear screen surface SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 255, 0, 0)); SDL_FillRect(game, NULL, SDL_MapRGB(screen->format, 0, 255, 0)); SDL_BlitSurface(testSurface, 0, game, NULL); SDL_BlitSurface(borderSurface, 0, screen, 0); SDL_Rect location = { 72,40,100,100 }; SDL_BlitSurface(game, 0, screen, &location); SDL_UpdateTexture(texture, NULL, screen->pixels, screen->pitch); SDL_RenderClear(renderer); SDL_RenderCopy(renderer, texture, 0, 0); SDL_RenderPresent(renderer); SDL_Delay(16); } SDL_FreeSurface(testSurface); SDL_DestroyWindow(window); SDL_Quit(); return 0; } <commit_msg>Indie<commit_after>#ifdef __APPLE__ #include <SDL2/SDL.h> #elif _WIN32 #define SDL_MAIN_HANDLED #include <SDL.h> #include <stdio.h> #endif #define SCREEN_WIDTH 400 #define SCREEN_HEIGHT 225 #define GAME_WIDTH 256 #define GAME_HEIGHT 144 int main(int argc, char* argv[]) { SDL_version compiled; SDL_version linked; SDL_VERSION(&compiled); SDL_GetVersion(&linked); printf("We compiled against SDL version %d.%d.%d ...\n", compiled.major, compiled.minor, compiled.patch); printf("We are linking against SDL version %d.%d.%d.\n", linked.major, linked.minor, linked.patch); SDL_Init(SDL_INIT_VIDEO); SDL_Window *window = SDL_CreateWindow( "unamed-dungeon-crawler", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH*2, SCREEN_HEIGHT*2, 0 ); SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0); SDL_Texture *texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, SCREEN_WIDTH, SCREEN_HEIGHT); // SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear"); // make the scaled rendering look smoother. // SDL_RenderSetLogicalSize(renderer, SCREEN_WIDTH*4, SCREEN_HEIGHT*4); //SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "ERROR", SDL_GetError(), window); SDL_Surface *screen = SDL_CreateRGBSurface(0, SCREEN_WIDTH, SCREEN_HEIGHT, 32, 0, 0, 0, 0); SDL_Surface *game = SDL_CreateRGBSurface(0, GAME_WIDTH, GAME_HEIGHT, 32, 0, 0, 0, 0); SDL_Surface *testSurface = SDL_LoadBMP("test.bmp"); SDL_Surface *borderSurface = SDL_LoadBMP("border.bmp"); SDL_Surface *tile00Surface = SDL_LoadBMP("tile00.bmp"); SDL_Surface *tile01Surface = SDL_LoadBMP("tile01.bmp"); bool quit = false; SDL_Event e; //SDL_Rect pos = { 0,40,100,100 }; int tilesArray[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, }; int arrayWidth = 16; int arrayHeight = 9; while (!quit) { while (SDL_PollEvent(&e) != 0) { const Uint8 *state = SDL_GetKeyboardState(NULL); if (e.type == SDL_QUIT) { quit = true; } if (state[SDL_SCANCODE_LEFT]) { //DestR.x -= 1; } if (state[SDL_SCANCODE_RIGHT]) { //DestR.x += 1; } } //clear screen surface SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 255, 0, 0)); SDL_FillRect(game, NULL, SDL_MapRGB(screen->format, 0, 255, 0)); //render tiles for (size_t i = 0; i < arrayWidth * arrayHeight; i++) { int x = i % arrayWidth; int y = (i / arrayWidth) % arrayHeight; SDL_Rect pos = { x * 16, y * 16, 16, 16 }; //printf("x: %i , y: %i\n", x, y); if (tilesArray[i] == 0) { SDL_BlitSurface(tile00Surface, NULL, game, &pos); } else if (tilesArray[i] == 1) { SDL_BlitSurface(tile01Surface, NULL, game, &pos); } } //SDL_BlitSurface(testSurface, 0, game, NULL); SDL_BlitSurface(borderSurface, 0, screen, 0); SDL_Rect location = { 72,40,100,100 }; SDL_BlitSurface(game, 0, screen, &location); SDL_UpdateTexture(texture, NULL, screen->pixels, screen->pitch); SDL_RenderClear(renderer); SDL_RenderCopy(renderer, texture, 0, 0); SDL_RenderPresent(renderer); SDL_Delay(16); } SDL_FreeSurface(testSurface); SDL_DestroyWindow(window); SDL_Quit(); return 0; } <|endoftext|>
<commit_before>#include <AppConfig.h> // #include <modules/juce_audio_basics/juce_audio_basics.h> // #include <modules/juce_audio_devices/juce_audio_devices.h> // #include <modules/juce_audio_formats/juce_audio_formats.h> // #include <modules/juce_audio_processors/juce_audio_processors.h> #include <modules/juce_core/juce_core.h> // #include <modules/juce_cryptography/juce_cryptography.h> // #include <modules/juce_data_structures/juce_data_structures.h> // #include <modules/juce_events/juce_events.h> // #include <modules/juce_graphics/juce_graphics.h> #include <modules/juce_gui_basics/juce_gui_basics.h> // #include <modules/juce_gui_extra/juce_gui_extra.h> // #include <modules/juce_opengl/juce_opengl.h> // #include <modules/juce_video/juce_video.h> #include <base/base.hpp> using namespace juce; using namespace granite; namespace ProjectInfo { const char* const projectName = "Kiwano"; const char* const versionString = "0.1"; const int versionNumber = 0x10000; } class playlist : public Component, public FileDragAndDropTarget { struct playlistModel : public ListBoxModel { StringArray entries; int getNumRows() override { return entries.size(); } void paintListBoxItem(int rowNumber, Graphics& g, int width, int height, bool rowIsSelected) override { if (rowIsSelected) g.fillAll(Colours::lightblue); g.setColour(Colours::black); g.setFont(height * 0.7f); g.drawText(entries[rowNumber], 5, 0, width, height, Justification::centredLeft, true); } }; ListBox box; playlistModel model; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(playlist); public: playlist() : box("playlist-box", nullptr) { setName("playlist"); box.setModel(&model); box.setMultipleSelectionEnabled(true); addAndMakeVisible(box); } void resized() override { box.setBounds(getLocalBounds().reduced(8)); } bool isInterestedInFileDrag(const StringArray& /*files*/) override { return true; } void fileDragEnter(const StringArray& /*files*/, int /*x*/, int /*y*/) override { repaint(); } void fileDragMove (const StringArray& /*files*/, int /*x*/, int /*y*/) override {} void fileDragExit (const StringArray& /*files*/) override { repaint(); } void filesDropped (const StringArray& files, int /*x*/, int /*y*/) override { model.entries.addArray(files); box.updateContent(); repaint(); } }; class tabs : public TabbedComponent { public: tabs() : TabbedComponent(TabbedButtonBar::TabsAtTop) { addTab("Menus", getRandomTabBackgroundColour(), new playlist(), true); addTab("Buttons", getRandomTabBackgroundColour(), new playlist(), true); } static Colour getRandomTabBackgroundColour() { return Colour(Random::getSystemRandom().nextFloat(), 0.1f, 0.97f, 1.0f); } }; class layout : public Component { StretchableLayoutManager l; StretchableLayoutResizerBar rb; std::vector<Component *> components; public: layout(Component *c1, Component *c2) : rb(&l, 1, false) { setOpaque(true); addAndMakeVisible(rb); components.push_back(c1); components.push_back(c2); components.push_back(nullptr); l.setItemLayout(0, -0.1, -0.9, -0.5); l.setItemLayout(1, -0.1, -0.9, -0.5); } void resized() { Rectangle<int> r(getLocalBounds().reduced(4)); l.layOutComponents(components.data(), 2, r.getX(), r.getY(), r.getWidth(), r.getHeight(), true, true); } }; class KiwanoApplication : public JUCEApplication { class MainWindow : public DocumentWindow { layout l; tabs c1, c2; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(MainWindow) public: MainWindow(String name) : DocumentWindow(name, Colours::lightgrey, DocumentWindow::allButtons), l(&c1, &c2) { addAndMakeVisible(&l); setContentOwned(&l, true); setVisible(true); setSize(600, 400); l.setSize(500, 300); } void closeButtonPressed() override { JUCEApplication::getInstance()->systemRequestedQuit(); } }; ScopedPointer<MainWindow> mainWindow; public: KiwanoApplication() {} const String getApplicationName() override { return ProjectInfo::projectName; } const String getApplicationVersion() override { return ProjectInfo::versionString; } bool moreThanOneInstanceAllowed() override { return false; } void initialise(const String& commandLine) override { mainWindow = new MainWindow(getApplicationName()); } void shutdown() override { mainWindow = nullptr; } void systemRequestedQuit() override { quit(); } void anotherInstanceStarted (const String& commandLine) override { } }; START_JUCE_APPLICATION(KiwanoApplication) <commit_msg>+ layout<commit_after>#include <AppConfig.h> // #include <modules/juce_audio_basics/juce_audio_basics.h> // #include <modules/juce_audio_devices/juce_audio_devices.h> // #include <modules/juce_audio_formats/juce_audio_formats.h> // #include <modules/juce_audio_processors/juce_audio_processors.h> #include <modules/juce_core/juce_core.h> // #include <modules/juce_cryptography/juce_cryptography.h> // #include <modules/juce_data_structures/juce_data_structures.h> // #include <modules/juce_events/juce_events.h> // #include <modules/juce_graphics/juce_graphics.h> #include <modules/juce_gui_basics/juce_gui_basics.h> // #include <modules/juce_gui_extra/juce_gui_extra.h> // #include <modules/juce_opengl/juce_opengl.h> // #include <modules/juce_video/juce_video.h> #include <base/base.hpp> using namespace juce; using namespace granite; namespace ProjectInfo { const char* const projectName = "Kiwano"; const char* const versionString = "0.1"; const int versionNumber = 0x10000; } class playlist : public Component, public FileDragAndDropTarget { struct playlistModel : public ListBoxModel { StringArray entries; int getNumRows() override { return entries.size(); } void paintListBoxItem(int rowNumber, Graphics& g, int width, int height, bool rowIsSelected) override { if (rowIsSelected) g.fillAll(Colours::lightblue); g.setColour(Colours::black); g.setFont(height * 0.7f); g.drawText(entries[rowNumber], 5, 0, width, height, Justification::centredLeft, true); } }; ListBox box; playlistModel model; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(playlist); public: playlist() : box("playlist-box", nullptr) { setName("playlist"); box.setModel(&model); box.setMultipleSelectionEnabled(true); addAndMakeVisible(box); } void resized() override { box.setBounds(getLocalBounds().reduced(0)); } bool isInterestedInFileDrag(const StringArray& /*files*/) override { return true; } void fileDragEnter(const StringArray& /*files*/, int /*x*/, int /*y*/) override { repaint(); } void fileDragMove (const StringArray& /*files*/, int /*x*/, int /*y*/) override {} void fileDragExit (const StringArray& /*files*/) override { repaint(); } void filesDropped (const StringArray& files, int /*x*/, int /*y*/) override { model.entries.addArray(files); box.updateContent(); repaint(); } }; class tabs : public TabbedComponent { public: tabs() : TabbedComponent(TabbedButtonBar::TabsAtTop) { addTab("Menus", getRandomTabBackgroundColour(), new playlist(), true); addTab("Buttons", getRandomTabBackgroundColour(), new playlist(), true); } static Colour getRandomTabBackgroundColour() { return Colour(Random::getSystemRandom().nextFloat(), 0.1f, 0.97f, 1.0f); } }; class layout : public Component { StretchableLayoutManager l; StretchableLayoutResizerBar rb; std::vector<Component *> components; public: layout(Component *c1, Component *c2) : rb(&l, 1, false) { setOpaque(true); addAndMakeVisible(rb); addAndMakeVisible(c1); addAndMakeVisible(c2); components.push_back(c1); components.push_back(&rb); components.push_back(c2); components.push_back(nullptr); l.setItemLayout(0, -0.1, -0.9, -0.5); l.setItemLayout(1, 5, 5, 5); l.setItemLayout(2, -0.1, -0.9, -0.5); } void paint(Graphics &g) override { g.setColour(Colour::greyLevel(0.2f)); g.fillAll(); } void resized() { Rectangle<int> r(getLocalBounds().reduced(4)); l.layOutComponents(components.data(), 3, r.getX(), r.getY(), r.getWidth(), r.getHeight(), true, true); } }; class KiwanoApplication : public JUCEApplication { class MainWindow : public DocumentWindow { layout l; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(MainWindow) public: MainWindow(String name) : DocumentWindow(name, Colours::lightgrey, DocumentWindow::allButtons), l(new tabs(), new tabs()) { setContentOwned(&l, false); setSize(800, 600); setVisible(true); setUsingNativeTitleBar(true); setResizable(true, true); } void closeButtonPressed() override { JUCEApplication::getInstance()->systemRequestedQuit(); } }; ScopedPointer<MainWindow> mainWindow; public: KiwanoApplication() {} const String getApplicationName() override { return ProjectInfo::projectName; } const String getApplicationVersion() override { return ProjectInfo::versionString; } bool moreThanOneInstanceAllowed() override { return false; } void initialise(const String& commandLine) override { mainWindow = new MainWindow(getApplicationName()); } void shutdown() override { mainWindow = nullptr; } void systemRequestedQuit() override { quit(); } void anotherInstanceStarted (const String& commandLine) override { } }; START_JUCE_APPLICATION(KiwanoApplication) <|endoftext|>
<commit_before>#include "app-cmdline.h" #ifdef QT_GUI_LIB #include "app-gui.h" #endif extern "C" { #include "optparse.h" WARNINGS_DISABLE #include "warnp.h" WARNINGS_ENABLE } #include <ConsoleLog.h> #include <TSettings.h> #include <stdlib.h> #include <persistentmodel/persistentstore.h> #include <translator.h> int main(int argc, char *argv[]) { struct optparse *opt; int ret; // Initialize debug messages. WARNP_INIT; // Parse command-line arguments if((opt = optparse_parse(argc, argv)) == nullptr) { ret = EXIT_FAILURE; goto done; } // Should we use the gui or non-gui app? if(opt->check == 0) { #ifdef QT_GUI_LIB // Basic initialization that cannot fail. AppGui app(argc, argv, opt); // Run more complicated initialization. if(!app.initializeCore()) { ret = EXIT_FAILURE; goto done; } // If we want the GUI or have any tasks, do them. if(app.prepMainLoop()) ret = app.exec(); else ret = EXIT_SUCCESS; #else warn0("This binary does not support GUI operations"); ret = 1; goto done; #endif } else { // Basic initialization that cannot fail. AppCmdline app(argc, argv, opt); // Run more complicated initialization. if(!app.initializeCore()) { ret = EXIT_FAILURE; goto done; } // If we want have any tasks, do them. if(app.prepMainLoop()) ret = app.exec(); else ret = EXIT_SUCCESS; } done: // Clean up PersistentStore::destroy(); TSettings::destroy(); Translator::destroy(); ConsoleLog::destroy(); optparse_free(opt); return (ret); } <commit_msg>main: refactor with run_cmdline() & run_gui()<commit_after>#include "app-cmdline.h" #ifdef QT_GUI_LIB #include "app-gui.h" #endif extern "C" { #include "optparse.h" WARNINGS_DISABLE #include "warnp.h" WARNINGS_ENABLE } #include <ConsoleLog.h> #include <TSettings.h> #include <stdlib.h> #include <persistentmodel/persistentstore.h> #include <translator.h> static int run_cmdline(int argc, char *argv[], struct optparse *opt) { int ret; // Basic initialization that cannot fail. AppCmdline app(argc, argv, opt); // Run more complicated initialization. if(!app.initializeCore()) { ret = EXIT_FAILURE; goto done; } // If we want have any tasks, do them. if(app.prepMainLoop()) ret = app.exec(); else ret = EXIT_SUCCESS; done: return (ret); } static int run_gui(int argc, char *argv[], struct optparse *opt) { int ret; #ifdef QT_GUI_LIB // Basic initialization that cannot fail. AppGui app(argc, argv, opt); // Run more complicated initialization. if(!app.initializeCore()) { ret = EXIT_FAILURE; goto done; } // If we want the GUI or have any tasks, do them. if(app.prepMainLoop()) ret = app.exec(); else ret = EXIT_SUCCESS; done: #else (void)argc; (void)argv; (void)opt; warn0("This binary does not support GUI operations"); ret = 1; #endif return (ret); } int main(int argc, char *argv[]) { struct optparse *opt; int ret; // Initialize debug messages. WARNP_INIT; // Parse command-line arguments if((opt = optparse_parse(argc, argv)) == nullptr) { ret = EXIT_FAILURE; goto done; } // Should we use the gui or non-gui app? if(opt->check == 0) ret = run_gui(argc, argv, opt); else ret = run_cmdline(argc, argv, opt); done: // Clean up PersistentStore::destroy(); TSettings::destroy(); Translator::destroy(); ConsoleLog::destroy(); optparse_free(opt); return (ret); } <|endoftext|>
<commit_before>/* * MRustC - Rust Compiler * - By John Hodge (Mutabah/thePowersGang) * * main.cpp * - Compiler Entrypoint */ #include <iostream> #include <iomanip> #include <string> #include <set> #include "parse/lex.hpp" #include "parse/parseerror.hpp" #include "ast/ast.hpp" #include "ast/crate.hpp" #include <serialiser_texttree.hpp> #include <cstring> #include <main_bindings.hpp> #include "resolve/main_bindings.hpp" #include "hir/main_bindings.hpp" #include "hir_conv/main_bindings.hpp" #include "hir_typeck/main_bindings.hpp" #include "hir_expand/main_bindings.hpp" #include "mir/main_bindings.hpp" #include "expand/cfg.hpp" int g_debug_indent_level = 0; ::std::string g_cur_phase; ::std::set< ::std::string> g_debug_disable_map; void init_debug_list() { g_debug_disable_map.insert( "Parse" ); g_debug_disable_map.insert( "Expand" ); g_debug_disable_map.insert( "Resolve Use" ); g_debug_disable_map.insert( "Resolve Index" ); g_debug_disable_map.insert( "Resolve Absolute" ); g_debug_disable_map.insert( "HIR Lower" ); g_debug_disable_map.insert( "Resolve Type Aliases" ); g_debug_disable_map.insert( "Resolve Bind" ); g_debug_disable_map.insert( "Resolve UFCS paths" ); g_debug_disable_map.insert( "Constant Evaluate" ); g_debug_disable_map.insert( "Typecheck Outer"); g_debug_disable_map.insert( "Typecheck Expressions" ); g_debug_disable_map.insert( "Expand HIR Annotate" ); g_debug_disable_map.insert( "Expand HIR Closures" ); g_debug_disable_map.insert( "Expand HIR Calls" ); g_debug_disable_map.insert( "Expand HIR Reborrows" ); g_debug_disable_map.insert( "Typecheck Expressions (validate)" ); g_debug_disable_map.insert( "Dump HIR" ); g_debug_disable_map.insert( "Lower MIR" ); g_debug_disable_map.insert( "MIR Validate" ); g_debug_disable_map.insert( "Dump MIR" ); g_debug_disable_map.insert( "HIR Serialise" ); } bool debug_enabled() { // TODO: Have an explicit enable list? if( g_debug_disable_map.count(g_cur_phase) != 0 ) { return false; } else { return true; } } ::std::ostream& debug_output(int indent, const char* function) { return ::std::cout << g_cur_phase << "- " << RepeatLitStr { " ", indent } << function << ": "; } struct ProgramParams { enum eLastStage { STAGE_PARSE, STAGE_EXPAND, STAGE_RESOLVE, STAGE_TYPECK, STAGE_BORROWCK, STAGE_MIR, STAGE_ALL, } last_stage = STAGE_ALL; const char *infile = NULL; ::std::string outfile; const char *crate_path = "."; ProgramParams(int argc, char *argv[]); }; template <typename Rv, typename Fcn> Rv CompilePhase(const char *name, Fcn f) { ::std::cout << name << ": V V V" << ::std::endl; g_cur_phase = name; auto start = clock(); auto rv = f(); auto end = clock(); g_cur_phase = ""; ::std::cout <<"(" << ::std::fixed << ::std::setprecision(2) << static_cast<double>(end - start) / static_cast<double>(CLOCKS_PER_SEC) << " s) "; ::std::cout << name << ": DONE"; ::std::cout << ::std::endl; return rv; } template <typename Fcn> void CompilePhaseV(const char *name, Fcn f) { CompilePhase<int>(name, [&]() { f(); return 0; }); } /// main! int main(int argc, char *argv[]) { init_debug_list(); ProgramParams params(argc, argv); // Set up cfg values // TODO: Target spec Cfg_SetFlag("linux"); Cfg_SetValue("target_pointer_width", "64"); Cfg_SetValue("target_endian", "little"); Cfg_SetValue("target_arch", "x86-noasm"); // TODO: asm! macro Cfg_SetValueCb("target_has_atomic", [](const ::std::string& s) { if(s == "8") return true; // Has an atomic byte if(s == "ptr") return true; // Has an atomic pointer-sized value return false; }); Cfg_SetValueCb("target_feature", [](const ::std::string& s) { return false; }); try { // Parse the crate into AST AST::Crate crate = CompilePhase<AST::Crate>("Parse", [&]() { return Parse_Crate(params.infile); }); if( params.last_stage == ProgramParams::STAGE_PARSE ) { return 0; } // Load external crates. CompilePhaseV("LoadCrates", [&]() { crate.load_externs(); }); // Iterate all items in the AST, applying syntax extensions CompilePhaseV("Expand", [&]() { Expand(crate); }); // XXX: Dump crate before resolve CompilePhaseV("Temp output - Parsed", [&]() { Dump_Rust( FMT(params.outfile << "_0_pp.rs").c_str(), crate ); }); if( params.last_stage == ProgramParams::STAGE_EXPAND ) { return 0; } // Resolve names to be absolute names (include references to the relevant struct/global/function) // - This does name checking on types and free functions. // - Resolves all identifiers/paths to references CompilePhaseV("Resolve Use", [&]() { Resolve_Use(crate); // - Absolutise and resolve use statements }); CompilePhaseV("Resolve Index", [&]() { Resolve_Index(crate); // - Build up a per-module index of avalable names (faster and simpler later resolve) }); CompilePhaseV("Resolve Absolute", [&]() { Resolve_Absolutise(crate); // - Convert all paths to Absolute or UFCS, and resolve variables }); // XXX: Dump crate before HIR CompilePhaseV("Temp output - Resolved", [&]() { Dump_Rust( FMT(params.outfile << "_1_res.rs").c_str(), crate ); }); if( params.last_stage == ProgramParams::STAGE_RESOLVE ) { return 0; } // Extract the crate type and name from the crate attributes auto crate_type = crate.m_crate_type; if( crate_type == ::AST::Crate::Type::Unknown ) { // Assume to be executable crate_type = ::AST::Crate::Type::Executable; } auto crate_name = crate.m_crate_name; if( crate_name == "" ) { // TODO: Take the crate name from the input filename } // -------------------------------------- // HIR Section // -------------------------------------- // Construc the HIR from the AST ::HIR::CratePtr hir_crate = CompilePhase< ::HIR::CratePtr>("HIR Lower", [&]() { return LowerHIR_FromAST(mv$( crate )); }); // Deallocate the original crate crate = ::AST::Crate(); // Replace type aliases (`type`) into the actual type CompilePhaseV("Resolve Type Aliases", [&]() { ConvertHIR_ExpandAliases(*hir_crate); }); CompilePhaseV("Resolve Bind", [&]() { ConvertHIR_Bind(*hir_crate); }); CompilePhaseV("Resolve UFCS paths", [&]() { ConvertHIR_ResolveUFCS(*hir_crate); }); CompilePhaseV("Constant Evaluate", [&]() { ConvertHIR_ConstantEvaluate(*hir_crate); }); // === Type checking === // - This can recurse and call the MIR lower to evaluate constants // Check outer items first (types of constants/functions/statics/impls/...) // - Doesn't do any expressions except those in types CompilePhaseV("Typecheck Outer", [&]() { Typecheck_ModuleLevel(*hir_crate); }); // Check the rest of the expressions (including function bodies) CompilePhaseV("Typecheck Expressions", [&]() { Typecheck_Expressions(*hir_crate); }); // === HIR Expansion === // Annotate how each node's result is used CompilePhaseV("Expand HIR Annotate", [&]() { HIR_Expand_AnnotateUsage(*hir_crate); }); // - Now that all types are known, closures can be desugared CompilePhaseV("Expand HIR Closures", [&]() { HIR_Expand_Closures(*hir_crate); }); // - And calls can be turned into UFCS CompilePhaseV("Expand HIR Calls", [&]() { HIR_Expand_UfcsEverything(*hir_crate); }); CompilePhaseV("Expand HIR Reborrows", [&]() { HIR_Expand_Reborrows(*hir_crate); }); // - Ensure that typeck worked (including Fn trait call insertion etc) CompilePhaseV("Typecheck Expressions (validate)", [&]() { Typecheck_Expressions_Validate(*hir_crate); }); CompilePhaseV("Dump HIR", [&]() { ::std::ofstream os (FMT(params.outfile << "_2_hir.rs")); HIR_Dump( os, *hir_crate ); }); if( params.last_stage == ProgramParams::STAGE_TYPECK ) { return 0; } // Lower expressions into MIR CompilePhaseV("Lower MIR", [&]() { HIR_GenerateMIR(*hir_crate); }); // Validate the MIR CompilePhaseV("MIR Validate", [&]() { MIR_CheckCrate(*hir_crate); }); CompilePhaseV("Dump MIR", [&]() { ::std::ofstream os (FMT(params.outfile << "_3_mir.rs")); MIR_Dump( os, *hir_crate ); }); if( params.last_stage == ProgramParams::STAGE_MIR ) { return 0; } // Optimise the MIR //CompilePhaseV("Dump MIR", [&]() { // ::std::ofstream os (FMT(params.outfile << "_4_mir_opt.rs")); // MIR_Dump( os, *hir_crate ); // }); // TODO: Pass to mark items that are // - Signature Exportable (public) // - MIR Exportable (public generic, #[inline], or used by a either of those) // - Require codegen (public or used by an exported function) // Generate code for non-generic public items (if requested) switch( crate_type ) { case ::AST::Crate::Type::Unknown: // ERROR? break; case ::AST::Crate::Type::RustLib: // Save a loadable HIR dump CompilePhaseV("HIR Serialise", [&]() { //HIR_Serialise(params.outfile + ".meta", *hir_crate); HIR_Serialise(params.outfile, *hir_crate); }); // Generate a .o //HIR_Codegen(params.outfile + ".o", *hir_crate); // Link into a .rlib break; case ::AST::Crate::Type::RustDylib: // Save a loadable HIR dump // Generate a .so/.dll break; case ::AST::Crate::Type::CDylib: // Generate a .so/.dll break; case ::AST::Crate::Type::Executable: // Generate a binary break; } } catch(unsigned int) {} //catch(const CompileError::Base& e) //{ // ::std::cerr << "Parser Error: " << e.what() << ::std::endl; // return 2; //} //catch(const ::std::exception& e) //{ // ::std::cerr << "Misc Error: " << e.what() << ::std::endl; // return 2; //} //catch(const char* e) //{ // ::std::cerr << "Internal Compiler Error: " << e << ::std::endl; // return 2; //} return 0; } ProgramParams::ProgramParams(int argc, char *argv[]) { // Hacky command-line parsing for( int i = 1; i < argc; i ++ ) { const char* arg = argv[i]; if( arg[0] != '-' ) { this->infile = arg; } else if( arg[1] != '-' ) { arg ++; // eat '-' for( ; *arg; arg ++ ) { switch(*arg) { // "-o <file>" : Set output file case 'o': if( i == argc - 1 ) { // TODO: BAIL! exit(1); } this->outfile = argv[++i]; break; default: exit(1); } } } else { if( strcmp(arg, "--crate-path") == 0 ) { if( i == argc - 1 ) { // TODO: BAIL! exit(1); } this->crate_path = argv[++i]; } else if( strcmp(arg, "--stop-after") == 0 ) { if( i == argc - 1 ) { // TODO: BAIL! exit(1); } arg = argv[++i]; if( strcmp(arg, "parse") == 0 ) this->last_stage = STAGE_PARSE; else { ::std::cerr << "Unknown argument to --stop-after : '" << arg << "'" << ::std::endl; exit(1); } } else { ::std::cerr << "Unknown option '" << arg << "'" << ::std::endl; exit(1); } } } if( this->outfile == "" ) { this->outfile = (::std::string)this->infile + ".o"; } } <commit_msg>main - Suppress debug for the LoadCrates phase<commit_after>/* * MRustC - Rust Compiler * - By John Hodge (Mutabah/thePowersGang) * * main.cpp * - Compiler Entrypoint */ #include <iostream> #include <iomanip> #include <string> #include <set> #include "parse/lex.hpp" #include "parse/parseerror.hpp" #include "ast/ast.hpp" #include "ast/crate.hpp" #include <serialiser_texttree.hpp> #include <cstring> #include <main_bindings.hpp> #include "resolve/main_bindings.hpp" #include "hir/main_bindings.hpp" #include "hir_conv/main_bindings.hpp" #include "hir_typeck/main_bindings.hpp" #include "hir_expand/main_bindings.hpp" #include "mir/main_bindings.hpp" #include "expand/cfg.hpp" int g_debug_indent_level = 0; ::std::string g_cur_phase; ::std::set< ::std::string> g_debug_disable_map; void init_debug_list() { g_debug_disable_map.insert( "Parse" ); g_debug_disable_map.insert( "LoadCrates" ); g_debug_disable_map.insert( "Expand" ); g_debug_disable_map.insert( "Resolve Use" ); g_debug_disable_map.insert( "Resolve Index" ); g_debug_disable_map.insert( "Resolve Absolute" ); g_debug_disable_map.insert( "HIR Lower" ); g_debug_disable_map.insert( "Resolve Type Aliases" ); g_debug_disable_map.insert( "Resolve Bind" ); g_debug_disable_map.insert( "Resolve UFCS paths" ); g_debug_disable_map.insert( "Constant Evaluate" ); g_debug_disable_map.insert( "Typecheck Outer"); g_debug_disable_map.insert( "Typecheck Expressions" ); g_debug_disable_map.insert( "Expand HIR Annotate" ); g_debug_disable_map.insert( "Expand HIR Closures" ); g_debug_disable_map.insert( "Expand HIR Calls" ); g_debug_disable_map.insert( "Expand HIR Reborrows" ); g_debug_disable_map.insert( "Typecheck Expressions (validate)" ); g_debug_disable_map.insert( "Dump HIR" ); g_debug_disable_map.insert( "Lower MIR" ); g_debug_disable_map.insert( "MIR Validate" ); g_debug_disable_map.insert( "Dump MIR" ); g_debug_disable_map.insert( "HIR Serialise" ); } bool debug_enabled() { // TODO: Have an explicit enable list? if( g_debug_disable_map.count(g_cur_phase) != 0 ) { return false; } else { return true; } } ::std::ostream& debug_output(int indent, const char* function) { return ::std::cout << g_cur_phase << "- " << RepeatLitStr { " ", indent } << function << ": "; } struct ProgramParams { enum eLastStage { STAGE_PARSE, STAGE_EXPAND, STAGE_RESOLVE, STAGE_TYPECK, STAGE_BORROWCK, STAGE_MIR, STAGE_ALL, } last_stage = STAGE_ALL; const char *infile = NULL; ::std::string outfile; const char *crate_path = "."; ProgramParams(int argc, char *argv[]); }; template <typename Rv, typename Fcn> Rv CompilePhase(const char *name, Fcn f) { ::std::cout << name << ": V V V" << ::std::endl; g_cur_phase = name; auto start = clock(); auto rv = f(); auto end = clock(); g_cur_phase = ""; ::std::cout <<"(" << ::std::fixed << ::std::setprecision(2) << static_cast<double>(end - start) / static_cast<double>(CLOCKS_PER_SEC) << " s) "; ::std::cout << name << ": DONE"; ::std::cout << ::std::endl; return rv; } template <typename Fcn> void CompilePhaseV(const char *name, Fcn f) { CompilePhase<int>(name, [&]() { f(); return 0; }); } /// main! int main(int argc, char *argv[]) { init_debug_list(); ProgramParams params(argc, argv); // Set up cfg values // TODO: Target spec Cfg_SetFlag("linux"); Cfg_SetValue("target_pointer_width", "64"); Cfg_SetValue("target_endian", "little"); Cfg_SetValue("target_arch", "x86-noasm"); // TODO: asm! macro Cfg_SetValueCb("target_has_atomic", [](const ::std::string& s) { if(s == "8") return true; // Has an atomic byte if(s == "ptr") return true; // Has an atomic pointer-sized value return false; }); Cfg_SetValueCb("target_feature", [](const ::std::string& s) { return false; }); try { // Parse the crate into AST AST::Crate crate = CompilePhase<AST::Crate>("Parse", [&]() { return Parse_Crate(params.infile); }); if( params.last_stage == ProgramParams::STAGE_PARSE ) { return 0; } // Load external crates. CompilePhaseV("LoadCrates", [&]() { crate.load_externs(); }); // Iterate all items in the AST, applying syntax extensions CompilePhaseV("Expand", [&]() { Expand(crate); }); // XXX: Dump crate before resolve CompilePhaseV("Temp output - Parsed", [&]() { Dump_Rust( FMT(params.outfile << "_0_pp.rs").c_str(), crate ); }); if( params.last_stage == ProgramParams::STAGE_EXPAND ) { return 0; } // Resolve names to be absolute names (include references to the relevant struct/global/function) // - This does name checking on types and free functions. // - Resolves all identifiers/paths to references CompilePhaseV("Resolve Use", [&]() { Resolve_Use(crate); // - Absolutise and resolve use statements }); CompilePhaseV("Resolve Index", [&]() { Resolve_Index(crate); // - Build up a per-module index of avalable names (faster and simpler later resolve) }); CompilePhaseV("Resolve Absolute", [&]() { Resolve_Absolutise(crate); // - Convert all paths to Absolute or UFCS, and resolve variables }); // XXX: Dump crate before HIR CompilePhaseV("Temp output - Resolved", [&]() { Dump_Rust( FMT(params.outfile << "_1_res.rs").c_str(), crate ); }); if( params.last_stage == ProgramParams::STAGE_RESOLVE ) { return 0; } // Extract the crate type and name from the crate attributes auto crate_type = crate.m_crate_type; if( crate_type == ::AST::Crate::Type::Unknown ) { // Assume to be executable crate_type = ::AST::Crate::Type::Executable; } auto crate_name = crate.m_crate_name; if( crate_name == "" ) { // TODO: Take the crate name from the input filename } // -------------------------------------- // HIR Section // -------------------------------------- // Construc the HIR from the AST ::HIR::CratePtr hir_crate = CompilePhase< ::HIR::CratePtr>("HIR Lower", [&]() { return LowerHIR_FromAST(mv$( crate )); }); // Deallocate the original crate crate = ::AST::Crate(); // Replace type aliases (`type`) into the actual type CompilePhaseV("Resolve Type Aliases", [&]() { ConvertHIR_ExpandAliases(*hir_crate); }); CompilePhaseV("Resolve Bind", [&]() { ConvertHIR_Bind(*hir_crate); }); CompilePhaseV("Resolve UFCS paths", [&]() { ConvertHIR_ResolveUFCS(*hir_crate); }); CompilePhaseV("Constant Evaluate", [&]() { ConvertHIR_ConstantEvaluate(*hir_crate); }); // === Type checking === // - This can recurse and call the MIR lower to evaluate constants // Check outer items first (types of constants/functions/statics/impls/...) // - Doesn't do any expressions except those in types CompilePhaseV("Typecheck Outer", [&]() { Typecheck_ModuleLevel(*hir_crate); }); // Check the rest of the expressions (including function bodies) CompilePhaseV("Typecheck Expressions", [&]() { Typecheck_Expressions(*hir_crate); }); // === HIR Expansion === // Annotate how each node's result is used CompilePhaseV("Expand HIR Annotate", [&]() { HIR_Expand_AnnotateUsage(*hir_crate); }); // - Now that all types are known, closures can be desugared CompilePhaseV("Expand HIR Closures", [&]() { HIR_Expand_Closures(*hir_crate); }); // - And calls can be turned into UFCS CompilePhaseV("Expand HIR Calls", [&]() { HIR_Expand_UfcsEverything(*hir_crate); }); CompilePhaseV("Expand HIR Reborrows", [&]() { HIR_Expand_Reborrows(*hir_crate); }); // - Ensure that typeck worked (including Fn trait call insertion etc) CompilePhaseV("Typecheck Expressions (validate)", [&]() { Typecheck_Expressions_Validate(*hir_crate); }); CompilePhaseV("Dump HIR", [&]() { ::std::ofstream os (FMT(params.outfile << "_2_hir.rs")); HIR_Dump( os, *hir_crate ); }); if( params.last_stage == ProgramParams::STAGE_TYPECK ) { return 0; } // Lower expressions into MIR CompilePhaseV("Lower MIR", [&]() { HIR_GenerateMIR(*hir_crate); }); // Validate the MIR CompilePhaseV("MIR Validate", [&]() { MIR_CheckCrate(*hir_crate); }); CompilePhaseV("Dump MIR", [&]() { ::std::ofstream os (FMT(params.outfile << "_3_mir.rs")); MIR_Dump( os, *hir_crate ); }); if( params.last_stage == ProgramParams::STAGE_MIR ) { return 0; } // Optimise the MIR //CompilePhaseV("Dump MIR", [&]() { // ::std::ofstream os (FMT(params.outfile << "_4_mir_opt.rs")); // MIR_Dump( os, *hir_crate ); // }); // TODO: Pass to mark items that are // - Signature Exportable (public) // - MIR Exportable (public generic, #[inline], or used by a either of those) // - Require codegen (public or used by an exported function) // Generate code for non-generic public items (if requested) switch( crate_type ) { case ::AST::Crate::Type::Unknown: // ERROR? break; case ::AST::Crate::Type::RustLib: // Save a loadable HIR dump CompilePhaseV("HIR Serialise", [&]() { //HIR_Serialise(params.outfile + ".meta", *hir_crate); HIR_Serialise(params.outfile, *hir_crate); }); // Generate a .o //HIR_Codegen(params.outfile + ".o", *hir_crate); // Link into a .rlib break; case ::AST::Crate::Type::RustDylib: // Save a loadable HIR dump // Generate a .so/.dll break; case ::AST::Crate::Type::CDylib: // Generate a .so/.dll break; case ::AST::Crate::Type::Executable: // Generate a binary break; } } catch(unsigned int) {} //catch(const CompileError::Base& e) //{ // ::std::cerr << "Parser Error: " << e.what() << ::std::endl; // return 2; //} //catch(const ::std::exception& e) //{ // ::std::cerr << "Misc Error: " << e.what() << ::std::endl; // return 2; //} //catch(const char* e) //{ // ::std::cerr << "Internal Compiler Error: " << e << ::std::endl; // return 2; //} return 0; } ProgramParams::ProgramParams(int argc, char *argv[]) { // Hacky command-line parsing for( int i = 1; i < argc; i ++ ) { const char* arg = argv[i]; if( arg[0] != '-' ) { this->infile = arg; } else if( arg[1] != '-' ) { arg ++; // eat '-' for( ; *arg; arg ++ ) { switch(*arg) { // "-o <file>" : Set output file case 'o': if( i == argc - 1 ) { // TODO: BAIL! exit(1); } this->outfile = argv[++i]; break; default: exit(1); } } } else { if( strcmp(arg, "--crate-path") == 0 ) { if( i == argc - 1 ) { // TODO: BAIL! exit(1); } this->crate_path = argv[++i]; } else if( strcmp(arg, "--stop-after") == 0 ) { if( i == argc - 1 ) { // TODO: BAIL! exit(1); } arg = argv[++i]; if( strcmp(arg, "parse") == 0 ) this->last_stage = STAGE_PARSE; else { ::std::cerr << "Unknown argument to --stop-after : '" << arg << "'" << ::std::endl; exit(1); } } else { ::std::cerr << "Unknown option '" << arg << "'" << ::std::endl; exit(1); } } } if( this->outfile == "" ) { this->outfile = (::std::string)this->infile + ".o"; } } <|endoftext|>
<commit_before>#include "sdk.h" #include "CScripting.h" #include "CCallback.h" #include "CDispatcher.h" #ifdef WIN32 #include <WinSock2.h> #include <mysql.h> #else #include <mysql/mysql.h> #endif extern void *pAMXFunctions; logprintf_t logprintf; PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES | SUPPORTS_PROCESS_TICK; } PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) { pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS]; logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF]; if (mysql_library_init(0, NULL, NULL)) { logprintf(" >> plugin.mysql: plugin failed to load due to uninitialized MySQL library ('libmysql.dll' probably missing)."); return false; } logprintf(" >> plugin.mysql: R40 successfully loaded."); return true; } PLUGIN_EXPORT void PLUGIN_CALL Unload() { logprintf("plugin.mysql: Unloading plugin..."); mysql_library_end(); logprintf("plugin.mysql: Plugin unloaded."); } PLUGIN_EXPORT void PLUGIN_CALL ProcessTick() { CDispatcher::Get()->Process(); } extern "C" const AMX_NATIVE_INFO native_list[] = { AMX_DEFINE_NATIVE(orm_create) AMX_DEFINE_NATIVE(orm_destroy) AMX_DEFINE_NATIVE(orm_errno) AMX_DEFINE_NATIVE(orm_select) AMX_DEFINE_NATIVE(orm_update) AMX_DEFINE_NATIVE(orm_insert) AMX_DEFINE_NATIVE(orm_delete) AMX_DEFINE_NATIVE(orm_save) AMX_DEFINE_NATIVE(orm_apply_cache) AMX_DEFINE_NATIVE(orm_addvar_int) AMX_DEFINE_NATIVE(orm_addvar_float) AMX_DEFINE_NATIVE(orm_addvar_string) AMX_DEFINE_NATIVE(orm_delvar) AMX_DEFINE_NATIVE(orm_setkey) AMX_DEFINE_NATIVE(mysql_log) AMX_DEFINE_NATIVE(mysql_connect) AMX_DEFINE_NATIVE(mysql_close) AMX_DEFINE_NATIVE(mysql_reconnect) AMX_DEFINE_NATIVE(mysql_unprocessed_queries) AMX_DEFINE_NATIVE(mysql_current_handle) AMX_DEFINE_NATIVE(mysql_global_options) AMX_DEFINE_NATIVE(mysql_init_options) AMX_DEFINE_NATIVE(mysql_set_option) AMX_DEFINE_NATIVE(mysql_errno) AMX_DEFINE_NATIVE(mysql_escape_string) AMX_DEFINE_NATIVE(mysql_format) AMX_DEFINE_NATIVE(mysql_pquery) AMX_DEFINE_NATIVE(mysql_tquery) AMX_DEFINE_NATIVE(mysql_query) AMX_DEFINE_NATIVE(mysql_stat) AMX_DEFINE_NATIVE(mysql_get_charset) AMX_DEFINE_NATIVE(mysql_set_charset) AMX_DEFINE_NATIVE(cache_get_row_count) AMX_DEFINE_NATIVE(cache_get_field_count) AMX_DEFINE_NATIVE(cache_get_result_count) AMX_DEFINE_NATIVE(cache_get_field_name) AMX_DEFINE_NATIVE(cache_set_result) AMX_DEFINE_NATIVE(cache_get_row) AMX_DEFINE_NATIVE(cache_get_row_int) AMX_DEFINE_NATIVE(cache_get_row_float) AMX_DEFINE_NATIVE(cache_get_field_content) AMX_DEFINE_NATIVE(cache_get_field_content_int) AMX_DEFINE_NATIVE(cache_get_field_content_float) AMX_DEFINE_NATIVE(cache_save) AMX_DEFINE_NATIVE(cache_delete) AMX_DEFINE_NATIVE(cache_set_active) AMX_DEFINE_NATIVE(cache_is_valid) AMX_DEFINE_NATIVE(cache_affected_rows) AMX_DEFINE_NATIVE(cache_insert_id) AMX_DEFINE_NATIVE(cache_warning_count) AMX_DEFINE_NATIVE(cache_get_query_exec_time) AMX_DEFINE_NATIVE(cache_get_query_string) {NULL, NULL} }; PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) { CCallbackManager::Get()->AddAmx(amx); return amx_Register(amx, native_list, -1); } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) { CCallbackManager::Get()->RemoveAmx(amx); return AMX_ERR_NONE; } <commit_msg>correctly unload all systems at plugin shutdown<commit_after>#include "sdk.h" #include "CScripting.h" #include "CHandle.h" #include "CCallback.h" #include "CResult.h" #include "CDispatcher.h" #include "COptions.h" #ifdef WIN32 #include <WinSock2.h> #include <mysql.h> #else #include <mysql/mysql.h> #endif extern void *pAMXFunctions; logprintf_t logprintf; PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES | SUPPORTS_PROCESS_TICK; } PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) { pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS]; logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF]; if (mysql_library_init(0, NULL, NULL)) { logprintf(" >> plugin.mysql: plugin failed to load due to uninitialized MySQL library ('libmysql.dll' probably missing)."); return false; } logprintf(" >> plugin.mysql: R40 successfully loaded."); return true; } PLUGIN_EXPORT void PLUGIN_CALL Unload() { logprintf("plugin.mysql: Unloading plugin..."); CHandleManager::CSingleton::Destroy(); CCallbackManager::CSingleton::Destroy(); CResultSetManager::CSingleton::Destroy(); CDispatcher::CSingleton::Destroy(); COptionManager::CSingleton::Destroy(); mysql_library_end(); logprintf("plugin.mysql: Plugin unloaded."); } PLUGIN_EXPORT void PLUGIN_CALL ProcessTick() { CDispatcher::Get()->Process(); } extern "C" const AMX_NATIVE_INFO native_list[] = { AMX_DEFINE_NATIVE(orm_create) AMX_DEFINE_NATIVE(orm_destroy) AMX_DEFINE_NATIVE(orm_errno) AMX_DEFINE_NATIVE(orm_select) AMX_DEFINE_NATIVE(orm_update) AMX_DEFINE_NATIVE(orm_insert) AMX_DEFINE_NATIVE(orm_delete) AMX_DEFINE_NATIVE(orm_save) AMX_DEFINE_NATIVE(orm_apply_cache) AMX_DEFINE_NATIVE(orm_addvar_int) AMX_DEFINE_NATIVE(orm_addvar_float) AMX_DEFINE_NATIVE(orm_addvar_string) AMX_DEFINE_NATIVE(orm_delvar) AMX_DEFINE_NATIVE(orm_setkey) AMX_DEFINE_NATIVE(mysql_log) AMX_DEFINE_NATIVE(mysql_connect) AMX_DEFINE_NATIVE(mysql_close) AMX_DEFINE_NATIVE(mysql_reconnect) AMX_DEFINE_NATIVE(mysql_unprocessed_queries) AMX_DEFINE_NATIVE(mysql_current_handle) AMX_DEFINE_NATIVE(mysql_global_options) AMX_DEFINE_NATIVE(mysql_init_options) AMX_DEFINE_NATIVE(mysql_set_option) AMX_DEFINE_NATIVE(mysql_errno) AMX_DEFINE_NATIVE(mysql_escape_string) AMX_DEFINE_NATIVE(mysql_format) AMX_DEFINE_NATIVE(mysql_pquery) AMX_DEFINE_NATIVE(mysql_tquery) AMX_DEFINE_NATIVE(mysql_query) AMX_DEFINE_NATIVE(mysql_stat) AMX_DEFINE_NATIVE(mysql_get_charset) AMX_DEFINE_NATIVE(mysql_set_charset) AMX_DEFINE_NATIVE(cache_get_row_count) AMX_DEFINE_NATIVE(cache_get_field_count) AMX_DEFINE_NATIVE(cache_get_result_count) AMX_DEFINE_NATIVE(cache_get_field_name) AMX_DEFINE_NATIVE(cache_set_result) AMX_DEFINE_NATIVE(cache_get_row) AMX_DEFINE_NATIVE(cache_get_row_int) AMX_DEFINE_NATIVE(cache_get_row_float) AMX_DEFINE_NATIVE(cache_get_field_content) AMX_DEFINE_NATIVE(cache_get_field_content_int) AMX_DEFINE_NATIVE(cache_get_field_content_float) AMX_DEFINE_NATIVE(cache_save) AMX_DEFINE_NATIVE(cache_delete) AMX_DEFINE_NATIVE(cache_set_active) AMX_DEFINE_NATIVE(cache_is_valid) AMX_DEFINE_NATIVE(cache_affected_rows) AMX_DEFINE_NATIVE(cache_insert_id) AMX_DEFINE_NATIVE(cache_warning_count) AMX_DEFINE_NATIVE(cache_get_query_exec_time) AMX_DEFINE_NATIVE(cache_get_query_string) {NULL, NULL} }; PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) { CCallbackManager::Get()->AddAmx(amx); return amx_Register(amx, native_list, -1); } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) { CCallbackManager::Get()->RemoveAmx(amx); return AMX_ERR_NONE; } <|endoftext|>
<commit_before>#include <utility> #include "Xml/XmlParser.hpp" #include "Xsd/XsdChecker.hpp" static int const SUCCESS = 0x0000; static int const INVALID_COMMAND = 0x0001; static int const PARSE_ERROR = 0x0002; static inline void displayMan() { std::cerr << "Available commands are:\n" << "xmltool -p file.xml : parse and display the xml file\n" << "xmltool -v file.xml file.xsd : parse both xml and xsd files and display the validation result\n" << "xmltool -t file.xml file.xsl : parse both xml and xsl files and display de transformation result of file.xml by the stylesheet file.xsl\n" << "xmltool -h : displays this help" << std::endl; } int appParse(std::string const & xmlPath) { Xml::Log xmlLog; Xml::Document * xmlDoc = Xml::load(xmlPath, &xmlLog); if(xmlDoc == nullptr) { std::cerr << "Failed to parse XML file: " << xmlPath << std::endl; std::cerr << xmlLog; return PARSE_ERROR; } std::cout << (*xmlDoc) << std::endl; std::cerr << xmlLog; delete xmlDoc; return SUCCESS; } int appVerify(std::string const & xmlPath, std::string const & xsdPath) { (void) xmlPath; (void) xsdPath; // Parsing XSD Document Xml::Log xmlLog; Xml::Document * xsdDoc = Xml::load(xsdPath, &xmlLog); Xml::Document * xmlDoc = Xml::load(xmlPath, &xmlLog); if(xsdDoc == nullptr) { std::cerr << "Failed to parse XSD file: " << xmlPath << std::endl; std::cerr << xmlLog; return PARSE_ERROR; } if(xmlDoc == nullptr) { std::cerr << "Failed to parse XML file: " << xmlPath << std::endl; std::cerr << xmlLog; return PARSE_ERROR; } // Building XSD Checker if(!Xsd::Checker::parseXsd(xsdDoc)) { return; } Xsd::Checker * checker = Xsd::Checker::getInstance(); // Validation process if(checker.isValid(xmlDoc)) { std::cout << xmlPath << " is valid according to the " << xsdPath << " schema" << std::endl; } else { std::cerr << xmlPath << " does not respect the " << xsdPath << " schema" << std::endl; } delete xmlDoc; delete checker; return SUCCESS; } int appTransform(std::string const & xmlPath, std::string const & xslPath) { (void) xmlPath; (void) xslPath; std::cerr << __func__ << " : not implemented yet" << std::endl; __builtin_trap(); return SUCCESS; } template <typename R, typename ...FArgs, typename ...Args> int checkArgsAndCall(std::string const & option, int argc, R(* func)(FArgs ...), Args && ...args) { static_assert(sizeof...(FArgs) == sizeof...(Args), "Wrong number of parameters"); auto nbCmdParams = argc - 2u; // -1 for executable name, -1 for the option auto nbFuncParams = sizeof...(FArgs); if(nbCmdParams != nbFuncParams) { std::cerr << "Invalid number of arguments for option \"" << option << "\" (expected " << nbFuncParams << " got " << nbCmdParams << ")\n" << std::endl; displayMan(); return INVALID_COMMAND; } return func(std::forward<Args>(args)...); } int main(int argc, char const * const * argv) { if(argc < 2) { displayMan(); return INVALID_COMMAND; } std::string option = argv[1]; // Ask for help if(option == "-h") { displayMan(); return SUCCESS; } // Parse and display the XML file if(option == "-p") { return checkArgsAndCall(option, argc, appParse, argv[2]); } // Parse both xml and xsd files and display the validation result if(option == "-v") { return checkArgsAndCall(option, argc, appVerify, argv[2], argv[3]); } // Parse both xml and xsl files and display de transformation result if(option == "-t") { return checkArgsAndCall(option, argc, appTransform, argv[2], argv[3]); } // If we get here, the command is invalid std::cerr << "Invalid command" << std::endl; displayMan(); return INVALID_COMMAND; } <commit_msg>fix error in main.cpp<commit_after>#include <utility> #include "Xml/XmlParser.hpp" #include "Xsd/XsdChecker.hpp" static int const SUCCESS = 0x0000; static int const INVALID_COMMAND = 0x0001; static int const PARSE_ERROR = 0x0002; static inline void displayMan() { std::cerr << "Available commands are:\n" << "xmltool -p file.xml : parse and display the xml file\n" << "xmltool -v file.xml file.xsd : parse both xml and xsd files and display the validation result\n" << "xmltool -t file.xml file.xsl : parse both xml and xsl files and display de transformation result of file.xml by the stylesheet file.xsl\n" << "xmltool -h : displays this help" << std::endl; } int appParse(std::string const & xmlPath) { Xml::Log xmlLog; Xml::Document * xmlDoc = Xml::load(xmlPath, &xmlLog); if(xmlDoc == nullptr) { std::cerr << "Failed to parse XML file: " << xmlPath << std::endl; std::cerr << xmlLog; return PARSE_ERROR; } std::cout << (*xmlDoc) << std::endl; std::cerr << xmlLog; delete xmlDoc; return SUCCESS; } int appVerify(std::string const & xmlPath, std::string const & xsdPath) { (void) xmlPath; (void) xsdPath; // Parsing XSD Document Xml::Log xmlLog; Xml::Document * xsdDoc = Xml::load(xsdPath, &xmlLog); Xml::Document * xmlDoc = Xml::load(xmlPath, &xmlLog); if(xsdDoc == nullptr) { std::cerr << "Failed to parse XSD file: " << xmlPath << std::endl; std::cerr << xmlLog; return PARSE_ERROR; } if(xmlDoc == nullptr) { std::cerr << "Failed to parse XML file: " << xmlPath << std::endl; std::cerr << xmlLog; return PARSE_ERROR; } // Building XSD Checker if(!Xsd::Checker::parseXsd(xsdDoc)) { return PARSE_ERROR; } Xsd::Checker * checker = Xsd::Checker::getInstance(); // Validation process if(checker->isValid(xmlDoc)) { std::cout << xmlPath << " is valid according to the " << xsdPath << " schema" << std::endl; } else { std::cerr << xmlPath << " does not respect the " << xsdPath << " schema" << std::endl; } delete xmlDoc; delete checker; return SUCCESS; } int appTransform(std::string const & xmlPath, std::string const & xslPath) { (void) xmlPath; (void) xslPath; std::cerr << __func__ << " : not implemented yet" << std::endl; __builtin_trap(); return SUCCESS; } template <typename R, typename ...FArgs, typename ...Args> int checkArgsAndCall(std::string const & option, int argc, R(* func)(FArgs ...), Args && ...args) { static_assert(sizeof...(FArgs) == sizeof...(Args), "Wrong number of parameters"); auto nbCmdParams = argc - 2u; // -1 for executable name, -1 for the option auto nbFuncParams = sizeof...(FArgs); if(nbCmdParams != nbFuncParams) { std::cerr << "Invalid number of arguments for option \"" << option << "\" (expected " << nbFuncParams << " got " << nbCmdParams << ")\n" << std::endl; displayMan(); return INVALID_COMMAND; } return func(std::forward<Args>(args)...); } int main(int argc, char const * const * argv) { if(argc < 2) { displayMan(); return INVALID_COMMAND; } std::string option = argv[1]; // Ask for help if(option == "-h") { displayMan(); return SUCCESS; } // Parse and display the XML file if(option == "-p") { return checkArgsAndCall(option, argc, appParse, argv[2]); } // Parse both xml and xsd files and display the validation result if(option == "-v") { return checkArgsAndCall(option, argc, appVerify, argv[2], argv[3]); } // Parse both xml and xsl files and display de transformation result if(option == "-t") { return checkArgsAndCall(option, argc, appTransform, argv[2], argv[3]); } // If we get here, the command is invalid std::cerr << "Invalid command" << std::endl; displayMan(); return INVALID_COMMAND; } <|endoftext|>
<commit_before>#define DISTANCECMCRITICAL 20 #define DISTANCECMWARNING 30 #define PUBLSIHINTERVAL 2000 #define TRYFOLLOWLINEINTERVAL 3000 #define WAITINTERVAL 5000 #define MOVESPEED 100 #define ID "11:11:11:11:11:13" #define JSON #include <Arduino.h> #include <Streaming.h> #include <ArduinoJson.h> #include <MeMCore.h> enum direction { STOP, FORWARD, BACKWARD, LEFT, RIGHT } move = STOP; MeDCMotor motorL(M1); MeDCMotor motorR(M2); MeLineFollower lineFollower(PORT_2); MeTemperature temperature(PORT_4, SLOT2); MeUltrasonicSensor ultrasonicSensor(PORT_3); MeLightSensor lightSensor(PORT_6); MeIR ir; MeRGBLed rgbLed(PORT_7, 2); MeBuzzer buzzer; MePIRMotionSensor pirMotionSensor(PORT_1); int moveSpeed = 100; int lineFollowFlag = 0; bool watch = false; bool blocked = false; bool obstacleDetected = false; unsigned long publishTimer = millis(); bool wait = false; unsigned long waitTimer = millis(); bool tryFollowLine = true; unsigned long tryFollowLineTimer = millis(); DynamicJsonBuffer jsonBuffer; JsonObject& root = jsonBuffer.createObject(); void forward() { motorL.run(-MOVESPEED); motorR.run(MOVESPEED); } void backward() { motorL.run(MOVESPEED); motorR.run(-MOVESPEED); } void turnLeft() { motorL.run(-MOVESPEED / 10); motorR.run(MOVESPEED); } void turnRight() { motorL.run(-MOVESPEED); motorR.run(MOVESPEED / 10); } void stop() { motorL.run(0); motorR.run(0); } bool distanceWarning(double distanceCmLimit) { if (ultrasonicSensor.distanceCm() < distanceCmLimit) { return true; } else { return false; } } void drive() { if (distanceWarning(DISTANCECMCRITICAL)) { if (move == BACKWARD) { backward(); } else { stop(); } } else { switch (move) { case FORWARD: forward(); break; case BACKWARD: backward(); break; case LEFT: turnLeft(); break; case RIGHT: turnRight(); break; case STOP: stop(); break; } } } void toggleWatch() { watch = !watch; if (watch) { rgbLed.setColor(1, 0, 10, 0); rgbLed.show(); } else { rgbLed.setColor(1, 0, 0, 0); rgbLed.show(); move = STOP; } delay(250); } void bottomCheck() { if (analogRead(A7) == 0) { toggleWatch(); } } void irCheck() { unsigned long value; if (ir.decode()) { value = ir.value; switch (value >> 16 & 0xff) { case IR_BUTTON_LEFT: move = LEFT; break; case IR_BUTTON_RIGHT: move = RIGHT; break; case IR_BUTTON_DOWN: move = BACKWARD; break; case IR_BUTTON_UP: move = FORWARD; break; case IR_BUTTON_SETTING: move = STOP; break; case IR_BUTTON_A: toggleWatch(); break; } } } void silent() { buzzer.noTone(); rgbLed.setColor(2, 0, 0, 0); rgbLed.show(); } void warning() { rgbLed.setColor(2, 0, 0, 10); rgbLed.show(); } void alarm() { //buzzer.tone(262, 100); rgbLed.setColor(2, 10, 0, 0); rgbLed.show(); } void noiseCheck() { if (watch and distanceWarning(DISTANCECMCRITICAL)) { if (wait == false) { wait = true; waitTimer = millis(); } if (wait and millis() - waitTimer > WAITINTERVAL) { blocked = true; alarm(); } else { warning(); } } else { wait = false; blocked = false; silent(); } } void autonomous() { byte randNumber; randomSeed(analogRead(6)); randNumber = random(2); if (!distanceWarning(DISTANCECMCRITICAL) and !obstacleDetected) { move = FORWARD; } else { obstacleDetected = true; } if (obstacleDetected) { if (distanceWarning(DISTANCECMWARNING)) { move = BACKWARD; } else { switch (randNumber) { case 0: move = LEFT; turnLeft(); delay(400); break; case 1: move = RIGHT; turnRight(); delay(400); break; } obstacleDetected = false; } } } void sendData() { if (millis() - publishTimer > PUBLSIHINTERVAL) { publishTimer = millis(); #ifdef JSON root["watch"] = watch; root["move"] = move; root["wait"] = wait; root["blocked"] = blocked; root["distanceCm"] = ultrasonicSensor.distanceCm(); root["lightSensor"] = lightSensor.read(); root["temperature"] = temperature.temperature(); root["isHumanDetected"] = pirMotionSensor.isHumanDetected(); //root.prettyPrintTo(Serial); root.printTo(Serial); Serial << "<eom>" << endl; #else Serial << ID << ";TEMP:" << temperature.temperature() << ";" << endl; Serial.flush(); Serial << ID << ";DIST:" << ultrasonicSensor.distanceCm() << ";" << endl; Serial.flush(); Serial << ID << ";LIGH:" << lightSensor.read() << ";" << endl; Serial.flush(); #endif } } void setup() { Serial.begin(115200); while (!Serial); Serial << endl << endl; pinMode(A7, INPUT); ir.begin(); pirMotionSensor.SetPirMotionMode(1); rgbLed.setColor(0, 0, 0, 0); rgbLed.show(); } void loop() { bottomCheck(); irCheck(); noiseCheck(); sendData(); drive(); if (watch) { switch (lineFollower.readSensors()) { case S1_IN_S2_IN: tryFollowLine = true; move = FORWARD; lineFollowFlag = 10; break; case S1_IN_S2_OUT: tryFollowLine = true; move = FORWARD; if (lineFollowFlag > 1) lineFollowFlag--; break; case S1_OUT_S2_IN: tryFollowLine = true; move = FORWARD; if (lineFollowFlag < 20) lineFollowFlag++; break; case S1_OUT_S2_OUT: if (tryFollowLine) { tryFollowLine = !tryFollowLine; tryFollowLineTimer = millis(); } if (millis() - tryFollowLineTimer < TRYFOLLOWLINEINTERVAL) { if (lineFollowFlag == 10) move = BACKWARD; if (lineFollowFlag < 10) move = LEFT; if (lineFollowFlag > 10) move = RIGHT; } else { autonomous(); } break; } } } <commit_msg>removed AppIoT specifica<commit_after>#define DISTANCECMCRITICAL 20 #define DISTANCECMWARNING 30 #define PUBLSIHINTERVAL 2000 #define TRYFOLLOWLINEINTERVAL 3000 #define WAITINTERVAL 5000 #define MOVESPEED 100 #include <Arduino.h> #include <Streaming.h> #include <ArduinoJson.h> #include <MeMCore.h> enum direction { STOP, FORWARD, BACKWARD, LEFT, RIGHT } move = STOP; MeDCMotor motorL(M1); MeDCMotor motorR(M2); MeLineFollower lineFollower(PORT_2); MeTemperature temperature(PORT_4, SLOT2); MeUltrasonicSensor ultrasonicSensor(PORT_3); MeLightSensor lightSensor(PORT_6); MeIR ir; MeRGBLed rgbLed(PORT_7, 2); MeBuzzer buzzer; MePIRMotionSensor pirMotionSensor(PORT_1); int moveSpeed = 100; int lineFollowFlag = 0; bool watch = false; bool blocked = false; bool obstacleDetected = false; unsigned long publishTimer = millis(); bool wait = false; unsigned long waitTimer = millis(); bool tryFollowLine = true; unsigned long tryFollowLineTimer = millis(); DynamicJsonBuffer jsonBuffer; JsonObject& root = jsonBuffer.createObject(); void forward() { motorL.run(-MOVESPEED); motorR.run(MOVESPEED); } void backward() { motorL.run(MOVESPEED); motorR.run(-MOVESPEED); } void turnLeft() { motorL.run(-MOVESPEED / 10); motorR.run(MOVESPEED); } void turnRight() { motorL.run(-MOVESPEED); motorR.run(MOVESPEED / 10); } void stop() { motorL.run(0); motorR.run(0); } bool distanceWarning(double distanceCmLimit) { if (ultrasonicSensor.distanceCm() < distanceCmLimit) { return true; } else { return false; } } void drive() { if (distanceWarning(DISTANCECMCRITICAL)) { if (move == BACKWARD) { backward(); } else { stop(); } } else { switch (move) { case FORWARD: forward(); break; case BACKWARD: backward(); break; case LEFT: turnLeft(); break; case RIGHT: turnRight(); break; case STOP: stop(); break; } } } void toggleWatch() { watch = !watch; if (watch) { rgbLed.setColor(1, 0, 10, 0); rgbLed.show(); } else { rgbLed.setColor(1, 0, 0, 0); rgbLed.show(); move = STOP; } delay(250); } void bottomCheck() { if (analogRead(A7) == 0) { toggleWatch(); } } void irCheck() { unsigned long value; if (ir.decode()) { value = ir.value; switch (value >> 16 & 0xff) { case IR_BUTTON_LEFT: move = LEFT; break; case IR_BUTTON_RIGHT: move = RIGHT; break; case IR_BUTTON_DOWN: move = BACKWARD; break; case IR_BUTTON_UP: move = FORWARD; break; case IR_BUTTON_SETTING: move = STOP; break; case IR_BUTTON_A: toggleWatch(); break; } } } void silent() { buzzer.noTone(); rgbLed.setColor(2, 0, 0, 0); rgbLed.show(); } void warning() { rgbLed.setColor(2, 0, 0, 10); rgbLed.show(); } void alarm() { buzzer.tone(262, 100); rgbLed.setColor(2, 10, 0, 0); rgbLed.show(); } void noiseCheck() { if (watch and distanceWarning(DISTANCECMCRITICAL)) { if (wait == false) { wait = true; waitTimer = millis(); } if (wait and millis() - waitTimer > WAITINTERVAL) { blocked = true; alarm(); } else { warning(); } } else { wait = false; blocked = false; silent(); } } void autonomous() { byte randNumber; randomSeed(analogRead(6)); randNumber = random(2); if (!distanceWarning(DISTANCECMCRITICAL) and !obstacleDetected) { move = FORWARD; } else { obstacleDetected = true; } if (obstacleDetected) { if (distanceWarning(DISTANCECMWARNING)) { move = BACKWARD; } else { switch (randNumber) { case 0: move = LEFT; turnLeft(); delay(500); break; case 1: move = RIGHT; turnRight(); delay(500); break; } obstacleDetected = false; } } } void sendData() { if (millis() - publishTimer > PUBLSIHINTERVAL) { publishTimer = millis(); root["watch"] = watch; root["move"] = move; root["wait"] = wait; root["blocked"] = blocked; root["obstacleDetected"] = obstacleDetected; root["distanceCm"] = ultrasonicSensor.distanceCm(); root["lightSensor"] = lightSensor.read(); root["temperature"] = temperature.temperature(); root["isHumanDetected"] = pirMotionSensor.isHumanDetected(); //root.prettyPrintTo(Serial); root.printTo(Serial); Serial << "<eom>" << endl; } } void setup() { Serial.begin(115200); while (!Serial); Serial << endl << endl; pinMode(A7, INPUT); ir.begin(); pirMotionSensor.SetPirMotionMode(1); rgbLed.setColor(0, 0, 0, 0); rgbLed.show(); } void loop() { bottomCheck(); irCheck(); noiseCheck(); sendData(); drive(); if (watch) { switch (lineFollower.readSensors()) { case S1_IN_S2_IN: tryFollowLine = true; move = FORWARD; lineFollowFlag = 10; break; case S1_IN_S2_OUT: tryFollowLine = true; move = FORWARD; if (lineFollowFlag > 1) lineFollowFlag--; break; case S1_OUT_S2_IN: tryFollowLine = true; move = FORWARD; if (lineFollowFlag < 20) lineFollowFlag++; break; case S1_OUT_S2_OUT: if (tryFollowLine) { tryFollowLine = !tryFollowLine; tryFollowLineTimer = millis(); } if (millis() - tryFollowLineTimer < TRYFOLLOWLINEINTERVAL) { if (lineFollowFlag == 10) move = BACKWARD; if (lineFollowFlag < 10) move = LEFT; if (lineFollowFlag > 10) move = RIGHT; } else { autonomous(); } break; } } } <|endoftext|>
<commit_before><commit_msg>Changes Live Search to Bing for en_US only. A full worldwide review is in progress and we'll pick up the other countries eventually.<commit_after><|endoftext|>
<commit_before>//============================================================================ // Name : UnscentedKalmanFilter.cpp // Author : Ramiz Raja // Version : // Copyright : MIT Licensed // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include "ukf.h" using namespace std; int main() { UKF ukf; VectorXd x = VectorXd::Zero(5); MatrixXd P = MatrixXd::Zero(5, 5); ukf.UpdateRadarState(&x, &P); //print result std::cout << "Updated mean x" << std::endl; std::cout << x << std::endl; std::cout << "Updated covariance matrix P" << std::endl; std::cout << P << std::endl; return 0; } <commit_msg>Feat: Code to read data and call UKF<commit_after>//============================================================================ // Name : UnscentedKalmanFilter.cpp // Author : Ramiz Raja // Version : // Copyright : MIT Licensed // Description : Hello World in C++, Ansi-style //============================================================================ #include <fstream> #include <iostream> #include <sstream> #include <vector> #include <stdlib.h> #include "Eigen/Dense" #include "ukf.h" #include "ground_truth_package.h" #include "measurement_package.h" using namespace std; using Eigen::MatrixXd; using Eigen::VectorXd; using std::vector; void CheckArguments(int argc, char* argv[]); void ReadMeasurements(string in_file_name, vector<MeasurementPackage> &measurement_pack_list, vector<GroundTruthPackage>& gt_pack_list); void CheckFiles(const string& in_name, const string& out_name); void TestUkf(const string& in_file_name, const string& out_file_name); void RunUkf(const vector<MeasurementPackage>& measurement_pack_list, const vector<GroundTruthPackage>& gt_pack_list, const string& out_file_name); using namespace std; int main(int argc, char* argv[]) { //check validity of arguments CheckArguments(argc, argv); string in_file_name = argv[1]; string out_file_name = argv[2]; //validate files existence CheckFiles(in_file_name, out_file_name); TestUkf(in_file_name, out_file_name); return 0; } void TestUkf(const string& in_file_name, const string& out_file_name) { vector<MeasurementPackage> measurement_pack_list; vector<GroundTruthPackage> gt_pack_list; ReadMeasurements(in_file_name, measurement_pack_list, gt_pack_list); RunUkf(measurement_pack_list, gt_pack_list, out_file_name); } void RunUkf(const vector<MeasurementPackage>& measurement_pack_list, const vector<GroundTruthPackage>& gt_pack_list, const string& out_file_name) { ofstream out_file(out_file_name, ofstream::out); if (!out_file.is_open()) { std::cerr << "Error opening file: " << out_file_name << std::endl; exit(EXIT_FAILURE); } // column names for output file out_file << "time_stamp" << "\t"; out_file << "px_state" << "\t"; out_file << "py_state" << "\t"; out_file << "v_state" << "\t"; out_file << "yaw_angle_state" << "\t"; out_file << "yaw_rate_state" << "\t"; out_file << "sensor_type" << "\t"; out_file << "NIS" << "\t"; out_file << "px_measured" << "\t"; out_file << "py_measured" << "\t"; out_file << "px_ground_truth" << "\t"; out_file << "py_ground_truth" << "\t"; out_file << "vx_ground_truth" << "\t"; out_file << "vy_ground_truth" << "\n"; // Create a UKF instance UKF ukf; // used to compute the RMSE later vector<VectorXd> estimations; vector<VectorXd> ground_truth; //Call the UKF-based fusion size_t N = measurement_pack_list.size(); for (size_t k = 0; k < N; ++k) { // start filtering from the second frame (the speed is unknown in the first // frame) ukf.ProcessMeasurement(measurement_pack_list[k]); // timestamp out_file << measurement_pack_list[k].timestamp_ << "\t"; // pos1 - est // output the estimation VectorXd x = ukf.GetMeanState(); out_file << x(0) << "\t"; //px out_file << x(1) << "\t"; //py out_file << x(2) << "\t"; //speed out_file << x(3) << "\t"; //yaw out_file << x(4) << "\t"; //yaw_rate // output the measurements if (measurement_pack_list[k].sensor_type_ == MeasurementPackage::LASER) { // sensor type out_file << "lidar" << "\t"; // NIS value out_file << ukf.GetLaserNIS() << "\t"; // output the estimation out_file << measurement_pack_list[k].raw_measurements_(0) << "\t"; out_file << measurement_pack_list[k].raw_measurements_(1) << "\t"; } else if (measurement_pack_list[k].sensor_type_ == MeasurementPackage::RADAR) { // sensor type out_file << "radar" << "\t"; // NIS value out_file << ukf.GetRadarNIS() << "\t"; // output the estimation in the cartesian coordinates float ro = measurement_pack_list[k].raw_measurements_(0); float phi = measurement_pack_list[k].raw_measurements_(1); out_file << ro * cos(phi) << "\t"; // p1_meas out_file << ro * sin(phi) << "\t"; // ps_meas } // output the ground truth packages out_file << gt_pack_list[k].gt_values_(0) << "\t"; out_file << gt_pack_list[k].gt_values_(1) << "\t"; out_file << gt_pack_list[k].gt_values_(2) << "\t"; out_file << gt_pack_list[k].gt_values_(3) << "\n"; // convert ukf x vector to cartesian to compare to ground truth VectorXd ukf_x_cartesian_ = VectorXd(4); x = ukf.GetMeanState(); float x_estimate_ = x(0); float y_estimate_ = x(1); float vx_estimate_ = x(2) * cos(x(3)); float vy_estimate_ = x(2) * sin(x(3)); ukf_x_cartesian_ << x_estimate_, y_estimate_, vx_estimate_, vy_estimate_; estimations.push_back(ukf_x_cartesian_); ground_truth.push_back(gt_pack_list[k].gt_values_); } // compute the accuracy (RMSE) cout << "Accuracy - RMSE:" << endl << Tools::CalculateRMSE(estimations, ground_truth) << endl; if (out_file.is_open()) { out_file.close(); } } void ReadMeasurements(string in_file_name, vector<MeasurementPackage> &measurement_pack_list, vector<GroundTruthPackage>& gt_pack_list) { ifstream in_file(in_file_name.c_str(), ifstream::in); if (!in_file.is_open()) { std::cerr << "Can not open file: " << in_file_name << std::endl; exit(EXIT_FAILURE); } // prep the measurement packages (each line represents a measurement at a // timestamp) string line; while (getline(in_file, line) && !in_file.eof()) { string sensor_type; MeasurementPackage meas_package; GroundTruthPackage gt_package; istringstream iss(line); long timestamp; // reads first element from the current line iss >> sensor_type; if (sensor_type.compare("L") == 0) { // LASER MEASUREMENT // read measurements at this timestamp meas_package.sensor_type_ = MeasurementPackage::LASER; meas_package.raw_measurements_ = VectorXd(2); float x; float y; iss >> x; iss >> y; meas_package.raw_measurements_ << x, y; iss >> timestamp; meas_package.timestamp_ = timestamp; measurement_pack_list.push_back(meas_package); } else if (sensor_type.compare("R") == 0) { // RADAR MEASUREMENT // read measurements at this timestamp meas_package.sensor_type_ = MeasurementPackage::RADAR; meas_package.raw_measurements_ = VectorXd(3); float ro; float phi; float ro_dot; iss >> ro; iss >> phi; iss >> ro_dot; meas_package.raw_measurements_ << ro, phi, ro_dot; iss >> timestamp; meas_package.timestamp_ = timestamp; measurement_pack_list.push_back(meas_package); } // read ground truth data to compare later float x_gt; float y_gt; float vx_gt; float vy_gt; iss >> x_gt; iss >> y_gt; iss >> vx_gt; iss >> vy_gt; gt_package.gt_values_ = VectorXd(4); gt_package.gt_values_ << x_gt, y_gt, vx_gt, vy_gt; gt_pack_list.push_back(gt_package); } if (in_file.is_open()) { in_file.close(); } } void CheckArguments(int argc, char* argv[]) { string usage_instructions = "Usage instructions: "; usage_instructions += argv[0]; usage_instructions += " path/to/input.txt output.txt"; bool has_valid_args = false; // make sure the user has provided input and output files if (argc == 1) { cerr << usage_instructions << endl; } else if (argc == 2) { cerr << "Please include an output file.\n" << usage_instructions << endl; } else if (argc == 3) { has_valid_args = true; } else if (argc > 3) { cerr << "Too many arguments.\n" << usage_instructions << endl; } if (!has_valid_args) { exit(EXIT_FAILURE); } } void CheckFiles(const string& in_name, const string& out_name) { ifstream in_file(in_name.c_str(), ifstream::in); if (!in_file.is_open()) { cerr << "Cannot open input file: " << in_name << endl; exit(EXIT_FAILURE); } in_file.close(); ofstream out_file(out_name.c_str(), ofstream::out); if (!out_file.is_open()) { cerr << "Cannot open output file: " << out_name << endl; exit(EXIT_FAILURE); } out_file.close(); } <|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include <fstream> #include <algorithm> #include <vector> #include <iomanip> #include <cassert> #include "logger.hpp" #include "lexer.hpp" #include "parser.hpp" #include "environment.hpp" #include "interpreter.hpp" // conver a double value to percent std::string format_probability(double prob) { if (prob < 0.0001 && prob != 0) { return "< 0.01 %"; } return std::to_string(prob * 100) + " %"; } // value formatting functions void print(int value) { std::cout << value << std::endl; } void print(double value) { std::cout << value << std::endl; } template<typename ValueType, typename ProbabilityType> void print( const dice::random_variable_decomposition<ValueType, ProbabilityType>& var) { const int width_value = 10; const int width_prob = 15; const int width_cdf = 15; std::cout << std::endl << "\e[1m" << std::setw(width_value) << "Value" << "\e[1m" << std::setw(width_prob) << "PMF" << "\e[1m" << std::setw(width_cdf) << "CDF" << "\e[0m" << std::endl; ProbabilityType sum = 0; for (auto&& pair : var.probability()) { std::cout << std::setw(width_value) << pair.first << std::setw(width_prob) << format_probability(pair.second) << std::setw(width_cdf) << format_probability(sum) << std::endl; sum += pair.second; } } /** Print computed value. * @param computed value */ void print_value(const dice::base_value* value) { if (value == nullptr) { return; } // print value auto int_value = dynamic_cast<const dice::type_int*>(value); if (int_value != nullptr) { print(int_value->data()); return; } auto double_value = dynamic_cast<const dice::type_double*>(value); if (double_value != nullptr) { print(double_value->data()); return; } auto var_value = dynamic_cast<const dice::type_rand_var*>(value); if (var_value != nullptr) { print(var_value->data()); return; } throw std::runtime_error("Unknown value."); } struct options { // Command line arguments std::vector<std::string> args; // Input stream std::istream* input; // Should we print the executed script? bool verbose; options(int argc, char** argv) : args(argv, argv + argc), input(nullptr), verbose(false) { parse(); } private: std::ifstream input_file_; std::stringstream input_mem_; void parse() { auto it = args.begin() + 1; // first arg is the file path bool load_from_file = false; for (; it != args.end(); ++it) { if (*it == "-f") // input file { assert(it + 1 != args.end()); ++it; input_file_.open(*it); input = &input_file_; load_from_file = true; } else if (*it == "-v") { verbose = true; } else { break; } } // load from arguments - concatenate the rest of the args if (!load_from_file && it != args.end()) { std::string expr = *it++; for (; it != args.end(); ++it) expr += " " + *it; input_mem_ = std::stringstream{ expr }; input = &input_mem_; } } }; int main(int argc, char** argv) { options opt{ argc, argv }; if (opt.input != nullptr) { // parse and interpret the expression dice::logger log; dice::lexer lexer{ opt.input, &log }; dice::environment env; dice::interpreter<dice::environment> interpret{ &env }; auto parser = dice::make_parser(&lexer, &log, &interpret); auto result = parser.parse(); for (auto&& value : result) { std::string expr; std::getline(interpret.code(), expr); if (value != nullptr || opt.verbose) { std::cout << expr; if (value != nullptr) std::cout << ": "; } print_value(value.get()); if (value != nullptr || opt.verbose) { std::cout << std::endl; } } } else { std::cerr << "Dice expressions interpreter." << std::endl << std::endl << "Usage:" << std::endl << " ./dice_cli [options] [expression]" << std::endl << std::endl << " [options]:" << std::endl << " -f <file> load expression from file" << std::endl << " -v verbose output (show executed script)" << std::endl << std::endl << " [expression]:" << std::endl << " A dice expression. Can be in multiple arguments." << std::endl << " The program will join them wih a space." << std::endl; return 1; } return 0; }<commit_msg>Fix: sort values before printing<commit_after>#include <iostream> #include <sstream> #include <fstream> #include <algorithm> #include <vector> #include <iomanip> #include <cassert> #include "logger.hpp" #include "lexer.hpp" #include "parser.hpp" #include "environment.hpp" #include "interpreter.hpp" // conver a double value to percent std::string format_probability(double prob) { if (prob < 0.0001 && prob != 0) { return "< 0.01 %"; } return std::to_string(prob * 100) + " %"; } // value formatting functions void print(int value) { std::cout << value << std::endl; } void print(double value) { std::cout << value << std::endl; } template<typename ValueType, typename ProbabilityType> void print( const dice::random_variable_decomposition<ValueType, ProbabilityType>& var) { const int width_value = 10; const int width_prob = 15; const int width_cdf = 15; std::cout << std::endl << "\e[1m" << std::setw(width_value) << "Value" << "\e[1m" << std::setw(width_prob) << "PMF" << "\e[1m" << std::setw(width_cdf) << "CDF" << "\e[0m" << std::endl; std::vector<std::pair<ValueType, ProbabilityType>> values{ var.probability().begin(), var.probability().end() }; std::sort(values.begin(), values.end(), [](auto&& a, auto&& b) { return a.first < b.first; }); ProbabilityType sum = 0; for (auto&& pair : values) { std::cout << std::setw(width_value) << pair.first << std::setw(width_prob) << format_probability(pair.second) << std::setw(width_cdf) << format_probability(sum) << std::endl; sum += pair.second; } } /** Print computed value. * @param computed value */ void print_value(const dice::base_value* value) { if (value == nullptr) { return; } // print value auto int_value = dynamic_cast<const dice::type_int*>(value); if (int_value != nullptr) { print(int_value->data()); return; } auto double_value = dynamic_cast<const dice::type_double*>(value); if (double_value != nullptr) { print(double_value->data()); return; } auto var_value = dynamic_cast<const dice::type_rand_var*>(value); if (var_value != nullptr) { print(var_value->data()); return; } throw std::runtime_error("Unknown value."); } struct options { // Command line arguments std::vector<std::string> args; // Input stream std::istream* input; // Should we print the executed script? bool verbose; options(int argc, char** argv) : args(argv, argv + argc), input(nullptr), verbose(false) { parse(); } private: std::ifstream input_file_; std::stringstream input_mem_; void parse() { auto it = args.begin() + 1; // first arg is the file path bool load_from_file = false; for (; it != args.end(); ++it) { if (*it == "-f") // input file { assert(it + 1 != args.end()); ++it; input_file_.open(*it); input = &input_file_; load_from_file = true; } else if (*it == "-v") { verbose = true; } else { break; } } // load from arguments - concatenate the rest of the args if (!load_from_file && it != args.end()) { std::string expr = *it++; for (; it != args.end(); ++it) expr += " " + *it; input_mem_ = std::stringstream{ expr }; input = &input_mem_; } } }; int main(int argc, char** argv) { options opt{ argc, argv }; if (opt.input != nullptr) { // parse and interpret the expression dice::logger log; dice::lexer lexer{ opt.input, &log }; dice::environment env; dice::interpreter<dice::environment> interpret{ &env }; auto parser = dice::make_parser(&lexer, &log, &interpret); auto result = parser.parse(); for (auto&& value : result) { std::string expr; std::getline(interpret.code(), expr); if (value != nullptr || opt.verbose) { std::cout << expr; if (value != nullptr) std::cout << ": "; } print_value(value.get()); if (value != nullptr || opt.verbose) { std::cout << std::endl; } } } else { std::cerr << "Dice expressions interpreter." << std::endl << std::endl << "Usage:" << std::endl << " ./dice_cli [options] [expression]" << std::endl << std::endl << " [options]:" << std::endl << " -f <file> load expression from file" << std::endl << " -v verbose output (show executed script)" << std::endl << std::endl << " [expression]:" << std::endl << " A dice expression. Can be in multiple arguments." << std::endl << " The program will join them wih a space." << std::endl; return 1; } return 0; }<|endoftext|>
<commit_before>#include <iostream> #include <cstdlib> #include <vector> #include <string> //getlogin() and gethostname(). #include <unistd.h> //perror. #include <stdio.h> //fork,wait and execvp. #include <sys/types.h> #include <sys/wait.h> //boost! #include "boost/algorithm/string.hpp" #include "boost/tokenizer.hpp" #include "boost/foreach.hpp" //that one class. #include "Command.h" using namespace std; using namespace boost; //execute command. void execute(const vector<string> & s); //takes a string and returns vector of parsed string. vector<string> parseInput(string s); //display vector. template<typename unit> void display_vector(vector<unit> v); //helper function that finds amount of character. int find_char_amount(const string s,char c); //removes comment from input. void remove_comment(string &s); int main() { //grab the login. char* login = getlogin(); //start a flag. bool login_check = true; if((!login) != 0) { //check flag. login_check = false; //output error. perror("Error: could not retrieve login name"); } //hold c-string for host name. char host[150]; //start another flag. bool host_check = true; //gets hostname while checking if it actually grabbed it. if(gethostname(host,sizeof(host)) != 0) { //check flag. host_check = false; //output error. perror("Error: could not rerieve host name."); } //warn user of upcoming trouble. if(login_check == false || host_check == false) cout << "Unable to display login and/or host information." << endl; //string to hold user input. string input; while(true) { //output login@hostname. if(login_check && host_check) cout << login << '@' << host << ' '; //bash money. cout << "$ "; //placeholder to tell its the program. cout << " (program) "; //geting input as a string. getline(cin,input); //remove comments. cout << "Before: " << input << endl; //remove extra white space. trim(input); remove_comment(input); cout << "After: " << input << endl; //trim again just in case. trim(input); //break. if(input == "exit") exit(0); //testing parse. //cout << "Testing parse" << endl; //display_vector(parseInput(input)); //execute command. //execute(input); } cout << "End of program" << endl; return 0; } void execute(const vector<string> &s) { //c-string to hold command. char* args[2048]; //place and convert commands. for(unsigned int i = 0; i < s.size(); ++i) args[i] = (char*)s.at(i).c_str(); args[s.size()] = NULL; pid_t pid = fork(); if(pid == -1) { //fork didn't work. perror("fork"); } if(pid ==0) { if(execvp(args[0], args) == -1) { //execute didn't work. perror("execvp"); //break out of shadow realm. exit(1); } } if(pid > 0) { //wait for child to die. if(wait(0) == -1) { //didnt wait. perror("wait"); } } return; } vector<string> parseInput(string s) { //make temp vector to hold parsed strings. vector<string> temp; //create boost magic function. char_separator<char> sep(" ;||&(){}\"", ";||&()[]\"", keep_empty_tokens); //create boost magic holder thingy. tokenizer< char_separator<char> > cm(s,sep); //for each loop to grab each peice and push it into a vector. for(tokenizer< char_separator<char> >::iterator it = cm.begin(); it != cm.end(); ++it) if(*it != "") temp.push_back(*it); //return that vector. return temp; } template<typename unit> void display_vector(vector<unit> v) { for(unsigned int i = 0; i < v.size(); ++i) cout << i+1 << ": " << v.at(i) << endl; return; } void remove_comment(string &s) { //just add a " to the end to avoid errors. if(find_char_amount(s,'\"') %2 != 0) s += '\"'; //delete everything! if(s.find("#") == 0) { s = ""; return; } //return if no comments. if(s.find("#") == string::npos) { return; } //if no comments then delets everything from hash forward. if(s.find("\"") == string::npos && s.find("#") != string::npos) { s = s.substr(0,s.find("#")); return; } //if comment before quote then delete. if(s.find("\"") > s.find("#")) { s = s.substr(0,s.find("#")); return; } //advanced situations. //get a vector to hold positions of quotes and hash. vector<int> quotePos; vector<int> hashPos; //grab pos. for(unsigned int i = 0; i < s.size(); ++i) { if(s.at(i) == '\"') quotePos.push_back(i); else if(s.at(i) == '#') hashPos.push_back(i); } //hold pos for hash. int i = 0; //checks to see if in middle. bool check = true; //pos of lone hash. int pos = 0; for(unsigned int j = 0; j < quotePos.size() - 1; j += 2) { if(hashPos.at(i) > quotePos.at(j) && hashPos.at(i) < quotePos.at(j+1)) { check = true; ++i; } else { check = false; pos = hashPos.at(i); } } if(!check) { s = s.substr(0,pos); return; } if(hashPos.at(hashPos.size()-1) > quotePos.at(quotePos.size()-1)) s = s.substr(0,hashPos.at(hashPos.size()-1)); return; } int find_char_amount(const string s, char c) { if(s.find(c) == string::npos) return 0; int count = 0; for(unsigned int i = 0; i < s.size(); ++i) if(s.at(i) == c) count++; return count; } <commit_msg>added incomplete replace in string function to help parse comments<commit_after>#include <iostream> #include <cstdlib> #include <vector> #include <string> //getlogin() and gethostname(). #include <unistd.h> //perror. #include <stdio.h> //fork,wait and execvp. #include <sys/types.h> #include <sys/wait.h> //boost! #include "boost/algorithm/string.hpp" #include "boost/tokenizer.hpp" #include "boost/foreach.hpp" //that one class. #include "Command.h" using namespace std; using namespace boost; //execute command. void execute(const vector<string> & s); //replaces char in string. void replace_char(string &s, char o, char r); //takes a string and returns vector of parsed string. vector<string> parseInput(string s); //display vector. template<typename unit> void display_vector(vector<unit> v); //helper function that finds amount of character. int find_char_amount(const string s,char c); //removes comment from input. void remove_comment(string &s); int main() { //grab the login. char* login = getlogin(); //start a flag. bool login_check = true; if((!login) != 0) { //check flag. login_check = false; //output error. perror("Error: could not retrieve login name"); } //hold c-string for host name. char host[150]; //start another flag. bool host_check = true; //gets hostname while checking if it actually grabbed it. if(gethostname(host,sizeof(host)) != 0) { //check flag. host_check = false; //output error. perror("Error: could not rerieve host name."); } //warn user of upcoming trouble. if(login_check == false || host_check == false) cout << "Unable to display login and/or host information." << endl; //string to hold user input. string input; while(true) { //output login@hostname. if(login_check && host_check) cout << login << '@' << host << ' '; //bash money. cout << "$ "; //placeholder to tell its the program. cout << " (program) "; //geting input as a string. getline(cin,input); //remove extra white space. trim(input); //remove comments. remove_comment(input); //trim again just in case. trim(input); //break. if(input == "exit") exit(0); //testing parse. cout << "Testing parse" << endl; display_vector(parseInput(input)); //execute command. //execute(input); } cout << "End of program" << endl; return 0; } void execute(const vector<string> &s) { //c-string to hold command. char* args[2048]; //place and convert commands. for(unsigned int i = 0; i < s.size(); ++i) args[i] = (char*)s.at(i).c_str(); args[s.size()] = NULL; pid_t pid = fork(); if(pid == -1) { //fork didn't work. perror("fork"); } if(pid ==0) { if(execvp(args[0], args) == -1) { //execute didn't work. perror("execvp"); //break out of shadow realm. exit(1); } } if(pid > 0) { //wait for child to die. if(wait(0) == -1) { //didnt wait. perror("wait"); } } return; } vector<string> parseInput(string s) { //replace spaces. replace_char(s,' ','_'); //make temp vector to hold parsed strings. vector<string> temp; //create boost magic function. //char_separator<char> sep(" ;||&(){}\"", ";||&()[]\"", keep_empty_tokens); //test copy char_separator<char> sep(" ;||&&(){}", ";||&&()[]",keep_empty_tokens); //create boost magic holder thingy. tokenizer< char_separator<char> > cm(s,sep); //for each loop to grab each peice and push it into a vector. for(tokenizer< char_separator<char> >::iterator it = cm.begin(); it != cm.end(); ++it) if(*it != "") temp.push_back(*it); //return that vector. return temp; } void replace_char(string &s, char o, char r) { if(s.find("\"") != string::npos) for(unsigned int i = s.find("\""); i < s.find("\"",s.find("\"")+1);++i) if(s.at(i) == o) s.at(i) = r; return; } template<typename unit> void display_vector(vector<unit> v) { for(unsigned int i = 0; i < v.size(); ++i) cout << i+1 << ": " << v.at(i) << endl; return; } void remove_comment(string &s) { //just add a " to the end to avoid errors. if(find_char_amount(s,'\"') %2 != 0) s += '\"'; //delete everything! if(s.find("#") == 0) { s = ""; return; } //return if no comments. if(s.find("#") == string::npos) { return; } //if no comments then delets everything from hash forward. if(s.find("\"") == string::npos && s.find("#") != string::npos) { s = s.substr(0,s.find("#")); return; } //if comment before quote then delete. if(s.find("\"") > s.find("#")) { s = s.substr(0,s.find("#")); return; } //advanced situations. //get a vector to hold positions of quotes and hash. vector<int> quotePos; vector<int> hashPos; //grab pos. for(unsigned int i = 0; i < s.size(); ++i) { if(s.at(i) == '\"') quotePos.push_back(i); else if(s.at(i) == '#') hashPos.push_back(i); } //hold pos for hash. int i = 0; //checks to see if in middle. bool check = true; //pos of lone hash. int pos = 0; for(unsigned int j = 0; j < quotePos.size() - 1; j += 2) { if(hashPos.at(i) > quotePos.at(j) && hashPos.at(i) < quotePos.at(j+1)) { check = true; ++i; } else { check = false; pos = hashPos.at(i); } } if(!check) { s = s.substr(0,pos); return; } if(hashPos.at(hashPos.size()-1) > quotePos.at(quotePos.size()-1)) s = s.substr(0,hashPos.at(hashPos.size()-1)); return; } int find_char_amount(const string s, char c) { if(s.find(c) == string::npos) return 0; int count = 0; for(unsigned int i = 0; i < s.size(); ++i) if(s.at(i) == c) count++; return count; } <|endoftext|>
<commit_before>/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed in accordance with the terms specified in * the LICENSE file found in the root directory of this source tree. */ #include <gtest/gtest.h> #include <osquery/database.h> #include <osquery/flags.h> #include <osquery/registry_interface.h> #include <osquery/remote/tests/test_utils.h> #include <osquery/system.h> #include "plugins/logger/tls_logger.h" namespace osquery { DECLARE_bool(disable_database); class TLSLoggerTests : public testing::Test { protected: void SetUp() { Initializer::platformSetup(); registryAndPluginInit(); FLAGS_disable_database = true; DatabasePlugin::setAllowOpen(true); DatabasePlugin::initPlugin(); } public: void runCheck(const std::shared_ptr<TLSLogForwarder>& runner) { runner->check(); } }; TEST_F(TLSLoggerTests, test_database) { // Start a server. TLSServerRunner::start(); TLSServerRunner::setClientConfig(); auto forwarder = std::make_shared<TLSLogForwarder>(); std::string expected = "{\"new_json\": true}"; forwarder->logString(expected); StatusLogLine status; status.message = "{\"status\": \"bar\"}"; forwarder->logStatus({status}); // Stop the server. TLSServerRunner::unsetClientConfig(); TLSServerRunner::stop(); std::vector<std::string> indexes; scanDatabaseKeys(kLogs, indexes); EXPECT_EQ(2U, indexes.size()); // Iterate using an unordered search, and search for the expected string // that was just logged. bool found_string = false; for (const auto& index : indexes) { std::string value; getDatabaseValue(kLogs, index, value); found_string = (found_string || value == expected); deleteDatabaseValue(kLogs, index); } EXPECT_TRUE(found_string); } TEST_F(TLSLoggerTests, test_send) { // Start a server. TLSServerRunner::start(); TLSServerRunner::setClientConfig(); auto forwarder = std::make_shared<TLSLogForwarder>(); for (size_t i = 0; i < 20; i++) { std::string expected = "{\"more_json\": true}"; forwarder->logString(expected); } runCheck(forwarder); // Stop the server. TLSServerRunner::unsetClientConfig(); TLSServerRunner::stop(); } } // namespace osquery <commit_msg>Fix undefined-behavior in TLSLoggerTests.test_database<commit_after>/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed in accordance with the terms specified in * the LICENSE file found in the root directory of this source tree. */ #include <gtest/gtest.h> #include <osquery/database.h> #include <osquery/flags.h> #include <osquery/registry_interface.h> #include <osquery/remote/tests/test_utils.h> #include <osquery/system.h> #include "plugins/logger/tls_logger.h" namespace osquery { DECLARE_bool(disable_database); class TLSLoggerTests : public testing::Test { protected: void SetUp() { Initializer::platformSetup(); registryAndPluginInit(); FLAGS_disable_database = true; DatabasePlugin::setAllowOpen(true); DatabasePlugin::initPlugin(); } public: void runCheck(const std::shared_ptr<TLSLogForwarder>& runner) { runner->check(); } }; TEST_F(TLSLoggerTests, test_database) { // Start a server. TLSServerRunner::start(); TLSServerRunner::setClientConfig(); auto forwarder = std::make_shared<TLSLogForwarder>(); std::string expected = "{\"new_json\": true}"; forwarder->logString(expected); StatusLogLine status{}; status.message = "{\"status\": \"bar\"}"; forwarder->logStatus({status}); // Stop the server. TLSServerRunner::unsetClientConfig(); TLSServerRunner::stop(); std::vector<std::string> indexes; scanDatabaseKeys(kLogs, indexes); EXPECT_EQ(2U, indexes.size()); // Iterate using an unordered search, and search for the expected string // that was just logged. bool found_string = false; for (const auto& index : indexes) { std::string value; getDatabaseValue(kLogs, index, value); found_string = (found_string || value == expected); deleteDatabaseValue(kLogs, index); } EXPECT_TRUE(found_string); } TEST_F(TLSLoggerTests, test_send) { // Start a server. TLSServerRunner::start(); TLSServerRunner::setClientConfig(); auto forwarder = std::make_shared<TLSLogForwarder>(); for (size_t i = 0; i < 20; i++) { std::string expected = "{\"more_json\": true}"; forwarder->logString(expected); } runCheck(forwarder); // Stop the server. TLSServerRunner::unsetClientConfig(); TLSServerRunner::stop(); } } // namespace osquery <|endoftext|>
<commit_before><commit_msg>Drop PLDM response while handling a new PLDM request<commit_after><|endoftext|>
<commit_before>/********************************************************************** //File WanderCPP //Author Judicael Abecassis //Last modified 08/04/2017 15:58:03 //Definition http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **********************************************************************/ #pragma region Includes #include "wRoot.h" #include "wTime.h" #pragma endregion bool Wander::Root::startUp() { return true; } void Wander::Root::shutDown() { } void Wander::Root::run() { while (true) { } } <commit_msg>[Add] Gameloop skeleton<commit_after>/********************************************************************** //File WanderCPP //Author Judicael Abecassis //Last modified 08/04/2017 15:58:03 //Definition http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **********************************************************************/ #pragma region Includes #include "wRoot.h" #include "wTime.h" #pragma endregion bool Wander::Root::startUp() { return true; } void Wander::Root::shutDown() { } void Wander::Root::run() { Time ms_per_update(60000); //dirty Timer timer; Time elapsed; Time lag(0LL); while (true) { elapsed = timer.frame(); lag += elapsed; //processInput if (lag >= ms_per_update) { //Update gp lag -= ms_per_update; } //render(lag/ms_per_update) } } <|endoftext|>
<commit_before>#include <QString> #include <QSharedPointer> #include <QVector> #include <QUrl> #include <QFileInfo> #include <qtconcurrentmap.h> #include <QCoreApplication> #include "kernel.h" #include "ilwisdata.h" #include "abstractfactory.h" #include "connectorinterface.h" #include "connectorfactory.h" #include "mastercatalog.h" #include "ilwisobjectconnector.h" #include "catalogconnector.h" #include "catalogexplorer.h" #include "domain.h" #include "datadefinition.h" #include "columndefinition.h" #include "table.h" #include "catalog.h" #include "dataset.h" using namespace Ilwis; CatalogConnector::CatalogConnector(const Resource &resource, bool load , const IOOptions &options) : IlwisObjectConnector(resource, load, options) { } bool CatalogConnector::isValid() const { return source().isValid(); } bool CatalogConnector::canUse(const Resource &resource) const { if (_dataProviders.size() == 0) const_cast<CatalogConnector *>(this)->loadExplorers(); for(const auto& explorer : _dataProviders){ if (explorer->canUse(resource)) return true; } return false; } QFileInfo CatalogConnector::toLocalFile(const QUrl &url) const { QString local = url.toLocalFile(); QFileInfo localFile(local); if ( localFile.exists()) return local; int index = local.lastIndexOf("/"); if ( index == -1){ return QFileInfo(); } QString parent = local.left(index); QString ownSection = local.right(local.size() - index - 1); if (Ilwis::Resource::isRoot(parent)){ // we are at the root; '/'has been removed and has to be added again; recursion ends here return local; // we return local here as we don't need to reconstruct our path. local is directly attached to the root and thus has sufficient info } QUrl parentUrl(QUrl::fromLocalFile(parent)); quint64 id = mastercatalog()->url2id(parentUrl, itCATALOG); if ( id == i64UNDEF) return localFile; //return QFileInfo(parent); Resource parentResource = mastercatalog()->id2Resource(id); QFileInfo parentPath = parentResource.toLocalFile(); if ( parentPath.fileName() == sUNDEF) parentPath = parent; QFileInfo currentPath(parentPath.absoluteFilePath() + "/"+ ownSection); return currentPath; } QFileInfo CatalogConnector::toLocalFile(const Resource &resource) const { QFileInfo currentPath = toLocalFile(resource.url()); if ( !currentPath.exists()){ for(const auto& explorer: _dataProviders) { if ( explorer->canUse(resource)){ return explorer->resolve2Local(); } } } return currentPath; } QString CatalogConnector::provider() const { return "ilwis"; } ConnectorInterface *CatalogConnector::create(const Ilwis::Resource &resource, bool load, const IOOptions& options) { return new CatalogConnector(resource, load, options); } bool CatalogConnector::loadMetaData(IlwisObject *data,const IOOptions &) { return loadExplorers(); } bool CatalogConnector::loadData(IlwisObject *obj, const IOOptions &options){ //outside the mainthread we already run things multithreaded. we are not going to put threads in threads as this only // gives problems with trhead affinity // if ( QCoreApplication::instance()->thread() == QThread::currentThread()){ return loadDataThreaded(obj,options); // } // return loadDataSingleThread(obj,options); } bool CatalogConnector::loadDataSingleThread(IlwisObject *obj, const IOOptions &options){ Catalog *cat = static_cast<Catalog *>(obj); kernel()->issues()->log(QString(TR("Scanning %1")).arg(source().url(true).toString()),IssueObject::itMessage); QVector<std::pair<CatalogExplorer *, IOOptions>> explorers; for(const auto& explorer : _dataProviders){ // TODO clear security issues which may arise here, as // all _dataProviders gets passed the ioptions probably // not indendet for them IOOptions iooptions = options.isEmpty() ? ioOptions() : options; std::vector<Resource> items = explorer->loadItems(iooptions); cat->addItemsPrivate(items); mastercatalog()->addItems(items); } return true; } std::vector<Resource> loadExplorerData(const std::pair<CatalogExplorer *, IOOptions>& expl){ try { std::vector<Resource> items = expl.first->loadItems(expl.second); return items; } catch (const ErrorObject& err){ } return std::vector<Resource>(); } void gatherData(std::vector<Resource>& outputItems, const std::vector<Resource>& inputItems){ std::copy(inputItems.begin(), inputItems.end(), std::back_inserter(outputItems)); } bool CatalogConnector::loadDataThreaded(IlwisObject *obj, const IOOptions &options){ Catalog *cat = static_cast<Catalog *>(obj); kernel()->issues()->log(QString(TR("Scanning %1")).arg(source().url(true).toString()),IssueObject::itMessage); QVector<std::pair<CatalogExplorer *, IOOptions>> explorers; for(const auto& explorer : _dataProviders){ explorers.push_back({explorer.get(), options}); } QFuture<std::vector<Resource>> res = QtConcurrent::mappedReduced(explorers,loadExplorerData, gatherData); res.waitForFinished(); cat->addItemsPrivate(res.result()); mastercatalog()->addItems(res.result()); return true; } Ilwis::IlwisObject *CatalogConnector::create() const { if ( source().hasProperty("domain")) return new DataSet(source()); return new Catalog(source()); } bool CatalogConnector::loadExplorers() { if ( _dataProviders.size() > 0) // already done return true; const Ilwis::ConnectorFactory *factory = kernel()->factory<Ilwis::ConnectorFactory>("ilwis::ConnectorFactory"); std::vector<CatalogExplorer*> explorers = factory->explorersForResource(source()); if ( explorers.size() == 0) { return ERROR2(ERR_COULDNT_CREATE_OBJECT_FOR_2,"Catalog connector", source().toLocalFile()); } _dataProviders.resize(explorers.size()); int i =0; for(CatalogExplorer *explorer : explorers) { _dataProviders[i++].reset(explorer); } return true; } <commit_msg>decides now, based on the runmode how the catalogs are read. multithreaded or single threaded<commit_after>#include <QString> #include <QSharedPointer> #include <QVector> #include <QUrl> #include <QFileInfo> #include <qtconcurrentmap.h> #include <QCoreApplication> #include "kernel.h" #include "ilwisdata.h" #include "abstractfactory.h" #include "connectorinterface.h" #include "connectorfactory.h" #include "mastercatalog.h" #include "ilwisobjectconnector.h" #include "catalogconnector.h" #include "catalogexplorer.h" #include "domain.h" #include "datadefinition.h" #include "columndefinition.h" #include "ilwiscontext.h" #include "table.h" #include "catalog.h" #include "dataset.h" using namespace Ilwis; CatalogConnector::CatalogConnector(const Resource &resource, bool load , const IOOptions &options) : IlwisObjectConnector(resource, load, options) { } bool CatalogConnector::isValid() const { return source().isValid(); } bool CatalogConnector::canUse(const Resource &resource) const { if (_dataProviders.size() == 0) const_cast<CatalogConnector *>(this)->loadExplorers(); for(const auto& explorer : _dataProviders){ if (explorer->canUse(resource)) return true; } return false; } QFileInfo CatalogConnector::toLocalFile(const QUrl &url) const { QString local = url.toLocalFile(); QFileInfo localFile(local); if ( localFile.exists()) return local; int index = local.lastIndexOf("/"); if ( index == -1){ return QFileInfo(); } QString parent = local.left(index); QString ownSection = local.right(local.size() - index - 1); if (Ilwis::Resource::isRoot(parent)){ // we are at the root; '/'has been removed and has to be added again; recursion ends here return local; // we return local here as we don't need to reconstruct our path. local is directly attached to the root and thus has sufficient info } QUrl parentUrl(QUrl::fromLocalFile(parent)); quint64 id = mastercatalog()->url2id(parentUrl, itCATALOG); if ( id == i64UNDEF) return localFile; //return QFileInfo(parent); Resource parentResource = mastercatalog()->id2Resource(id); QFileInfo parentPath = parentResource.toLocalFile(); if ( parentPath.fileName() == sUNDEF) parentPath = parent; QFileInfo currentPath(parentPath.absoluteFilePath() + "/"+ ownSection); return currentPath; } QFileInfo CatalogConnector::toLocalFile(const Resource &resource) const { QFileInfo currentPath = toLocalFile(resource.url()); if ( !currentPath.exists()){ for(const auto& explorer: _dataProviders) { if ( explorer->canUse(resource)){ return explorer->resolve2Local(); } } } return currentPath; } QString CatalogConnector::provider() const { return "ilwis"; } ConnectorInterface *CatalogConnector::create(const Ilwis::Resource &resource, bool load, const IOOptions& options) { return new CatalogConnector(resource, load, options); } bool CatalogConnector::loadMetaData(IlwisObject *data,const IOOptions &) { return loadExplorers(); } bool CatalogConnector::loadData(IlwisObject *obj, const IOOptions &options){ if ( context()->runMode() == rmDESKTOP){ return loadDataThreaded(obj,options); } return loadDataSingleThread(obj,options); } bool CatalogConnector::loadDataSingleThread(IlwisObject *obj, const IOOptions &options){ Catalog *cat = static_cast<Catalog *>(obj); kernel()->issues()->log(QString(TR("Scanning %1")).arg(source().url(true).toString()),IssueObject::itMessage); QVector<std::pair<CatalogExplorer *, IOOptions>> explorers; for(const auto& explorer : _dataProviders){ // TODO clear security issues which may arise here, as // all _dataProviders gets passed the ioptions probably // not indendet for them IOOptions iooptions = options.isEmpty() ? ioOptions() : options; std::vector<Resource> items = explorer->loadItems(iooptions); cat->addItemsPrivate(items); mastercatalog()->addItems(items); } return true; } std::vector<Resource> loadExplorerData(const std::pair<CatalogExplorer *, IOOptions>& expl){ try { std::vector<Resource> items = expl.first->loadItems(expl.second); return items; } catch (const ErrorObject& err){ } return std::vector<Resource>(); } void gatherData(std::vector<Resource>& outputItems, const std::vector<Resource>& inputItems){ std::copy(inputItems.begin(), inputItems.end(), std::back_inserter(outputItems)); } bool CatalogConnector::loadDataThreaded(IlwisObject *obj, const IOOptions &options){ Catalog *cat = static_cast<Catalog *>(obj); kernel()->issues()->log(QString(TR("Scanning %1")).arg(source().url(true).toString()),IssueObject::itMessage); QVector<std::pair<CatalogExplorer *, IOOptions>> explorers; for(const auto& explorer : _dataProviders){ explorers.push_back({explorer.get(), options}); } QFuture<std::vector<Resource>> res = QtConcurrent::mappedReduced(explorers,loadExplorerData, gatherData); res.waitForFinished(); cat->addItemsPrivate(res.result()); mastercatalog()->addItems(res.result()); return true; } Ilwis::IlwisObject *CatalogConnector::create() const { if ( source().hasProperty("domain")) return new DataSet(source()); return new Catalog(source()); } bool CatalogConnector::loadExplorers() { if ( _dataProviders.size() > 0) // already done return true; const Ilwis::ConnectorFactory *factory = kernel()->factory<Ilwis::ConnectorFactory>("ilwis::ConnectorFactory"); std::vector<CatalogExplorer*> explorers = factory->explorersForResource(source()); if ( explorers.size() == 0) { return ERROR2(ERR_COULDNT_CREATE_OBJECT_FOR_2,"Catalog connector", source().toLocalFile()); } _dataProviders.resize(explorers.size()); int i =0; for(CatalogExplorer *explorer : explorers) { _dataProviders[i++].reset(explorer); } return true; } <|endoftext|>
<commit_before>/** * v8cgi - apache module. * Extends v8cgi_App by adding customized initialization and (std)IO routines */ #include <stdlib.h> #include <string.h> #include "httpd.h" #include "http_config.h" #include "http_log.h" #include "http_protocol.h" #include "util_script.h" #include "apr_pools.h" #include "js_app.h" #include "js_path.h" #include "js_macros.h" typedef struct { const char * config; } v8cgi_config; /** * First module declaration */ extern "C" module AP_MODULE_DECLARE_DATA v8cgi_module; class v8cgi_Module : public v8cgi_App { public: size_t reader(char * destination, size_t amount) { return (size_t) ap_get_client_block(this->request, destination, amount); } size_t writer(const char * data, size_t amount) { if (this->output_started) { /* response data */ return (size_t) ap_rwrite(data, amount, this->request); } else { /* header or content separator */ char * end = strchr((char *) data, '\r'); if (!end) { end = strchr((char *) data, '\n'); } /* header or separator must end with a newline */ if (!end) { return 0; } if (end == data) { /* content separator */ this->output_started = true; return 0; } else { /* header */ char * colon = strchr((char *) data, ':'); /* header without colon is a bad header */ if (!colon) { return 0; } size_t namelen = colon - data; /* skip space after colon */ if ((size_t) (colon-data+1) < amount && *(colon+1) == ' ') { colon++; } size_t valuelen = end - colon - 1; char * name = (char *) apr_palloc(request->pool, namelen + 1); char * value = (char *) apr_palloc(request->pool, valuelen + 1); name[namelen] = '\0'; value[valuelen] = '\0'; strncpy(name, data, namelen); strncpy(value, colon+1, valuelen); this->header(name, value); return (size_t) amount; } } } /** * We log errors to apache errorlog */ void error(const char * data, const char * file, int line) { ap_log_rerror(file, line, APLOG_ERR, 0, this->request, "%s", data); } /** * Remember apache request structure and continue as usually */ int execute(request_rec * request, char ** envp) { this->output_started = false; this->request = request; this->mainfile = std::string(request->filename); path_chdir(path_dirname(this->mainfile)); return v8cgi_App::execute(envp); } void init(v8cgi_config * cfg) { v8cgi_App::init(); this->cfgfile = cfg->config; } private: request_rec * request; bool output_started; /** * Set a HTTP response header * @param {char *} name * @param {char *} value */ void header(const char * name, const char * value) { if (strcasecmp(name, "content-type") == 0) { char * ct = (char *) apr_palloc(request->pool, strlen(value)+1); strcpy(ct, value); this->request->content_type = ct; } else if (strcasecmp(name, "status") == 0) { char * line = (char *) apr_palloc(request->pool, strlen(value)+1); strcpy(line, value); this->request->status_line = line; this->request->status = atoi(value); } else { apr_table_set(this->request->headers_out, name, value); } } }; static v8cgi_Module app; /** * This is called from Apache every time request arrives */ static int mod_v8cgi_handler(request_rec *r) { const apr_array_header_t *arr; const apr_table_entry_t *elts; if (!r->handler || strcmp(r->handler, "v8cgi-script")) { return DECLINED; } ap_setup_client_block(r, REQUEST_CHUNKED_DECHUNK); ap_add_common_vars(r); ap_add_cgi_vars(r); /* extract the CGI environment */ arr = apr_table_elts(r->subprocess_env); elts = (const apr_table_entry_t*) arr->elts; char ** envp = new char *[arr->nelts + 1]; envp[arr->nelts] = NULL; size_t size = 0; size_t len1 = 0; size_t len2 = 0; for (int i=0;i<arr->nelts;i++) { len1 = strlen(elts[i].key); len2 = strlen(elts[i].val); size = len1 + len2 + 2; envp[i] = new char[size]; envp[i][size-1] = '\0'; envp[i][len1] = '='; strncpy(envp[i], elts[i].key, len1); strncpy(&(envp[i][len1+1]), elts[i].val, len2); } app.execute(r, envp); for (int i=0;i<arr->nelts;i++) { free(envp[i]); } free(envp); // Ok is safer, because HTTP_INTERNAL_SERVER_ERROR overwrites any content already generated // if (result) { // return HTTP_INTERNAL_SERVER_ERROR; // } else { return OK; // } } /** * Module initialization */ static int mod_v8cgi_init_handler(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s) { ap_add_version_component(p, "mod_v8cgi"); v8cgi_config * cfg = (v8cgi_config *) ap_get_module_config(s->module_config, &v8cgi_module); app.init(cfg); return OK; } /** * Child initialization * FIXME: what is this for? */ static void mod_v8cgi_child_init(apr_pool_t *p, server_rec *s) { } /** * Register relevant hooks */ static void mod_v8cgi_register_hooks(apr_pool_t *p ) { ap_hook_handler(mod_v8cgi_handler, NULL, NULL, APR_HOOK_MIDDLE); ap_hook_post_config(mod_v8cgi_init_handler, NULL, NULL, APR_HOOK_MIDDLE); ap_hook_child_init(mod_v8cgi_child_init, NULL, NULL, APR_HOOK_MIDDLE); } /** * Create initial configuration values */ static void * mod_v8cgi_create_config(apr_pool_t *p, server_rec *s) { v8cgi_config * newcfg = (v8cgi_config *) apr_pcalloc(p, sizeof(v8cgi_config)); newcfg->config = STRING(CONFIG_PATH); return (void *) newcfg; } /** * Callback executed for every configuration change */ static const char * set_v8cgi_config(cmd_parms * parms, void * mconfig, const char * arg) { v8cgi_config * cfg = (v8cgi_config *) ap_get_module_config(parms->server->module_config, &v8cgi_module); cfg->config = (char *) arg; return NULL; } typedef const char * (* CONFIG_HANDLER) (); /* list of configurations */ static const command_rec mod_v8cgi_cmds[] = { AP_INIT_TAKE1( "v8cgi_Config", (CONFIG_HANDLER) set_v8cgi_config, NULL, RSRC_CONF, "Path to v8cgi configuration file." ), {NULL} }; /** * Module (re-)declaration */ extern "C" { module AP_MODULE_DECLARE_DATA v8cgi_module = { STANDARD20_MODULE_STUFF, NULL, NULL, mod_v8cgi_create_config, NULL, mod_v8cgi_cmds, mod_v8cgi_register_hooks, }; } <commit_msg>support for http basic auth variables, thanks to neocoder<commit_after>/** * v8cgi - apache module. * Extends v8cgi_App by adding customized initialization and (std)IO routines */ #include <stdlib.h> #include <string.h> #include "httpd.h" #include "http_config.h" #include "http_log.h" #include "http_protocol.h" #include "util_script.h" #include "apr_pools.h" #include "apr_base64.h" #include "apr_strings.h" #include "js_app.h" #include "js_path.h" #include "js_macros.h" typedef struct { const char * config; } v8cgi_config; /** * First module declaration */ extern "C" module AP_MODULE_DECLARE_DATA v8cgi_module; class v8cgi_Module : public v8cgi_App { public: size_t reader(char * destination, size_t amount) { return (size_t) ap_get_client_block(this->request, destination, amount); } size_t writer(const char * data, size_t amount) { if (this->output_started) { /* response data */ return (size_t) ap_rwrite(data, amount, this->request); } else { /* header or content separator */ char * end = strchr((char *) data, '\r'); if (!end) { end = strchr((char *) data, '\n'); } /* header or separator must end with a newline */ if (!end) { return 0; } if (end == data) { /* content separator */ this->output_started = true; return 0; } else { /* header */ char * colon = strchr((char *) data, ':'); /* header without colon is a bad header */ if (!colon) { return 0; } size_t namelen = colon - data; /* skip space after colon */ if ((size_t) (colon-data+1) < amount && *(colon+1) == ' ') { colon++; } size_t valuelen = end - colon - 1; char * name = (char *) apr_palloc(request->pool, namelen + 1); char * value = (char *) apr_palloc(request->pool, valuelen + 1); name[namelen] = '\0'; value[valuelen] = '\0'; strncpy(name, data, namelen); strncpy(value, colon+1, valuelen); this->header(name, value); return (size_t) amount; } } } /** * We log errors to apache errorlog */ void error(const char * data, const char * file, int line) { ap_log_rerror(file, line, APLOG_ERR, 0, this->request, "%s", data); } /** * Remember apache request structure and continue as usually */ int execute(request_rec * request, char ** envp) { this->output_started = false; this->request = request; this->mainfile = std::string(request->filename); path_chdir(path_dirname(this->mainfile)); return v8cgi_App::execute(envp); } void init(v8cgi_config * cfg) { v8cgi_App::init(); this->cfgfile = cfg->config; } private: request_rec * request; bool output_started; /** * Set a HTTP response header * @param {char *} name * @param {char *} value */ void header(const char * name, const char * value) { if (strcasecmp(name, "content-type") == 0) { char * ct = (char *) apr_palloc(request->pool, strlen(value)+1); strcpy(ct, value); this->request->content_type = ct; } else if (strcasecmp(name, "status") == 0) { char * line = (char *) apr_palloc(request->pool, strlen(value)+1); strcpy(line, value); this->request->status_line = line; this->request->status = atoi(value); } else { apr_table_set(this->request->headers_out, name, value); } } }; static v8cgi_Module app; /** * This is called from Apache every time request arrives */ static int mod_v8cgi_handler(request_rec *r) { const apr_array_header_t *arr; const apr_table_entry_t *elts; if (!r->handler || strcmp(r->handler, "v8cgi-script")) { return DECLINED; } ap_setup_client_block(r, REQUEST_CHUNKED_DECHUNK); ap_add_common_vars(r); ap_add_cgi_vars(r); if (r->headers_in) { const char *auth; auth = apr_table_get(r->headers_in, "Authorization"); if (auth && auth[0] != 0 && strncmp(auth, "Basic ", 6) == 0) { char *user = NULL; char *pass = NULL; int length; user = (char *)apr_palloc(r->pool, apr_base64_decode_len(auth+6) + 1); length = apr_base64_decode(user, auth + 6); /* Null-terminate the string. */ user[length] = '\0'; if (user) { pass = strchr(user, ':'); if (pass) { *pass++ = '\0'; apr_table_setn(r->subprocess_env, "AUTH_USER", user); apr_table_setn(r->subprocess_env, "AUTH_PW", pass); } } } } /* extract the CGI environment */ arr = apr_table_elts(r->subprocess_env); elts = (const apr_table_entry_t*) arr->elts; char ** envp = new char *[arr->nelts + 1]; envp[arr->nelts] = NULL; size_t size = 0; size_t len1 = 0; size_t len2 = 0; for (int i=0;i<arr->nelts;i++) { len1 = strlen(elts[i].key); len2 = strlen(elts[i].val); size = len1 + len2 + 2; envp[i] = new char[size]; envp[i][size-1] = '\0'; envp[i][len1] = '='; strncpy(envp[i], elts[i].key, len1); strncpy(&(envp[i][len1+1]), elts[i].val, len2); } app.execute(r, envp); for (int i=0;i<arr->nelts;i++) { free(envp[i]); } free(envp); // Ok is safer, because HTTP_INTERNAL_SERVER_ERROR overwrites any content already generated // if (result) { // return HTTP_INTERNAL_SERVER_ERROR; // } else { return OK; // } } /** * Module initialization */ static int mod_v8cgi_init_handler(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s) { ap_add_version_component(p, "mod_v8cgi"); v8cgi_config * cfg = (v8cgi_config *) ap_get_module_config(s->module_config, &v8cgi_module); app.init(cfg); return OK; } /** * Child initialization * FIXME: what is this for? */ static void mod_v8cgi_child_init(apr_pool_t *p, server_rec *s) { } /** * Register relevant hooks */ static void mod_v8cgi_register_hooks(apr_pool_t *p ) { ap_hook_handler(mod_v8cgi_handler, NULL, NULL, APR_HOOK_MIDDLE); ap_hook_post_config(mod_v8cgi_init_handler, NULL, NULL, APR_HOOK_MIDDLE); ap_hook_child_init(mod_v8cgi_child_init, NULL, NULL, APR_HOOK_MIDDLE); } /** * Create initial configuration values */ static void * mod_v8cgi_create_config(apr_pool_t *p, server_rec *s) { v8cgi_config * newcfg = (v8cgi_config *) apr_pcalloc(p, sizeof(v8cgi_config)); newcfg->config = STRING(CONFIG_PATH); return (void *) newcfg; } /** * Callback executed for every configuration change */ static const char * set_v8cgi_config(cmd_parms * parms, void * mconfig, const char * arg) { v8cgi_config * cfg = (v8cgi_config *) ap_get_module_config(parms->server->module_config, &v8cgi_module); cfg->config = (char *) arg; return NULL; } typedef const char * (* CONFIG_HANDLER) (); /* list of configurations */ static const command_rec mod_v8cgi_cmds[] = { AP_INIT_TAKE1( "v8cgi_Config", (CONFIG_HANDLER) set_v8cgi_config, NULL, RSRC_CONF, "Path to v8cgi configuration file." ), {NULL} }; /** * Module (re-)declaration */ extern "C" { module AP_MODULE_DECLARE_DATA v8cgi_module = { STANDARD20_MODULE_STUFF, NULL, NULL, mod_v8cgi_create_config, NULL, mod_v8cgi_cmds, mod_v8cgi_register_hooks, }; } <|endoftext|>
<commit_before>/* Copyright (C) 2006 by Kapoulkine Arseny 2007 by Marten Svanfeldt This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "factory.h" #include "cell.h" #include "terrainsystem.h" CS_PLUGIN_NAMESPACE_BEGIN(Terrain2) { csTerrainFactory::csTerrainFactory (iMeshObjectType *pParent) : scfImplementationType (this), type (pParent), defaultCell (0, 128, 128, 128, 128, false, csVector2 (0, 0), csVector3 (128, 32, 128), 0, 0, 0), logParent (0), maxLoadedCells (~0), virtualViewDistance (2.0f), autoPreLoad (false) { } csTerrainFactory::~csTerrainFactory () { } csFlags& csTerrainFactory::GetFlags () { return flags; } csPtr<iMeshObject> csTerrainFactory::NewInstance () { csTerrainSystem* terrain = new csTerrainSystem (this, renderer, collider, dataFeeder); terrain->SetMaxLoadedCells (maxLoadedCells); terrain->SetVirtualViewDistance (virtualViewDistance); terrain->SetAutoPreLoad (autoPreLoad); for (size_t i = 0; i < cells.GetSize (); ++i) { csRef<csTerrainCell> c = cells[i]->CreateCell (terrain); terrain->AddCell (c); } return csPtr<iMeshObject> (terrain); } csPtr<iMeshObjectFactory> csTerrainFactory::Clone () { return csPtr<iMeshObjectFactory> (new csTerrainFactory (*this)); } void csTerrainFactory::HardTransform (const csReversibleTransform& t) { } bool csTerrainFactory::SupportsHardTransform () const { return false; } void csTerrainFactory::SetMeshFactoryWrapper (iMeshFactoryWrapper* lp) { logParent = lp; } iMeshFactoryWrapper* csTerrainFactory::GetMeshFactoryWrapper () const { return logParent; } iMeshObjectType* csTerrainFactory::GetMeshObjectType () const { return type; } iObjectModel* csTerrainFactory::GetObjectModel () { return 0; } bool csTerrainFactory::SetMaterialWrapper (iMaterialWrapper* material) { return false; } iMaterialWrapper* csTerrainFactory::GetMaterialWrapper () const { return 0; } void csTerrainFactory::SetMixMode (uint mode) { } uint csTerrainFactory::GetMixMode () const { return 0; } void csTerrainFactory::SetRenderer (iTerrainRenderer* renderer) { this->renderer = renderer; csRef<iTerrainCellRenderProperties> renderProp = renderer ? renderer->CreateProperties () : 0; defaultCell.SetRenderProperties (renderProp); } void csTerrainFactory::SetCollider (iTerrainCollider* collider) { this->collider = collider; csRef<iTerrainCellCollisionProperties> collProp = collider ? collider->CreateProperties () : 0; defaultCell.SetCollisionProperties (collProp); } void csTerrainFactory::SetFeeder (iTerrainDataFeeder* feeder) { this->dataFeeder = feeder; csRef<iTerrainCellFeederProperties> feederProp = dataFeeder ? dataFeeder->CreateProperties () : 0; defaultCell.SetFeederProperties (feederProp); } iTerrainFactoryCell* csTerrainFactory::GetCell (const char* name) { for (size_t i = 0; i < cells.GetSize(); i++) { const char* cellName = cells[i]->GetName(); if (cellName == 0) continue; if (strcmp (cellName, name) == 0) return cells[i]; } return 0; } iTerrainFactoryCell* csTerrainFactory::AddCell(const char* name, int gridWidth, int gridHeight, int materialMapWidth, int materialMapHeight, bool materialMapPersistent, const csVector2& position, const csVector3& size) { csRef<csTerrainFactoryCell> cell; csRef<iTerrainCellRenderProperties> renderProp = renderer ? renderer->CreateProperties () : 0; csRef<iTerrainCellCollisionProperties> collProp = collider ? collider->CreateProperties () : 0; csRef<iTerrainCellFeederProperties> feederProp = dataFeeder ? dataFeeder->CreateProperties () : 0; cell.AttachNew (new csTerrainFactoryCell (name, gridWidth, gridHeight, materialMapWidth, materialMapHeight, materialMapPersistent, position, size, renderProp, collProp, feederProp)); cells.Push (cell); return cell; } iTerrainFactoryCell* csTerrainFactory::AddCell() { csRef<csTerrainFactoryCell> cell; csRef<iTerrainCellRenderProperties> renderProp = renderer ? renderer->CreateProperties () : 0; csRef<iTerrainCellCollisionProperties> collProp = collider ? collider->CreateProperties () : 0; csRef<iTerrainCellFeederProperties> feederProp = dataFeeder ? dataFeeder->CreateProperties () : 0; cell.AttachNew (new csTerrainFactoryCell (defaultCell)); cells.Push (cell); return cell; } void csTerrainFactory::SetMaxLoadedCells (size_t value) { maxLoadedCells = value; } void csTerrainFactory::SetVirtualViewDistance (float distance) { virtualViewDistance = distance; } void csTerrainFactory::SetAutoPreLoad (bool mode) { autoPreLoad = mode; } csTerrainFactoryCell::csTerrainFactoryCell (const char* name, int gridWidth, int gridHeight, int materialMapWidth, int materialMapHeight, bool materialMapPersistent, const csVector2& position, const csVector3& size, iTerrainCellRenderProperties* renderProp, iTerrainCellCollisionProperties* collisionProp, iTerrainCellFeederProperties* feederProp) : scfImplementationType (this), name (name), position (position), size (size), gridWidth (gridWidth), gridHeight (gridHeight), materialMapWidth (materialMapWidth), materialMapHeight (materialMapHeight), materialMapPersistent (materialMapPersistent), rendererProperties (renderProp), colliderProperties (collisionProp), feederProperties (feederProp) { } csTerrainFactoryCell::csTerrainFactoryCell (const csTerrainFactoryCell& other) : scfImplementationType (this), name (other.name), position (other.position), size (other.size), gridWidth (other.gridWidth), gridHeight (other.gridHeight), materialMapWidth (other.materialMapWidth), materialMapHeight (other.materialMapHeight), materialMapPersistent (other.materialMapPersistent), baseMaterial (other.baseMaterial), rendererProperties (other.rendererProperties), colliderProperties (other.colliderProperties), feederProperties (other.feederProperties) { } csPtr<csTerrainCell> csTerrainFactoryCell::CreateCell (csTerrainSystem* terrain) { csTerrainCell* cell; csRef<iTerrainCellRenderProperties> renderProp = rendererProperties ? rendererProperties->Clone () : 0; csRef<iTerrainCellCollisionProperties> collProp = colliderProperties ? colliderProperties->Clone () : 0; csRef<iTerrainCellFeederProperties> feederProp = feederProperties ? feederProperties->Clone () : 0; cell = new csTerrainCell (terrain, name.GetData (), gridWidth, gridHeight, materialMapWidth, materialMapHeight, materialMapPersistent, position, size, renderProp, collProp, feederProp); cell->SetBaseMaterial (baseMaterial); return csPtr<csTerrainCell> (cell); } iTerrainCellRenderProperties* csTerrainFactoryCell::GetRenderProperties () const { return rendererProperties; } iTerrainCellCollisionProperties* csTerrainFactoryCell::GetCollisionProperties () const { return colliderProperties; } iTerrainCellFeederProperties* csTerrainFactoryCell::GetFeederProperties () const { return feederProperties; } void csTerrainFactoryCell::SetBaseMaterial (iMaterialWrapper* material) { baseMaterial = material; } } CS_PLUGIN_NAMESPACE_END(Terrain2) <commit_msg>Fix factory cell creation to use property clones of the default cell props<commit_after>/* Copyright (C) 2006 by Kapoulkine Arseny 2007 by Marten Svanfeldt This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "factory.h" #include "cell.h" #include "terrainsystem.h" CS_PLUGIN_NAMESPACE_BEGIN(Terrain2) { csTerrainFactory::csTerrainFactory (iMeshObjectType *pParent) : scfImplementationType (this), type (pParent), defaultCell (0, 128, 128, 128, 128, false, csVector2 (0, 0), csVector3 (128, 32, 128), 0, 0, 0), logParent (0), maxLoadedCells (~0), virtualViewDistance (2.0f), autoPreLoad (false) { } csTerrainFactory::~csTerrainFactory () { } csFlags& csTerrainFactory::GetFlags () { return flags; } csPtr<iMeshObject> csTerrainFactory::NewInstance () { csTerrainSystem* terrain = new csTerrainSystem (this, renderer, collider, dataFeeder); terrain->SetMaxLoadedCells (maxLoadedCells); terrain->SetVirtualViewDistance (virtualViewDistance); terrain->SetAutoPreLoad (autoPreLoad); for (size_t i = 0; i < cells.GetSize (); ++i) { csRef<csTerrainCell> c = cells[i]->CreateCell (terrain); terrain->AddCell (c); } return csPtr<iMeshObject> (terrain); } csPtr<iMeshObjectFactory> csTerrainFactory::Clone () { return csPtr<iMeshObjectFactory> (new csTerrainFactory (*this)); } void csTerrainFactory::HardTransform (const csReversibleTransform& t) { } bool csTerrainFactory::SupportsHardTransform () const { return false; } void csTerrainFactory::SetMeshFactoryWrapper (iMeshFactoryWrapper* lp) { logParent = lp; } iMeshFactoryWrapper* csTerrainFactory::GetMeshFactoryWrapper () const { return logParent; } iMeshObjectType* csTerrainFactory::GetMeshObjectType () const { return type; } iObjectModel* csTerrainFactory::GetObjectModel () { return 0; } bool csTerrainFactory::SetMaterialWrapper (iMaterialWrapper* material) { return false; } iMaterialWrapper* csTerrainFactory::GetMaterialWrapper () const { return 0; } void csTerrainFactory::SetMixMode (uint mode) { } uint csTerrainFactory::GetMixMode () const { return 0; } void csTerrainFactory::SetRenderer (iTerrainRenderer* renderer) { this->renderer = renderer; csRef<iTerrainCellRenderProperties> renderProp = renderer ? renderer->CreateProperties () : 0; defaultCell.SetRenderProperties (renderProp); } void csTerrainFactory::SetCollider (iTerrainCollider* collider) { this->collider = collider; csRef<iTerrainCellCollisionProperties> collProp = collider ? collider->CreateProperties () : 0; defaultCell.SetCollisionProperties (collProp); } void csTerrainFactory::SetFeeder (iTerrainDataFeeder* feeder) { this->dataFeeder = feeder; csRef<iTerrainCellFeederProperties> feederProp = dataFeeder ? dataFeeder->CreateProperties () : 0; defaultCell.SetFeederProperties (feederProp); } iTerrainFactoryCell* csTerrainFactory::GetCell (const char* name) { for (size_t i = 0; i < cells.GetSize(); i++) { const char* cellName = cells[i]->GetName(); if (cellName == 0) continue; if (strcmp (cellName, name) == 0) return cells[i]; } return 0; } iTerrainFactoryCell* csTerrainFactory::AddCell(const char* name, int gridWidth, int gridHeight, int materialMapWidth, int materialMapHeight, bool materialMapPersistent, const csVector2& position, const csVector3& size) { csRef<csTerrainFactoryCell> cell; csRef<iTerrainCellRenderProperties> renderProp = renderer ? renderer->CreateProperties () : 0; csRef<iTerrainCellCollisionProperties> collProp = collider ? collider->CreateProperties () : 0; csRef<iTerrainCellFeederProperties> feederProp = dataFeeder ? dataFeeder->CreateProperties () : 0; cell.AttachNew (new csTerrainFactoryCell (name, gridWidth, gridHeight, materialMapWidth, materialMapHeight, materialMapPersistent, position, size, renderProp, collProp, feederProp)); cells.Push (cell); return cell; } iTerrainFactoryCell* csTerrainFactory::AddCell() { csRef<csTerrainFactoryCell> cell; cell.AttachNew (new csTerrainFactoryCell (defaultCell)); cells.Push (cell); return cell; } void csTerrainFactory::SetMaxLoadedCells (size_t value) { maxLoadedCells = value; } void csTerrainFactory::SetVirtualViewDistance (float distance) { virtualViewDistance = distance; } void csTerrainFactory::SetAutoPreLoad (bool mode) { autoPreLoad = mode; } csTerrainFactoryCell::csTerrainFactoryCell (const char* name, int gridWidth, int gridHeight, int materialMapWidth, int materialMapHeight, bool materialMapPersistent, const csVector2& position, const csVector3& size, iTerrainCellRenderProperties* renderProp, iTerrainCellCollisionProperties* collisionProp, iTerrainCellFeederProperties* feederProp) : scfImplementationType (this), name (name), position (position), size (size), gridWidth (gridWidth), gridHeight (gridHeight), materialMapWidth (materialMapWidth), materialMapHeight (materialMapHeight), materialMapPersistent (materialMapPersistent), rendererProperties (renderProp), colliderProperties (collisionProp), feederProperties (feederProp) { } csTerrainFactoryCell::csTerrainFactoryCell (const csTerrainFactoryCell& other) : scfImplementationType (this), name (other.name), position (other.position), size (other.size), gridWidth (other.gridWidth), gridHeight (other.gridHeight), materialMapWidth (other.materialMapWidth), materialMapHeight (other.materialMapHeight), materialMapPersistent (other.materialMapPersistent), baseMaterial (other.baseMaterial), rendererProperties (other.rendererProperties->Clone()), colliderProperties (other.colliderProperties->Clone()), feederProperties (other.feederProperties->Clone()) { } csPtr<csTerrainCell> csTerrainFactoryCell::CreateCell (csTerrainSystem* terrain) { csTerrainCell* cell; csRef<iTerrainCellRenderProperties> renderProp = rendererProperties ? rendererProperties->Clone () : 0; csRef<iTerrainCellCollisionProperties> collProp = colliderProperties ? colliderProperties->Clone () : 0; csRef<iTerrainCellFeederProperties> feederProp = feederProperties ? feederProperties->Clone () : 0; cell = new csTerrainCell (terrain, name.GetData (), gridWidth, gridHeight, materialMapWidth, materialMapHeight, materialMapPersistent, position, size, renderProp, collProp, feederProp); cell->SetBaseMaterial (baseMaterial); return csPtr<csTerrainCell> (cell); } iTerrainCellRenderProperties* csTerrainFactoryCell::GetRenderProperties () const { return rendererProperties; } iTerrainCellCollisionProperties* csTerrainFactoryCell::GetCollisionProperties () const { return colliderProperties; } iTerrainCellFeederProperties* csTerrainFactoryCell::GetFeederProperties () const { return feederProperties; } void csTerrainFactoryCell::SetBaseMaterial (iMaterialWrapper* material) { baseMaterial = material; } } CS_PLUGIN_NAMESPACE_END(Terrain2) <|endoftext|>
<commit_before>// // EigenJS.cpp // ~~~~~~~~~~~ // // 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 <node.h> #include <v8.h> #include <nan.h> #include <eigen3/Eigen/Dense> #include <complex> namespace EigenJS { template < template <typename, const char*> class Derived , typename ValueType , const char* ClassName > struct base { typedef ValueType element_type; typedef std::complex<element_type> complex_type; typedef Eigen::Matrix< element_type , Eigen::Dynamic , Eigen::Dynamic > matrix_type; typedef Derived<ValueType, ClassName> derived_type; static bool HasInstance(const v8::Handle<v8::Value>& value) { NanScope(); v8::Local<v8::FunctionTemplate> tpl = NanNew(function_template); return tpl->HasInstance(value); } static inline bool is_scalar(const v8::Handle<v8::Value>& arg) { return arg->IsNumber() ? true : false; } protected: static v8::Persistent<v8::FunctionTemplate> function_template; static v8::Persistent<v8::Function> constructor; }; template< template <typename, const char*> class Derived , typename ValueType , const char* ClassName > v8::Persistent<v8::FunctionTemplate> base<Derived, ValueType, ClassName>::function_template; template< template <typename, const char*> class Derived , typename ValueType , const char* ClassName > v8::Persistent<v8::Function> base<Derived, ValueType, ClassName>::constructor; } // namespace EigenJS #endif // EIGENJS_BASIC_HPP <commit_msg>src: changed modifier of 'base::is_scalar' from public to private<commit_after>// // EigenJS.cpp // ~~~~~~~~~~~ // // 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 <node.h> #include <v8.h> #include <nan.h> #include <eigen3/Eigen/Dense> #include <complex> namespace EigenJS { template < template <typename, const char*> class Derived , typename ValueType , const char* ClassName > struct base { typedef ValueType element_type; typedef std::complex<element_type> complex_type; typedef Eigen::Matrix< element_type , Eigen::Dynamic , Eigen::Dynamic > matrix_type; typedef Derived<ValueType, ClassName> derived_type; static inline bool is_scalar(const v8::Handle<v8::Value>& arg) { return arg->IsNumber() ? true : false; } protected: static bool HasInstance(const v8::Handle<v8::Value>& value) { NanScope(); v8::Local<v8::FunctionTemplate> tpl = NanNew(function_template); return tpl->HasInstance(value); } static v8::Persistent<v8::FunctionTemplate> function_template; static v8::Persistent<v8::Function> constructor; }; template< template <typename, const char*> class Derived , typename ValueType , const char* ClassName > v8::Persistent<v8::FunctionTemplate> base<Derived, ValueType, ClassName>::function_template; template< template <typename, const char*> class Derived , typename ValueType , const char* ClassName > v8::Persistent<v8::Function> base<Derived, ValueType, ClassName>::constructor; } // namespace EigenJS #endif // EIGENJS_BASIC_HPP <|endoftext|>
<commit_before>/* * optionsbutton.cpp * PHD Guiding * * Created by Andy Galasso * Copyright (c) 2013 Andy Galasso * All rights reserved. * * This source code is distributed under the following "BSD" license * 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 Craig Stark, Stark Labs, * Bret McKee, Dad Dog Development, Ltd, 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 HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include "phd.h" #include "optionsbutton.h" #include "icons/down_arrow.xpm" #include "icons/down_arrow_bold.xpm" BEGIN_EVENT_TABLE(OptionsButton, wxPanel) EVT_ENTER_WINDOW(OptionsButton::OnMouseEnter) EVT_MOTION(OptionsButton::OnMouseMove) EVT_LEAVE_WINDOW(OptionsButton::OnMouseLeave) EVT_PAINT(OptionsButton::OnPaint) EVT_LEFT_UP(OptionsButton::OnClick) END_EVENT_TABLE() enum { PADX = 5, PADY = 5, }; OptionsButton::OptionsButton(wxWindow *parent, wxWindowID id, const wxString& label, const wxPoint& pos, const wxSize& size, long style, const wxString& name) : wxPanel(parent, id, pos, size, style, name), m_highlighted(false), m_label(label) { m_bmp = new wxBitmap(down_arrow); m_bmp_bold = new wxBitmap(down_arrow_bold); SetBackgroundStyle(wxBG_STYLE_PAINT); } OptionsButton::~OptionsButton() { delete m_bmp; delete m_bmp_bold; } wxSize OptionsButton::GetMinSize() const { wxSize txtsz = GetTextExtent(m_label); return wxSize(PADX + txtsz.x + PADX + m_bmp->GetWidth() + PADX, PADY + txtsz.y + PADY); } void OptionsButton::SetLabel(const wxString& label) { m_label = label; Refresh(); } void OptionsButton::OnPaint(wxPaintEvent & evt) { wxBufferedPaintDC dc(this); if (m_highlighted) dc.SetPen(wxPen(wxColor(0, 0, 0))); else dc.SetPen(wxPen(wxColor(56, 56, 56))); dc.SetBrush(wxBrush(wxColor(200, 200, 200))); wxSize txtsz = GetTextExtent(m_label); wxSize size(GetSize()); int xbmp = size.GetWidth() - m_bmp->GetWidth() - PADX; wxPoint bmp_pos(xbmp, 7); int xtxt; if (GetWindowStyleFlag() & wxALIGN_CENTER_HORIZONTAL) { xtxt = (size.GetWidth() - txtsz.GetWidth()) / 2; } else { xtxt = PADX; } dc.DrawRectangle(wxPoint(0, 0), size); dc.SetTextBackground(wxColor(200, 200, 200)); if (m_highlighted) { dc.SetTextForeground(wxColor(0, 0, 0)); dc.DrawText(m_label, xtxt, PADY); dc.DrawBitmap(*m_bmp_bold, bmp_pos); } else { dc.SetTextForeground(wxColor(56, 56, 56)); dc.DrawText(m_label, xtxt, PADY); dc.DrawBitmap(*m_bmp, bmp_pos); } } void OptionsButton::OnMouseEnter(wxMouseEvent& event) { m_highlighted = true; Refresh(); } void OptionsButton::OnMouseMove(wxMouseEvent& event) { if (!m_highlighted) { m_highlighted = true; Refresh(); } } void OptionsButton::OnMouseLeave(wxMouseEvent& event) { m_highlighted = false; Refresh(); } void OptionsButton::OnClick(wxMouseEvent& event) { wxCommandEvent cmd(wxEVT_COMMAND_BUTTON_CLICKED, GetId()); ::wxPostEvent(GetParent(), cmd); m_highlighted = false; Refresh(); } <commit_msg>Fix the Manage Profile button on Linux.<commit_after>/* * optionsbutton.cpp * PHD Guiding * * Created by Andy Galasso * Copyright (c) 2013 Andy Galasso * All rights reserved. * * This source code is distributed under the following "BSD" license * 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 Craig Stark, Stark Labs, * Bret McKee, Dad Dog Development, Ltd, 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 HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include "phd.h" #include "optionsbutton.h" #include "icons/down_arrow.xpm" #include "icons/down_arrow_bold.xpm" BEGIN_EVENT_TABLE(OptionsButton, wxPanel) EVT_ENTER_WINDOW(OptionsButton::OnMouseEnter) EVT_MOTION(OptionsButton::OnMouseMove) EVT_LEAVE_WINDOW(OptionsButton::OnMouseLeave) EVT_PAINT(OptionsButton::OnPaint) EVT_LEFT_UP(OptionsButton::OnClick) END_EVENT_TABLE() enum { PADX = 5, PADY = 5, }; OptionsButton::OptionsButton(wxWindow *parent, wxWindowID id, const wxString& label, const wxPoint& pos, const wxSize& size, long style, const wxString& name) : wxPanel(parent, id, pos, size, style, name), m_highlighted(false), m_label(label) { m_bmp = new wxBitmap(down_arrow); m_bmp_bold = new wxBitmap(down_arrow_bold); SetBackgroundStyle(wxBG_STYLE_PAINT); } OptionsButton::~OptionsButton() { delete m_bmp; delete m_bmp_bold; } wxSize OptionsButton::GetMinSize() const { wxSize txtsz = GetTextExtent(m_label); return wxSize(PADX + txtsz.x + PADX + m_bmp->GetWidth() + PADX, PADY + txtsz.y + PADY); } void OptionsButton::SetLabel(const wxString& label) { m_label = label; Refresh(); } void OptionsButton::OnPaint(wxPaintEvent & evt) { wxBufferedPaintDC dc(this); if (m_highlighted) dc.SetPen(wxPen(wxColor(0, 0, 0))); else dc.SetPen(wxPen(wxColor(56, 56, 56))); dc.SetBrush(wxBrush(wxColor(200, 200, 200))); wxSize txtsz = GetTextExtent(m_label); wxSize size(GetSize()); int xbmp = size.GetWidth() - m_bmp->GetWidth() - PADX; wxPoint bmp_pos(xbmp, 7); int xtxt; if (GetWindowStyleFlag() & wxALIGN_CENTER_HORIZONTAL) { xtxt = (size.GetWidth() - txtsz.GetWidth()) / 2; } else { xtxt = PADX; } dc.DrawRectangle(wxPoint(0, 0), size); dc.SetTextBackground(wxColor(200, 200, 200)); if (m_highlighted) { dc.SetTextForeground(wxColor(0, 0, 0)); dc.DrawText(m_label, xtxt, PADY); dc.DrawBitmap(*m_bmp_bold, bmp_pos); } else { dc.SetTextForeground(wxColor(56, 56, 56)); dc.DrawText(m_label, xtxt, PADY); dc.DrawBitmap(*m_bmp, bmp_pos); } } void OptionsButton::OnMouseEnter(wxMouseEvent& event) { m_highlighted = true; Refresh(); } void OptionsButton::OnMouseMove(wxMouseEvent& event) { if (!m_highlighted) { m_highlighted = true; Refresh(); } } void OptionsButton::OnMouseLeave(wxMouseEvent& event) { m_highlighted = false; Refresh(); } void OptionsButton::OnClick(wxMouseEvent& event) { wxCommandEvent cmd(wxEVT_COMMAND_BUTTON_CLICKED, GetId()); #ifdef __WXGTK__ // Process the event as in wxgtk_button_clicked_callback() HandleWindowEvent(cmd); #else ::wxPostEvent(GetParent(), cmd); #endif m_highlighted = false; Refresh(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: jobexecutor.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2003-05-22 08:38:04 $ * * 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): _______________________________________ * * ************************************************************************/ //________________________________ // my own includes #ifndef __FRAMEWORK_JOBS_JOBEXECUTOR_HXX_ #include <jobs/jobexecutor.hxx> #endif #ifndef __FRAMEWORK_JOBS_JOB_HXX_ #include <jobs/job.hxx> #endif #ifndef __FRAMEWORK_JOBS_JOBURL_HXX_ #include <jobs/joburl.hxx> #endif #ifndef __FRAMEWORK_CLASS_CONVERTER_HXX_ #include <classes/converter.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_TRANSACTIONGUARD_HXX_ #include <threadhelp/transactionguard.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_ #include <threadhelp/readguard.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_ #include <threadhelp/writeguard.hxx> #endif #ifndef __FRAMEWORK_GENERAL_H_ #include <general.h> #endif #ifndef __FRAMEWORK_SERVICES_H_ #include <services.h> #endif //________________________________ // interface includes #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_ #include <com/sun/star/container/XContainer.hpp> #endif //________________________________ // includes of other projects #ifndef UNOTOOLS_CONFIGPATHES_HXX_INCLUDED #include <unotools/configpathes.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif //________________________________ // namespace namespace framework{ //________________________________ // non exported const //________________________________ // non exported definitions //________________________________ // declarations DEFINE_XINTERFACE_6( JobExecutor , OWeakObject , DIRECT_INTERFACE(css::lang::XTypeProvider ), DIRECT_INTERFACE(css::lang::XServiceInfo ), DIRECT_INTERFACE(css::task::XJobExecutor ), DIRECT_INTERFACE(css::container::XContainerListener ), DIRECT_INTERFACE(css::document::XEventListener ), DERIVED_INTERFACE(css::lang::XEventListener,css::document::XEventListener) ) DEFINE_XTYPEPROVIDER_6( JobExecutor , css::lang::XTypeProvider , css::lang::XServiceInfo , css::task::XJobExecutor , css::container::XContainerListener, css::document::XEventListener , css::lang::XEventListener ) DEFINE_XSERVICEINFO_ONEINSTANCESERVICE( JobExecutor , ::cppu::OWeakObject , SERVICENAME_JOBEXECUTOR , IMPLEMENTATIONNAME_JOBEXECUTOR ) DEFINE_INIT_SERVICE( JobExecutor, { /*Attention I think we don't need any mutex or lock here ... because we are called by our own static method impl_createInstance() to create a new instance of this class by our own supported service factory. see macro DEFINE_XSERVICEINFO_MULTISERVICE and "impl_initService()" for further informations! */ // read the list of all currently registered events inside configuration. // e.g. "/org.openoffice.Office.Jobs/Events/<event name>" // We need it later to check if an incoming event request can be executed successfully // or must be rejected. It's an optimization! Of course we must implement updating of this // list too ... Be listener at the configuration. m_aConfig.open(ConfigAccess::E_READONLY); if (m_aConfig.getMode() == ConfigAccess::E_READONLY) { css::uno::Reference< css::container::XNameAccess > xRegistry(m_aConfig.cfg(), css::uno::UNO_QUERY); if (xRegistry.is()) m_lEvents = Converter::convert_seqOUString2OUStringList(xRegistry->getElementNames()); css::uno::Reference< css::container::XContainer > xNotifier(m_aConfig.cfg(), css::uno::UNO_QUERY); if (xNotifier.is()) { css::uno::Reference< css::container::XContainerListener > xThis(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY); xNotifier->addContainerListener(xThis); } // don't close cfg here! // It will be done inside disposing ... } } ) //________________________________ /** @short standard ctor @descr It initialize this new instance. @param xSMGR reference to the uno service manager */ JobExecutor::JobExecutor( /*IN*/ const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ) : ThreadHelpBase (&Application::GetSolarMutex() ) , ::cppu::OWeakObject ( ) , m_xSMGR (xSMGR ) , m_aConfig (xSMGR, ::rtl::OUString::createFromAscii(JobData::EVENTCFG_ROOT) ) { // Don't do any reference related code here! Do it inside special // impl_ method() ... see DEFINE_INIT_SERVICE() macro for further informations. } JobExecutor::~JobExecutor() { LOG_ASSERT(m_aConfig.getMode() == ConfigAccess::E_CLOSED, "JobExecutor::~JobExecutor()\nConfiguration don't send dispoing() message!\n") } //________________________________ /** @short implementation of XJobExecutor interface @descr We use the given event to locate any registered job inside our configuration and execute it. Further we control the lifetime of it and supress shutdown of the office till all jobs was finished. @param sEvent is used to locate registered jobs */ void SAL_CALL JobExecutor::trigger( const ::rtl::OUString& sEvent ) throw(css::uno::RuntimeException) { /* SAFE { */ ReadGuard aReadLock(m_aLock); // Optimization! // Check if the given event name exist inside configuration and reject wrong requests. // This optimization supress using of the cfg api for getting event and job descriptions ... if (m_lEvents.find(sEvent) == m_lEvents.end()) return; // get list of all enabled jobs // The called static helper methods read it from the configuration and // filter disabled jobs using it's time stamp values. css::uno::Sequence< ::rtl::OUString > lJobs = JobData::getEnabledJobsForEvent(m_xSMGR, sEvent); aReadLock.unlock(); /* } SAFE */ // step over all enabled jobs and execute it sal_Int32 c = lJobs.getLength(); for (sal_Int32 j=0; j<c; ++j) { /* SAFE { */ aReadLock.lock(); JobData aCfg(m_xSMGR); aCfg.setEvent(sEvent, lJobs[j]); aCfg.setEnvironment(JobData::E_EXECUTION); /*Attention! Jobs implements interfaces and dies by ref count! And freeing of such uno object is done by uno itself. So we have to use dynamic memory everytimes. */ Job* pJob = new Job(m_xSMGR, css::uno::Reference< css::frame::XFrame >()); css::uno::Reference< css::uno::XInterface > xJob(static_cast< ::cppu::OWeakObject* >(pJob), css::uno::UNO_QUERY); pJob->setJobData(aCfg); aReadLock.unlock(); /* } SAFE */ pJob->execute(css::uno::Sequence< css::beans::NamedValue >()); } } //________________________________ void SAL_CALL JobExecutor::notifyEvent( const css::document::EventObject& aEvent ) throw(css::uno::RuntimeException) { /* SAFE { */ ReadGuard aReadLock(m_aLock); // Optimization! // Check if the given event name exist inside configuration and reject wrong requests. // This optimization supress using of the cfg api for getting event and job descriptions ... if (m_lEvents.find(aEvent.EventName) == m_lEvents.end()) return; // get list of all enabled jobs // The called static helper methods read it from the configuration and // filter disabled jobs using it's time stamp values. css::uno::Sequence< ::rtl::OUString > lJobs = JobData::getEnabledJobsForEvent(m_xSMGR, aEvent.EventName); // Special feature: If the events "OnNew" or "OnLoad" occures - we generate our own event "onDocumentOpened". if ( (aEvent.EventName.equalsAscii("OnNew") ) || (aEvent.EventName.equalsAscii("OnLoad")) ) { css::uno::Sequence< ::rtl::OUString > lAdditionalJobs = JobData::getEnabledJobsForEvent(m_xSMGR, DECLARE_ASCII("onDocumentOpened")); sal_Int32 count = lAdditionalJobs.getLength(); if (count > 0) { sal_Int32 dest = lJobs.getLength(); sal_Int32 source = 0; lJobs.realloc(dest+count); while(source < count) { lJobs[dest] = lAdditionalJobs[source]; ++source; ++dest; } } } aReadLock.unlock(); /* } SAFE */ // step over all enabled jobs and execute it sal_Int32 c = lJobs.getLength(); for (sal_Int32 j=0; j<c; ++j) { /* SAFE { */ aReadLock.lock(); JobData aCfg(m_xSMGR); aCfg.setEvent(aEvent.EventName, lJobs[j]); aCfg.setEnvironment(JobData::E_DOCUMENTEVENT); /*Attention! Jobs implements interfaces and dies by ref count! And freeing of such uno object is done by uno itself. So we have to use dynamic memory everytimes. */ css::uno::Reference< css::frame::XModel > xModel(aEvent.Source, css::uno::UNO_QUERY); Job* pJob = new Job(m_xSMGR, xModel); css::uno::Reference< css::uno::XInterface > xJob(static_cast< ::cppu::OWeakObject* >(pJob), css::uno::UNO_QUERY); pJob->setJobData(aCfg); aReadLock.unlock(); /* } SAFE */ pJob->execute(css::uno::Sequence< css::beans::NamedValue >()); } } //________________________________ void SAL_CALL JobExecutor::elementInserted( const css::container::ContainerEvent& aEvent ) throw(css::uno::RuntimeException) { ::rtl::OUString sValue; if (aEvent.Accessor >>= sValue) { ::rtl::OUString sEvent = ::utl::extractFirstFromConfigurationPath(sValue); if (sEvent.getLength() > 0) { OUStringList::iterator pEvent = m_lEvents.find(sEvent); if (pEvent == m_lEvents.end()) m_lEvents.push_back(sEvent); } } } void SAL_CALL JobExecutor::elementRemoved ( const css::container::ContainerEvent& aEvent ) throw(css::uno::RuntimeException) { ::rtl::OUString sValue; if (aEvent.Accessor >>= sValue) { ::rtl::OUString sEvent = ::utl::extractFirstFromConfigurationPath(sValue); if (sEvent.getLength() > 0) { OUStringList::iterator pEvent = m_lEvents.find(sEvent); if (pEvent != m_lEvents.end()) m_lEvents.erase(pEvent); } } } void SAL_CALL JobExecutor::elementReplaced( const css::container::ContainerEvent& aEvent ) throw(css::uno::RuntimeException) { // I'm not interested on changed items :-) } //________________________________ /** @short the used cfg changes notifier wish to be released in its reference. @descr We close our internal used configuration instance to free this reference. @attention For the special feature "bind global document event broadcaster to job execution" this job executor instance was registered from outside code as css.document.XEventListener. So it can be, that this disposing call comes from the global event broadcaster service. But we don't hold any reference to this service which can or must be released. Because this broadcaster itself is an one instance service too, we can ignore this request. On the other side we must relase our internal CFG reference ... SOLUTION => check the given event source and react only, if it's our internal hold configuration object! */ void SAL_CALL JobExecutor::disposing( const css::lang::EventObject& aEvent ) throw(css::uno::RuntimeException) { /* SAFE { */ ReadGuard aReadLock(m_aLock); css::uno::Reference< css::uno::XInterface > xCFG(m_aConfig.cfg(), css::uno::UNO_QUERY); if ( (xCFG == aEvent.Source ) && (m_aConfig.getMode() != ConfigAccess::E_CLOSED) ) { m_aConfig.close(); } aReadLock.unlock(); /* } SAFE */ } } // namespace framework <commit_msg>INTEGRATION: CWS ooo19126 (1.4.474); FILE MERGED 2005/09/05 13:06:39 rt 1.4.474.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: jobexecutor.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:36:02 $ * * 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 * ************************************************************************/ //________________________________ // my own includes #ifndef __FRAMEWORK_JOBS_JOBEXECUTOR_HXX_ #include <jobs/jobexecutor.hxx> #endif #ifndef __FRAMEWORK_JOBS_JOB_HXX_ #include <jobs/job.hxx> #endif #ifndef __FRAMEWORK_JOBS_JOBURL_HXX_ #include <jobs/joburl.hxx> #endif #ifndef __FRAMEWORK_CLASS_CONVERTER_HXX_ #include <classes/converter.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_TRANSACTIONGUARD_HXX_ #include <threadhelp/transactionguard.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_ #include <threadhelp/readguard.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_ #include <threadhelp/writeguard.hxx> #endif #ifndef __FRAMEWORK_GENERAL_H_ #include <general.h> #endif #ifndef __FRAMEWORK_SERVICES_H_ #include <services.h> #endif //________________________________ // interface includes #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_ #include <com/sun/star/container/XContainer.hpp> #endif //________________________________ // includes of other projects #ifndef UNOTOOLS_CONFIGPATHES_HXX_INCLUDED #include <unotools/configpathes.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif //________________________________ // namespace namespace framework{ //________________________________ // non exported const //________________________________ // non exported definitions //________________________________ // declarations DEFINE_XINTERFACE_6( JobExecutor , OWeakObject , DIRECT_INTERFACE(css::lang::XTypeProvider ), DIRECT_INTERFACE(css::lang::XServiceInfo ), DIRECT_INTERFACE(css::task::XJobExecutor ), DIRECT_INTERFACE(css::container::XContainerListener ), DIRECT_INTERFACE(css::document::XEventListener ), DERIVED_INTERFACE(css::lang::XEventListener,css::document::XEventListener) ) DEFINE_XTYPEPROVIDER_6( JobExecutor , css::lang::XTypeProvider , css::lang::XServiceInfo , css::task::XJobExecutor , css::container::XContainerListener, css::document::XEventListener , css::lang::XEventListener ) DEFINE_XSERVICEINFO_ONEINSTANCESERVICE( JobExecutor , ::cppu::OWeakObject , SERVICENAME_JOBEXECUTOR , IMPLEMENTATIONNAME_JOBEXECUTOR ) DEFINE_INIT_SERVICE( JobExecutor, { /*Attention I think we don't need any mutex or lock here ... because we are called by our own static method impl_createInstance() to create a new instance of this class by our own supported service factory. see macro DEFINE_XSERVICEINFO_MULTISERVICE and "impl_initService()" for further informations! */ // read the list of all currently registered events inside configuration. // e.g. "/org.openoffice.Office.Jobs/Events/<event name>" // We need it later to check if an incoming event request can be executed successfully // or must be rejected. It's an optimization! Of course we must implement updating of this // list too ... Be listener at the configuration. m_aConfig.open(ConfigAccess::E_READONLY); if (m_aConfig.getMode() == ConfigAccess::E_READONLY) { css::uno::Reference< css::container::XNameAccess > xRegistry(m_aConfig.cfg(), css::uno::UNO_QUERY); if (xRegistry.is()) m_lEvents = Converter::convert_seqOUString2OUStringList(xRegistry->getElementNames()); css::uno::Reference< css::container::XContainer > xNotifier(m_aConfig.cfg(), css::uno::UNO_QUERY); if (xNotifier.is()) { css::uno::Reference< css::container::XContainerListener > xThis(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY); xNotifier->addContainerListener(xThis); } // don't close cfg here! // It will be done inside disposing ... } } ) //________________________________ /** @short standard ctor @descr It initialize this new instance. @param xSMGR reference to the uno service manager */ JobExecutor::JobExecutor( /*IN*/ const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ) : ThreadHelpBase (&Application::GetSolarMutex() ) , ::cppu::OWeakObject ( ) , m_xSMGR (xSMGR ) , m_aConfig (xSMGR, ::rtl::OUString::createFromAscii(JobData::EVENTCFG_ROOT) ) { // Don't do any reference related code here! Do it inside special // impl_ method() ... see DEFINE_INIT_SERVICE() macro for further informations. } JobExecutor::~JobExecutor() { LOG_ASSERT(m_aConfig.getMode() == ConfigAccess::E_CLOSED, "JobExecutor::~JobExecutor()\nConfiguration don't send dispoing() message!\n") } //________________________________ /** @short implementation of XJobExecutor interface @descr We use the given event to locate any registered job inside our configuration and execute it. Further we control the lifetime of it and supress shutdown of the office till all jobs was finished. @param sEvent is used to locate registered jobs */ void SAL_CALL JobExecutor::trigger( const ::rtl::OUString& sEvent ) throw(css::uno::RuntimeException) { /* SAFE { */ ReadGuard aReadLock(m_aLock); // Optimization! // Check if the given event name exist inside configuration and reject wrong requests. // This optimization supress using of the cfg api for getting event and job descriptions ... if (m_lEvents.find(sEvent) == m_lEvents.end()) return; // get list of all enabled jobs // The called static helper methods read it from the configuration and // filter disabled jobs using it's time stamp values. css::uno::Sequence< ::rtl::OUString > lJobs = JobData::getEnabledJobsForEvent(m_xSMGR, sEvent); aReadLock.unlock(); /* } SAFE */ // step over all enabled jobs and execute it sal_Int32 c = lJobs.getLength(); for (sal_Int32 j=0; j<c; ++j) { /* SAFE { */ aReadLock.lock(); JobData aCfg(m_xSMGR); aCfg.setEvent(sEvent, lJobs[j]); aCfg.setEnvironment(JobData::E_EXECUTION); /*Attention! Jobs implements interfaces and dies by ref count! And freeing of such uno object is done by uno itself. So we have to use dynamic memory everytimes. */ Job* pJob = new Job(m_xSMGR, css::uno::Reference< css::frame::XFrame >()); css::uno::Reference< css::uno::XInterface > xJob(static_cast< ::cppu::OWeakObject* >(pJob), css::uno::UNO_QUERY); pJob->setJobData(aCfg); aReadLock.unlock(); /* } SAFE */ pJob->execute(css::uno::Sequence< css::beans::NamedValue >()); } } //________________________________ void SAL_CALL JobExecutor::notifyEvent( const css::document::EventObject& aEvent ) throw(css::uno::RuntimeException) { /* SAFE { */ ReadGuard aReadLock(m_aLock); // Optimization! // Check if the given event name exist inside configuration and reject wrong requests. // This optimization supress using of the cfg api for getting event and job descriptions ... if (m_lEvents.find(aEvent.EventName) == m_lEvents.end()) return; // get list of all enabled jobs // The called static helper methods read it from the configuration and // filter disabled jobs using it's time stamp values. css::uno::Sequence< ::rtl::OUString > lJobs = JobData::getEnabledJobsForEvent(m_xSMGR, aEvent.EventName); // Special feature: If the events "OnNew" or "OnLoad" occures - we generate our own event "onDocumentOpened". if ( (aEvent.EventName.equalsAscii("OnNew") ) || (aEvent.EventName.equalsAscii("OnLoad")) ) { css::uno::Sequence< ::rtl::OUString > lAdditionalJobs = JobData::getEnabledJobsForEvent(m_xSMGR, DECLARE_ASCII("onDocumentOpened")); sal_Int32 count = lAdditionalJobs.getLength(); if (count > 0) { sal_Int32 dest = lJobs.getLength(); sal_Int32 source = 0; lJobs.realloc(dest+count); while(source < count) { lJobs[dest] = lAdditionalJobs[source]; ++source; ++dest; } } } aReadLock.unlock(); /* } SAFE */ // step over all enabled jobs and execute it sal_Int32 c = lJobs.getLength(); for (sal_Int32 j=0; j<c; ++j) { /* SAFE { */ aReadLock.lock(); JobData aCfg(m_xSMGR); aCfg.setEvent(aEvent.EventName, lJobs[j]); aCfg.setEnvironment(JobData::E_DOCUMENTEVENT); /*Attention! Jobs implements interfaces and dies by ref count! And freeing of such uno object is done by uno itself. So we have to use dynamic memory everytimes. */ css::uno::Reference< css::frame::XModel > xModel(aEvent.Source, css::uno::UNO_QUERY); Job* pJob = new Job(m_xSMGR, xModel); css::uno::Reference< css::uno::XInterface > xJob(static_cast< ::cppu::OWeakObject* >(pJob), css::uno::UNO_QUERY); pJob->setJobData(aCfg); aReadLock.unlock(); /* } SAFE */ pJob->execute(css::uno::Sequence< css::beans::NamedValue >()); } } //________________________________ void SAL_CALL JobExecutor::elementInserted( const css::container::ContainerEvent& aEvent ) throw(css::uno::RuntimeException) { ::rtl::OUString sValue; if (aEvent.Accessor >>= sValue) { ::rtl::OUString sEvent = ::utl::extractFirstFromConfigurationPath(sValue); if (sEvent.getLength() > 0) { OUStringList::iterator pEvent = m_lEvents.find(sEvent); if (pEvent == m_lEvents.end()) m_lEvents.push_back(sEvent); } } } void SAL_CALL JobExecutor::elementRemoved ( const css::container::ContainerEvent& aEvent ) throw(css::uno::RuntimeException) { ::rtl::OUString sValue; if (aEvent.Accessor >>= sValue) { ::rtl::OUString sEvent = ::utl::extractFirstFromConfigurationPath(sValue); if (sEvent.getLength() > 0) { OUStringList::iterator pEvent = m_lEvents.find(sEvent); if (pEvent != m_lEvents.end()) m_lEvents.erase(pEvent); } } } void SAL_CALL JobExecutor::elementReplaced( const css::container::ContainerEvent& aEvent ) throw(css::uno::RuntimeException) { // I'm not interested on changed items :-) } //________________________________ /** @short the used cfg changes notifier wish to be released in its reference. @descr We close our internal used configuration instance to free this reference. @attention For the special feature "bind global document event broadcaster to job execution" this job executor instance was registered from outside code as css.document.XEventListener. So it can be, that this disposing call comes from the global event broadcaster service. But we don't hold any reference to this service which can or must be released. Because this broadcaster itself is an one instance service too, we can ignore this request. On the other side we must relase our internal CFG reference ... SOLUTION => check the given event source and react only, if it's our internal hold configuration object! */ void SAL_CALL JobExecutor::disposing( const css::lang::EventObject& aEvent ) throw(css::uno::RuntimeException) { /* SAFE { */ ReadGuard aReadLock(m_aLock); css::uno::Reference< css::uno::XInterface > xCFG(m_aConfig.cfg(), css::uno::UNO_QUERY); if ( (xCFG == aEvent.Source ) && (m_aConfig.getMode() != ConfigAccess::E_CLOSED) ) { m_aConfig.close(); } aReadLock.unlock(); /* } SAFE */ } } // namespace framework <|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 "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 ValueType 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 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 T, typename U> static NAN_INLINE typename std::enable_if< boost::mpl::and_< detail::is_eigen_matrix<typename T::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_< detail::is_eigen_matrix<typename T::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(); } protected: base() : value_ptr_(new value_type()) {} explicit base(const Complex<scalar_type>&) : value_ptr_() {} base(const base& other) : value_ptr_(other.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: supported 'Block'<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 "Block_fwd.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_; }; template <typename T> struct unwrap_block { typedef T type; }; template<typename XprType, int BlockRows, int BlockCols, bool InnerPanel> struct unwrap_block< Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel> > { typedef XprType type; }; } // 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_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 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 T, typename U> static NAN_INLINE typename std::enable_if< boost::mpl::and_< detail::is_eigen_matrix<typename T::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_< detail::is_eigen_matrix<typename T::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_() {} 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>/*===========================================================================*\ * * * OpenMesh * * Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * * * * OpenMesh is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenMesh 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 LesserGeneral Public * * License along with OpenMesh. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision: 448 $ * * $Date: 2011-11-04 13:59:37 +0100 (Fri, 04 Nov 2011) $ * * * \*===========================================================================*/ /** \file ModHausdorffT.cc */ //============================================================================= // // CLASS ModHausdorffT - IMPLEMENTATION // //============================================================================= #define OPENMESH_DECIMATER_MODHAUSDORFFT_C //== INCLUDES ================================================================= #include "ModHausdorffT.hh" #ifdef USE_OPENMP #include <omp.h> #endif //== NAMESPACES =============================================================== namespace OpenMesh { namespace Decimater { //== IMPLEMENTATION ========================================================== template <class MeshT> typename ModHausdorffT<MeshT>::Scalar ModHausdorffT<MeshT>:: distPointTriangleSquared( const Point& _p, const Point& _v0, const Point& _v1, const Point& _v2 ) { const Point v0v1 = _v1 - _v0; const Point v0v2 = _v2 - _v0; const Point n = v0v1 % v0v2; // not normalized ! const double d = n.sqrnorm(); // Check if the triangle is degenerated if (d < FLT_MIN && d > -FLT_MIN) { // std::cerr << "distPointTriangleSquared: Degenerated triangle !\n"; // std::cerr << "Points are : " << _v0 << " " << _v1 << " " << _v2 << std::endl; // std::cerr << "d is " << d << std::endl; return -1.0; } const double invD = 1.0 / d; // these are not needed for every point, should still perform // better with many points against one triangle const Point v1v2 = _v2 - _v1; const double inv_v0v2_2 = 1.0 / v0v2.sqrnorm(); const double inv_v0v1_2 = 1.0 / v0v1.sqrnorm(); const double inv_v1v2_2 = 1.0 / v1v2.sqrnorm(); Point v0p = _p - _v0; Point t = v0p % n; double s01, s02, s12; const double a = (t | v0v2) * -invD; const double b = (t | v0v1) * invD; if (a < 0) { // Calculate the distance to an edge or a corner vertex s02 = ( v0v2 | v0p ) * inv_v0v2_2; if (s02 < 0.0) { s01 = ( v0v1 | v0p ) * inv_v0v1_2; if (s01 <= 0.0) { v0p = _v0; } else if (s01 >= 1.0) { v0p = _v1; } else { v0p = _v0 + v0v1 * s01; } } else if (s02 > 1.0) { s12 = ( v1v2 | ( _p - _v1 )) * inv_v1v2_2; if (s12 >= 1.0) { v0p = _v2; } else if (s12 <= 0.0) { v0p = _v1; } else { v0p = _v1 + v1v2 * s12; } } else { v0p = _v0 + v0v2 * s02; } } else if (b < 0.0) { // Calculate the distance to an edge or a corner vertex s01 = ( v0v1 | v0p ) * inv_v0v1_2; if (s01 < 0.0) { const Point n = v0v1 % v0v2; // not normalized ! s02 = ( v0v2 | v0p ) * inv_v0v2_2; if (s02 <= 0.0) { v0p = _v0; } else if (s02 >= 1.0) { v0p = _v2; } else { v0p = _v0 + v0v2 * s02; } } else if (s01 > 1.0) { s12 = ( v1v2 | ( _p - _v1 )) * inv_v1v2_2; if (s12 >= 1.0) { v0p = _v2; } else if (s12 <= 0.0) { v0p = _v1; } else { v0p = _v1 + v1v2 * s12; } } else { v0p = _v0 + v0v1 * s01; } } else if (a+b > 1.0) { // Calculate the distance to an edge or a corner vertex s12 = ( v1v2 | ( _p - _v1 )) * inv_v1v2_2; if (s12 >= 1.0) { s02 = ( v0v2 | v0p ) * inv_v0v2_2; if (s02 <= 0.0) { v0p = _v0; } else if (s02 >= 1.0) { v0p = _v2; } else { v0p = _v0 + v0v2*s02; } } else if (s12 <= 0.0) { s01 = ( v0v1 | v0p ) * inv_v0v1_2; if (s01 <= 0.0) { v0p = _v0; } else if (s01 >= 1.0) { v0p = _v1; } else { v0p = _v0 + v0v1 * s01; } } else { v0p = _v1 + v1v2 * s12; } } else { // Calculate the distance to an interior point of the triangle return ( (_p - n*((n|v0p) * invD)) - _p).sqrnorm(); } return (v0p - _p).sqrnorm(); } template <class MeshT> void ModHausdorffT<MeshT>:: initialize() { typename Mesh::FIter f_it(mesh_.faces_begin()), f_end(mesh_.faces_end()); for (; f_it!=f_end; ++f_it) mesh_.property(points_, f_it).clear(); } //----------------------------------------------------------------------------- template <class MeshT> float ModHausdorffT<MeshT>:: collapse_priority(const CollapseInfo& _ci) { static Points points; points.clear(); std::vector<FaceHandle> faces; faces.reserve(20); typename Mesh::VertexFaceIter vf_it; typename Mesh::FaceHandle fh; typename Mesh::Scalar sqr_tolerace = tolerance_*tolerance_; typename Mesh::CFVIter fv_it; bool ok; // collect all points to be tested // collect all faces to be tested against for (vf_it=mesh_.vf_iter(_ci.v0); vf_it; ++vf_it) { fh = vf_it.handle(); if (fh != _ci.fl && fh != _ci.fr) faces.push_back(fh); Points& pts = mesh_.property(points_, fh); std::copy(pts.begin(), pts.end(), std::back_inserter(points)); } // add point to be removed points.push_back(_ci.p0); // setup iterators typename std::vector<FaceHandle>::iterator fh_it, fh_end(faces.end()); typename Points::const_iterator p_it, p_end(points.end()); // simulate collapse mesh_.set_point(_ci.v0, _ci.p1); // for each point: try to find a face such that error is < tolerance ok = true; for (p_it=points.begin(); ok && p_it!=p_end; ++p_it) { ok = false; for (fh_it=faces.begin(); !ok && fh_it!=fh_end; ++fh_it) { const Point& p0 = mesh_.point(fv_it=mesh_.cfv_iter(*fh_it)); const Point& p1 = mesh_.point(++fv_it); const Point& p2 = mesh_.point(++fv_it); if ( distPointTriangleSquared(*p_it, p0, p1, p2) <= sqr_tolerace) ok = true; } } // undo simulation changes mesh_.set_point(_ci.v0, _ci.p0); return ( ok ? Base::LEGAL_COLLAPSE : Base::ILLEGAL_COLLAPSE ); } //----------------------------------------------------------------------------- template<class MeshT> void ModHausdorffT<MeshT>::set_error_tolerance_factor(double _factor) { if (_factor >= 0.0 && _factor <= 1.0) { // the smaller the factor, the smaller tolerance gets // thus creating a stricter constraint // division by error_tolerance_factor_ is for normalization Scalar tolerance = tolerance_ * _factor / this->error_tolerance_factor_; set_tolerance(tolerance); this->error_tolerance_factor_ = _factor; } } //----------------------------------------------------------------------------- template <class MeshT> void ModHausdorffT<MeshT>:: postprocess_collapse(const CollapseInfo& _ci) { static Points points; typename Mesh::VertexFaceIter vf_it; FaceHandle fh; std::vector<FaceHandle> faces; // collect points & neighboring triangles points.clear(); // it's static ! faces.reserve(20); // collect active faces and their points for (vf_it=mesh_.vf_iter(_ci.v1); vf_it; ++vf_it) { fh = vf_it.handle(); faces.push_back(fh); Points& pts = mesh_.property(points_, fh); std::copy(pts.begin(), pts.end(), std::back_inserter(points)); pts.clear(); } if (faces.empty()) return; // should not happen anyway... // collect points of the 2 deleted faces if ((fh=_ci.fl).is_valid()) { Points& pts = mesh_.property(points_, fh); std::copy(pts.begin(), pts.end(), std::back_inserter(points)); pts.clear(); } if ((fh=_ci.fr).is_valid()) { Points& pts = mesh_.property(points_, fh); std::copy(pts.begin(), pts.end(), std::back_inserter(points)); pts.clear(); } // add the deleted point points.push_back(_ci.p0); // setup iterators typename std::vector<FaceHandle>::iterator fh_it, fh_end(faces.end()); typename Points::const_iterator p_it, p_end(points.end()); // re-distribute points Scalar emin, e; typename Mesh::CFVIter fv_it; for (p_it=points.begin(); p_it!=p_end; ++p_it) { emin = FLT_MAX; for (fh_it=faces.begin(); fh_it!=fh_end; ++fh_it) { const Point& p0 = mesh_.point(fv_it=mesh_.cfv_iter(*fh_it)); const Point& p1 = mesh_.point(++fv_it); const Point& p2 = mesh_.point(++fv_it); e = distPointTriangleSquared(*p_it, p0, p1, p2); if (e < emin) { emin = e; fh = *fh_it; } } mesh_.property(points_, fh).push_back(*p_it); } } //----------------------------------------------------------------------------- template <class MeshT> typename ModHausdorffT<MeshT>::Scalar ModHausdorffT<MeshT>:: compute_sqr_error(FaceHandle _fh, const Point& _p) const { typename Mesh::CFVIter fv_it = mesh_.cfv_iter(_fh); const Point& p0 = mesh_.point(fv_it); const Point& p1 = mesh_.point(++fv_it); const Point& p2 = mesh_.point(++fv_it); const Points& points = mesh_.property(points_, _fh); typename Points::const_iterator p_it = points.begin(); typename Points::const_iterator p_end = points.end(); Point dummy; Scalar e; Scalar emax = distPointTriangleSquared(_p, p0, p1, p2); #ifdef USE_OPENMP int pointsCount = points.size(); #pragma omp parallel for private(e) shared(emax) for (int i = 0; i < pointsCount; ++i) { e = distPointTriangleSquared(points[i], p0, p1, p2); #pragma omp critical(emaxUpdate) { if (e > emax) emax = e; } } #else for (; p_it!=p_end; ++p_it) { e = distPointTriangleSquared(*p_it, p0, p1, p2); if (e > emax) emax = e; } #endif return emax; } //============================================================================= } } //============================================================================= <commit_msg>Removed OpenMP stuff<commit_after>/*===========================================================================*\ * * * OpenMesh * * Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * * * * OpenMesh is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenMesh 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 LesserGeneral Public * * License along with OpenMesh. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision: 448 $ * * $Date: 2011-11-04 13:59:37 +0100 (Fri, 04 Nov 2011) $ * * * \*===========================================================================*/ /** \file ModHausdorffT.cc */ //============================================================================= // // CLASS ModHausdorffT - IMPLEMENTATION // //============================================================================= #define OPENMESH_DECIMATER_MODHAUSDORFFT_C //== INCLUDES ================================================================= #include "ModHausdorffT.hh" //== NAMESPACES =============================================================== namespace OpenMesh { namespace Decimater { //== IMPLEMENTATION ========================================================== template <class MeshT> typename ModHausdorffT<MeshT>::Scalar ModHausdorffT<MeshT>:: distPointTriangleSquared( const Point& _p, const Point& _v0, const Point& _v1, const Point& _v2 ) { const Point v0v1 = _v1 - _v0; const Point v0v2 = _v2 - _v0; const Point n = v0v1 % v0v2; // not normalized ! const double d = n.sqrnorm(); // Check if the triangle is degenerated if (d < FLT_MIN && d > -FLT_MIN) { return -1.0; } const double invD = 1.0 / d; // these are not needed for every point, should still perform // better with many points against one triangle const Point v1v2 = _v2 - _v1; const double inv_v0v2_2 = 1.0 / v0v2.sqrnorm(); const double inv_v0v1_2 = 1.0 / v0v1.sqrnorm(); const double inv_v1v2_2 = 1.0 / v1v2.sqrnorm(); Point v0p = _p - _v0; Point t = v0p % n; double s01, s02, s12; const double a = (t | v0v2) * -invD; const double b = (t | v0v1) * invD; if (a < 0) { // Calculate the distance to an edge or a corner vertex s02 = ( v0v2 | v0p ) * inv_v0v2_2; if (s02 < 0.0) { s01 = ( v0v1 | v0p ) * inv_v0v1_2; if (s01 <= 0.0) { v0p = _v0; } else if (s01 >= 1.0) { v0p = _v1; } else { v0p = _v0 + v0v1 * s01; } } else if (s02 > 1.0) { s12 = ( v1v2 | ( _p - _v1 )) * inv_v1v2_2; if (s12 >= 1.0) { v0p = _v2; } else if (s12 <= 0.0) { v0p = _v1; } else { v0p = _v1 + v1v2 * s12; } } else { v0p = _v0 + v0v2 * s02; } } else if (b < 0.0) { // Calculate the distance to an edge or a corner vertex s01 = ( v0v1 | v0p ) * inv_v0v1_2; if (s01 < 0.0) { const Point n = v0v1 % v0v2; // not normalized ! s02 = ( v0v2 | v0p ) * inv_v0v2_2; if (s02 <= 0.0) { v0p = _v0; } else if (s02 >= 1.0) { v0p = _v2; } else { v0p = _v0 + v0v2 * s02; } } else if (s01 > 1.0) { s12 = ( v1v2 | ( _p - _v1 )) * inv_v1v2_2; if (s12 >= 1.0) { v0p = _v2; } else if (s12 <= 0.0) { v0p = _v1; } else { v0p = _v1 + v1v2 * s12; } } else { v0p = _v0 + v0v1 * s01; } } else if (a+b > 1.0) { // Calculate the distance to an edge or a corner vertex s12 = ( v1v2 | ( _p - _v1 )) * inv_v1v2_2; if (s12 >= 1.0) { s02 = ( v0v2 | v0p ) * inv_v0v2_2; if (s02 <= 0.0) { v0p = _v0; } else if (s02 >= 1.0) { v0p = _v2; } else { v0p = _v0 + v0v2*s02; } } else if (s12 <= 0.0) { s01 = ( v0v1 | v0p ) * inv_v0v1_2; if (s01 <= 0.0) { v0p = _v0; } else if (s01 >= 1.0) { v0p = _v1; } else { v0p = _v0 + v0v1 * s01; } } else { v0p = _v1 + v1v2 * s12; } } else { // Calculate the distance to an interior point of the triangle return ( (_p - n*((n|v0p) * invD)) - _p).sqrnorm(); } return (v0p - _p).sqrnorm(); } template <class MeshT> void ModHausdorffT<MeshT>:: initialize() { typename Mesh::FIter f_it(mesh_.faces_begin()), f_end(mesh_.faces_end()); for (; f_it!=f_end; ++f_it) mesh_.property(points_, f_it).clear(); } //----------------------------------------------------------------------------- template <class MeshT> float ModHausdorffT<MeshT>:: collapse_priority(const CollapseInfo& _ci) { static Points points; points.clear(); std::vector<FaceHandle> faces; faces.reserve(20); typename Mesh::VertexFaceIter vf_it; typename Mesh::FaceHandle fh; const typename Mesh::Scalar sqr_tolerace = tolerance_*tolerance_; typename Mesh::CFVIter fv_it; bool ok; // collect all points to be tested // collect all faces to be tested against for (vf_it=mesh_.vf_iter(_ci.v0); vf_it; ++vf_it) { fh = vf_it.handle(); if (fh != _ci.fl && fh != _ci.fr) faces.push_back(fh); Points& pts = mesh_.property(points_, fh); std::copy(pts.begin(), pts.end(), std::back_inserter(points)); } // add point to be removed points.push_back(_ci.p0); // setup iterators typename std::vector<FaceHandle>::iterator fh_it, fh_end(faces.end()); typename Points::const_iterator p_it, p_end(points.end()); // simulate collapse mesh_.set_point(_ci.v0, _ci.p1); // for each point: try to find a face such that error is < tolerance ok = true; for (p_it=points.begin(); ok && p_it!=p_end; ++p_it) { ok = false; for (fh_it=faces.begin(); !ok && fh_it!=fh_end; ++fh_it) { const Point& p0 = mesh_.point(fv_it=mesh_.cfv_iter(*fh_it)); const Point& p1 = mesh_.point(++fv_it); const Point& p2 = mesh_.point(++fv_it); if ( distPointTriangleSquared(*p_it, p0, p1, p2) <= sqr_tolerace) ok = true; } } // undo simulation changes mesh_.set_point(_ci.v0, _ci.p0); return ( ok ? Base::LEGAL_COLLAPSE : Base::ILLEGAL_COLLAPSE ); } //----------------------------------------------------------------------------- template<class MeshT> void ModHausdorffT<MeshT>::set_error_tolerance_factor(double _factor) { if (_factor >= 0.0 && _factor <= 1.0) { // the smaller the factor, the smaller tolerance gets // thus creating a stricter constraint // division by error_tolerance_factor_ is for normalization Scalar tolerance = tolerance_ * _factor / this->error_tolerance_factor_; set_tolerance(tolerance); this->error_tolerance_factor_ = _factor; } } //----------------------------------------------------------------------------- template <class MeshT> void ModHausdorffT<MeshT>:: postprocess_collapse(const CollapseInfo& _ci) { static Points points; typename Mesh::VertexFaceIter vf_it; FaceHandle fh; std::vector<FaceHandle> faces; // collect points & neighboring triangles points.clear(); // it's static ! faces.reserve(20); // collect active faces and their points for (vf_it=mesh_.vf_iter(_ci.v1); vf_it; ++vf_it) { fh = vf_it.handle(); faces.push_back(fh); Points& pts = mesh_.property(points_, fh); std::copy(pts.begin(), pts.end(), std::back_inserter(points)); pts.clear(); } if (faces.empty()) return; // should not happen anyway... // collect points of the 2 deleted faces if ((fh=_ci.fl).is_valid()) { Points& pts = mesh_.property(points_, fh); std::copy(pts.begin(), pts.end(), std::back_inserter(points)); pts.clear(); } if ((fh=_ci.fr).is_valid()) { Points& pts = mesh_.property(points_, fh); std::copy(pts.begin(), pts.end(), std::back_inserter(points)); pts.clear(); } // add the deleted point points.push_back(_ci.p0); // setup iterators typename std::vector<FaceHandle>::iterator fh_it, fh_end(faces.end()); typename Points::const_iterator p_it, p_end(points.end()); // re-distribute points Scalar emin, e; typename Mesh::CFVIter fv_it; for (p_it=points.begin(); p_it!=p_end; ++p_it) { emin = FLT_MAX; for (fh_it=faces.begin(); fh_it!=fh_end; ++fh_it) { const Point& p0 = mesh_.point(fv_it=mesh_.cfv_iter(*fh_it)); const Point& p1 = mesh_.point(++fv_it); const Point& p2 = mesh_.point(++fv_it); e = distPointTriangleSquared(*p_it, p0, p1, p2); if (e < emin) { emin = e; fh = *fh_it; } } mesh_.property(points_, fh).push_back(*p_it); } } //----------------------------------------------------------------------------- template <class MeshT> typename ModHausdorffT<MeshT>::Scalar ModHausdorffT<MeshT>:: compute_sqr_error(FaceHandle _fh, const Point& _p) const { typename Mesh::CFVIter fv_it = mesh_.cfv_iter(_fh); const Point& p0 = mesh_.point(fv_it); const Point& p1 = mesh_.point(++fv_it); const Point& p2 = mesh_.point(++fv_it); const Points& points = mesh_.property(points_, _fh); typename Points::const_iterator p_it = points.begin(); typename Points::const_iterator p_end = points.end(); Point dummy; Scalar e; Scalar emax = distPointTriangleSquared(_p, p0, p1, p2); for (; p_it!=p_end; ++p_it) { e = distPointTriangleSquared(*p_it, p0, p1, p2); if (e > emax) emax = e; } return emax; } //============================================================================= } } //============================================================================= <|endoftext|>
<commit_before>/** Copyright (c) 2017, Philip Deegan. 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 Philip Deegan 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. */ #ifndef _KUL_TUPLE_HPP_ #define _KUL_TUPLE_HPP_ #include "kul/for.hpp" namespace kul { template <size_t N, typename T> struct Pointer { static constexpr size_t INDEX = N; T* p = nullptr; }; template <typename T, typename SIZE = size_t> struct Pointers { Pointers(T const* p_, SIZE s_) : p{p_}, s{s_} {} T const* p = nullptr; SIZE s = 0; auto& operator[](SIZE i) const { return p[i]; } auto& begin() const { return p; } auto end() const { return p + s; } auto& size() const { return s; } }; template <typename Tuple> struct PointersApply { PointersApply(Tuple& t) : tuple{t} {} template <size_t i> decltype(auto) operator()() { auto t = std::get<i>(tuple); using T = decltype(t); if constexpr (std::is_pointer<T>::value) return Pointer<i, std::remove_pointer_t<std::decay_t<T>>>{t}; else return Pointer<i, std::decay_t<T>>{&t}; } Tuple& tuple; }; template <typename... Pointer> struct PointerContainer : public Pointer... { PointerContainer(Pointer&... args) : Pointer(std::forward<Pointer>(args))... {} }; template <typename... Args> decltype(auto) _make_pointer_container(std::tuple<Args...>&& t) { return std::make_from_tuple<PointerContainer<Args...>>(t); } template <typename... Refs> decltype(auto) make_pointer_container(Refs&&... args) { auto tuple = std::forward_as_tuple(args...); constexpr size_t size = std::tuple_size<decltype(tuple)>::value; return _make_pointer_container(for_N<size>(PointersApply{tuple})); } template <typename T> struct ApplySingleTupleValue { constexpr ApplySingleTupleValue(T t_) : t{t_} {} template <size_t i> constexpr decltype(auto) operator()() { return t; } T t; }; template <typename T, size_t Size> constexpr decltype(auto) tuple_from(T t) { return for_N<Size>(ApplySingleTupleValue{t}); } } // namespace kul #endif /* _KUL_TUPLE_HPP_ */ <commit_msg>data() for Pointers<T><commit_after>/** Copyright (c) 2017, Philip Deegan. 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 Philip Deegan 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. */ #ifndef _KUL_TUPLE_HPP_ #define _KUL_TUPLE_HPP_ #include "kul/for.hpp" namespace kul { template <size_t N, typename T> struct Pointer { static constexpr size_t INDEX = N; T* p = nullptr; }; template <typename T, typename SIZE = size_t> struct Pointers { Pointers(T const* p_, SIZE s_) : p{p_}, s{s_} {} T const* p = nullptr; SIZE s = 0; auto& operator[](SIZE i) const { return p[i]; } auto& data() const { return p; } auto& begin() const { return p; } auto end() const { return p + s; } auto& size() const { return s; } }; template <typename Tuple> struct PointersApply { PointersApply(Tuple& t) : tuple{t} {} template <size_t i> decltype(auto) operator()() { auto t = std::get<i>(tuple); using T = decltype(t); if constexpr (std::is_pointer<T>::value) return Pointer<i, std::remove_pointer_t<std::decay_t<T>>>{t}; else return Pointer<i, std::decay_t<T>>{&t}; } Tuple& tuple; }; template <typename... Pointer> struct PointerContainer : public Pointer... { PointerContainer(Pointer&... args) : Pointer(std::forward<Pointer>(args))... {} }; template <typename... Args> decltype(auto) _make_pointer_container(std::tuple<Args...>&& t) { return std::make_from_tuple<PointerContainer<Args...>>(t); } template <typename... Refs> decltype(auto) make_pointer_container(Refs&&... args) { auto tuple = std::forward_as_tuple(args...); constexpr size_t size = std::tuple_size<decltype(tuple)>::value; return _make_pointer_container(for_N<size>(PointersApply{tuple})); } template <typename T> struct ApplySingleTupleValue { constexpr ApplySingleTupleValue(T t_) : t{t_} {} template <size_t i> constexpr decltype(auto) operator()() { return t; } T t; }; template <typename T, size_t Size> constexpr decltype(auto) tuple_from(T t) { return for_N<Size>(ApplySingleTupleValue{t}); } } // namespace kul #endif /* _KUL_TUPLE_HPP_ */ <|endoftext|>
<commit_before>#ifndef PROCESS_H #define PROCESS_H #include"heaps.hpp" #include"errors.hpp" #include<vector> #include<stack> #include<boost/shared_ptr.hpp> class Process; /*Use our own stack in order to support restack()*/ class ProcessStack{ private: std::vector<Generic*> stack; public: Generic*& top(size_t off=1){ if(off > stack.size() || off == 0){ throw ArcError("internal", "Process stack underflow in top()"); } return stack[stack.size() - off]; } void pop(size_t num=1){ if(num > stack.size()){ throw ArcError( "internal", "Process stack underflow in pop()"); } if(num != 0) stack.resize(stack.size() - num); } void push(Generic* gp){ stack.push_back(gp); } /*Used in function calls*/ void restack(size_t sz){ if(sz > stack.size()){ throw ArcError( "internal", "Process stack underflow in restack()"); } size_t off = stack.size() - sz; /*Not exactly the best way to do it?*/ if(sz != 0) stack.erase(stack.begin(), stack.begin() + off); } size_t size(void) const{ return stack.size(); }; friend class Process; }; class Atom; class Process : public Heap { private: //should also be locked using the other_spaces lock std::vector<Generic*> mailbox; Generic* queue;//handled by Arc-side code protected: virtual void get_root_set(std::stack<Generic**>& s){ if(queue != NULL) s.push(&queue); for(std::vector<Generic*>::iterator i = mailbox.begin(); i != mailbox.end(); ++i){ s.push(&*i); } for(std::vector<Generic*>::iterator i = stack.stack.begin(); i != stack.stack.end(); ++i){ s.push(&*i); } } public: ProcessStack stack; void sendto(Process&, Generic*) const ; void assign(boost::shared_ptr<Atom>, Generic*) const ; virtual ~Process(){}; Process() : Heap(), queue(NULL) {}; }; #endif //PROCESS_H <commit_msg>Added operator[] to ProcessStack to allow easy access to arbitrary locals<commit_after>#ifndef PROCESS_H #define PROCESS_H #include"heaps.hpp" #include"errors.hpp" #include<vector> #include<stack> #include<boost/shared_ptr.hpp> class Process; /*Use our own stack in order to support restack()*/ class ProcessStack{ private: std::vector<Generic*> stack; public: Generic*& top(size_t off=1){ if(off > stack.size() || off == 0){ throw ArcError("internal", "Process stack underflow in top()"); } return stack[stack.size() - off]; } void pop(size_t num=1){ if(num > stack.size()){ throw ArcError( "internal", "Process stack underflow in pop()"); } if(num != 0) stack.resize(stack.size() - num); } void push(Generic* gp){ stack.push_back(gp); } /*Used in function calls*/ void restack(size_t sz){ if(sz > stack.size()){ throw ArcError( "internal", "Process stack underflow in restack()"); } size_t off = stack.size() - sz; /*Not exactly the best way to do it?*/ if(sz != 0) stack.erase(stack.begin(), stack.begin() + off); } Generic*& operator[](int i){ return stack[i]; } size_t size(void) const{ return stack.size(); }; friend class Process; }; class Atom; class Process : public Heap { private: //should also be locked using the other_spaces lock std::vector<Generic*> mailbox; Generic* queue;//handled by Arc-side code protected: virtual void get_root_set(std::stack<Generic**>& s){ if(queue != NULL) s.push(&queue); for(std::vector<Generic*>::iterator i = mailbox.begin(); i != mailbox.end(); ++i){ s.push(&*i); } for(std::vector<Generic*>::iterator i = stack.stack.begin(); i != stack.stack.end(); ++i){ s.push(&*i); } } public: ProcessStack stack; void sendto(Process&, Generic*) const ; void assign(boost::shared_ptr<Atom>, Generic*) const ; virtual ~Process(){}; Process() : Heap(), queue(NULL) {}; }; #endif //PROCESS_H <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/ 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 "mitkSurfaceToImageFilter.h" #include <vtkPolyData.h> #include <vtkPolyDataToImageStencil.h> #include <vtkImageStencil.h> #include <vtkImageData.h> #include <vtkPolyData.h> #include <vtkTransformPolyDataFilter.h> #include <vtkTriangleFilter.h> #include <vtkDataSetTriangleFilter.h> #include <vtkImageThreshold.h> #include <vtkImageMathematics.h> #include <vtkPolyDataNormals.h> mitk::SurfaceToImageFilter::SurfaceToImageFilter() { } mitk::SurfaceToImageFilter::~SurfaceToImageFilter() { } void mitk::SurfaceToImageFilter::GenerateOutputInformation() { mitk::Surface::ConstPointer input = this->GetInput(); mitk::Image::Pointer output = this->GetOutput(); itkDebugMacro(<<"GenerateOutputInformation()"); if(input.IsNull()) return; // output->SetGeometry(static_cast<Geometry3D*>(input->GetGeometry()->Clone().GetPointer())); } void mitk::SurfaceToImageFilter::GenerateData() { vtkPolyDataNormals * normalsFilter = vtkPolyDataNormals::New(); normalsFilter->SetInput( ( (mitk::Surface*)GetInput() )->GetVtkPolyData() ); normalsFilter->SetFeatureAngle(50); normalsFilter->SetConsistency(1); normalsFilter->SetSplitting(1); normalsFilter->SetFlipNormals(0); normalsFilter->Update(); vtkPolyDataToImageStencil * surfaceConverter = vtkPolyDataToImageStencil::New(); surfaceConverter->SetInput( normalsFilter->GetOutput() ); surfaceConverter->SetTolerance( 0.0 ); surfaceConverter->Update(); vtkImageData * tmp = ( (mitk::Image*)GetImage() )->GetVtkImageData(); vtkImageMathematics * maths = vtkImageMathematics::New(); maths->SetOperationToAddConstant(); maths->SetConstantC(100); maths->SetConstantK(100); maths->SetInput1(tmp); maths->Update(); vtkImageStencil * stencil = vtkImageStencil::New(); stencil->SetStencil( surfaceConverter->GetOutput() ); stencil->SetBackgroundValue( 0 ); stencil->ReverseStencilOff(); stencil->SetInput( maths->GetOutput() ); stencil->Update(); vtkImageThreshold * threshold = vtkImageThreshold::New(); threshold->SetInput( stencil->GetOutput() ); threshold->ThresholdByUpper(1); threshold->ReplaceInOn(); threshold->SetInValue(1); threshold->Update(); mitk::Image::Pointer output = this->GetOutput(); output->Initialize( threshold->GetOutput() ); output->SetVolume( threshold->GetOutput()->GetScalarPointer() ); } const mitk::Surface *mitk::SurfaceToImageFilter::GetInput(void) { if (this->GetNumberOfInputs() < 1) { return 0; } return static_cast<const mitk::Surface * > ( this->ProcessObject::GetInput(0) ); } void mitk::SurfaceToImageFilter::SetInput(const mitk::Surface *input) { // Process object is not const-correct so the const_cast is required here this->ProcessObject::SetNthInput(0, const_cast< mitk::Surface * >( input ) ); } void mitk::SurfaceToImageFilter::SetImage(const mitk::Image *source) { this->ProcessObject::SetNthInput( 1, const_cast< mitk::Image * >( source ) ); } const mitk::Image *mitk::SurfaceToImageFilter::GetImage(void) { return static_cast< const mitk::Image * >(this->ProcessObject::GetInput(1)); } <commit_msg>FIX: added move<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/ 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 "mitkSurfaceToImageFilter.h" #include <vtkPolyData.h> #include <vtkPolyDataToImageStencil.h> #include <vtkImageStencil.h> #include <vtkImageData.h> #include <vtkPolyData.h> #include <vtkTriangleFilter.h> #include <vtkDataSetTriangleFilter.h> #include <vtkImageThreshold.h> #include <vtkImageMathematics.h> #include <vtkPolyDataNormals.h> #include <vtkTransformPolyDataFilter.h> #include <vtkTransform.h> mitk::SurfaceToImageFilter::SurfaceToImageFilter() { } mitk::SurfaceToImageFilter::~SurfaceToImageFilter() { } void mitk::SurfaceToImageFilter::GenerateOutputInformation() { mitk::Surface::ConstPointer input = this->GetInput(); mitk::Image::Pointer output = this->GetOutput(); itkDebugMacro(<<"GenerateOutputInformation()"); if(input.IsNull()) return; // output->SetGeometry(static_cast<Geometry3D*>(input->GetGeometry()->Clone().GetPointer())); } void mitk::SurfaceToImageFilter::GenerateData() { vtkPolyData * polydata = ( (mitk::Surface*)GetInput() )->GetVtkPolyData(); vtkTransformPolyDataFilter * move=vtkTransformPolyDataFilter::New(); move->SetInput(polydata); vtkTransform *transform=vtkTransform::New(); mitk::Vector3D spacing=GetImage()->GetSlicedGeometry()->GetSpacing(); spacing*=0.5; transform->Translate(spacing[0],spacing[1],spacing[2]); move->SetTransform(transform); polydata=move->GetOutput(); vtkPolyDataNormals * normalsFilter = vtkPolyDataNormals::New(); normalsFilter->SetInput( polydata ); normalsFilter->SetFeatureAngle(50); normalsFilter->SetConsistency(1); normalsFilter->SetSplitting(1); normalsFilter->SetFlipNormals(0); normalsFilter->Update(); vtkPolyDataToImageStencil * surfaceConverter = vtkPolyDataToImageStencil::New(); surfaceConverter->SetInput( normalsFilter->GetOutput() ); surfaceConverter->SetTolerance( 0.0 ); surfaceConverter->Update(); vtkImageData * tmp = ( (mitk::Image*)GetImage() )->GetVtkImageData(); vtkImageMathematics * maths = vtkImageMathematics::New(); maths->SetOperationToAddConstant(); maths->SetConstantC(100); maths->SetConstantK(100); maths->SetInput1(tmp); maths->Update(); vtkImageStencil * stencil = vtkImageStencil::New(); stencil->SetStencil( surfaceConverter->GetOutput() ); stencil->SetBackgroundValue( 0 ); stencil->ReverseStencilOff(); stencil->SetInput( maths->GetOutput() ); stencil->Update(); vtkImageThreshold * threshold = vtkImageThreshold::New(); threshold->SetInput( stencil->GetOutput() ); threshold->ThresholdByUpper(1); threshold->ReplaceInOn(); threshold->SetInValue(1); threshold->Update(); mitk::Image::Pointer output = this->GetOutput(); output->Initialize( threshold->GetOutput() ); output->SetVolume( threshold->GetOutput()->GetScalarPointer() ); } const mitk::Surface *mitk::SurfaceToImageFilter::GetInput(void) { if (this->GetNumberOfInputs() < 1) { return 0; } return static_cast<const mitk::Surface * > ( this->ProcessObject::GetInput(0) ); } void mitk::SurfaceToImageFilter::SetInput(const mitk::Surface *input) { // Process object is not const-correct so the const_cast is required here this->ProcessObject::SetNthInput(0, const_cast< mitk::Surface * >( input ) ); } void mitk::SurfaceToImageFilter::SetImage(const mitk::Image *source) { this->ProcessObject::SetNthInput( 1, const_cast< mitk::Image * >( source ) ); } const mitk::Image *mitk::SurfaceToImageFilter::GetImage(void) { return static_cast< const mitk::Image * >(this->ProcessObject::GetInput(1)); } <|endoftext|>
<commit_before>#include "command.hh" #include "common-args.hh" #include "shared.hh" #include "progress-bar.hh" #include "eval.hh" #include "eval-inline.hh" #include "primops/flake.hh" #include "get-drvs.hh" #include "store-api.hh" #include <nlohmann/json.hpp> #include <queue> #include <iomanip> using namespace nix; using namespace nix::flake; class FlakeCommand : virtual Args, public EvalCommand, public MixFlakeOptions { std::string flakeUri = "."; public: FlakeCommand() { expectArg("flake-uri", &flakeUri, true); } FlakeRef getFlakeRef() { if (flakeUri.find('/') != std::string::npos || flakeUri == ".") return FlakeRef(flakeUri, true); else return FlakeRef(flakeUri); } Flake getFlake() { auto evalState = getEvalState(); return flake::getFlake(*evalState, getFlakeRef(), useRegistries); } ResolvedFlake resolveFlake() { return flake::resolveFlake(*getEvalState(), getFlakeRef(), getLockFileMode()); } }; struct CmdFlakeList : EvalCommand { std::string name() override { return "list"; } std::string description() override { return "list available Nix flakes"; } void run(nix::ref<nix::Store> store) override { auto registries = getEvalState()->getFlakeRegistries(); stopProgressBar(); for (auto & entry : registries[FLAG_REGISTRY]->entries) std::cout << entry.first.to_string() << " flags " << entry.second.to_string() << "\n"; for (auto & entry : registries[USER_REGISTRY]->entries) std::cout << entry.first.to_string() << " user " << entry.second.to_string() << "\n"; for (auto & entry : registries[GLOBAL_REGISTRY]->entries) std::cout << entry.first.to_string() << " global " << entry.second.to_string() << "\n"; } }; static void printSourceInfo(const SourceInfo & sourceInfo) { std::cout << fmt("URI: %s\n", sourceInfo.resolvedRef.to_string()); if (sourceInfo.resolvedRef.ref) std::cout << fmt("Branch: %s\n",*sourceInfo.resolvedRef.ref); if (sourceInfo.resolvedRef.rev) std::cout << fmt("Revision: %s\n", sourceInfo.resolvedRef.rev->to_string(Base16, false)); if (sourceInfo.revCount) std::cout << fmt("Revisions: %s\n", *sourceInfo.revCount); if (sourceInfo.lastModified) std::cout << fmt("Last modified: %s\n", std::put_time(std::localtime(&*sourceInfo.lastModified), "%F %T")); std::cout << fmt("Path: %s\n", sourceInfo.storePath); } static void sourceInfoToJson(const SourceInfo & sourceInfo, nlohmann::json & j) { j["uri"] = sourceInfo.resolvedRef.to_string(); if (sourceInfo.resolvedRef.ref) j["branch"] = *sourceInfo.resolvedRef.ref; if (sourceInfo.resolvedRef.rev) j["revision"] = sourceInfo.resolvedRef.rev->to_string(Base16, false); if (sourceInfo.revCount) j["revCount"] = *sourceInfo.revCount; if (sourceInfo.lastModified) j["lastModified"] = *sourceInfo.lastModified; j["path"] = sourceInfo.storePath; } static void printFlakeInfo(const Flake & flake) { std::cout << fmt("ID: %s\n", flake.id); std::cout << fmt("Description: %s\n", flake.description); std::cout << fmt("Epoch: %s\n", flake.epoch); printSourceInfo(flake.sourceInfo); } static nlohmann::json flakeToJson(const Flake & flake) { nlohmann::json j; j["id"] = flake.id; j["description"] = flake.description; j["epoch"] = flake.epoch; sourceInfoToJson(flake.sourceInfo, j); return j; } static void printNonFlakeInfo(const NonFlake & nonFlake) { std::cout << fmt("ID: %s\n", nonFlake.alias); printSourceInfo(nonFlake.sourceInfo); } static nlohmann::json nonFlakeToJson(const NonFlake & nonFlake) { nlohmann::json j; j["id"] = nonFlake.alias; sourceInfoToJson(nonFlake.sourceInfo, j); return j; } // FIXME: merge info CmdFlakeInfo? struct CmdFlakeDeps : FlakeCommand { std::string name() override { return "deps"; } std::string description() override { return "list informaton about dependencies"; } void run(nix::ref<nix::Store> store) override { auto evalState = getEvalState(); evalState->addRegistryOverrides(registryOverrides); std::queue<ResolvedFlake> todo; todo.push(resolveFlake()); stopProgressBar(); while (!todo.empty()) { auto resFlake = std::move(todo.front()); todo.pop(); for (auto & nonFlake : resFlake.nonFlakeDeps) printNonFlakeInfo(nonFlake); for (auto & info : resFlake.flakeDeps) { printFlakeInfo(info.second.flake); todo.push(info.second); } } } }; struct CmdFlakeUpdate : FlakeCommand { std::string name() override { return "update"; } std::string description() override { return "update flake lock file"; } void run(nix::ref<nix::Store> store) override { auto evalState = getEvalState(); auto flakeRef = getFlakeRef(); if (std::get_if<FlakeRef::IsPath>(&flakeRef.data)) updateLockFile(*evalState, flakeRef, true); else throw Error("cannot update lockfile of flake '%s'", flakeRef); } }; struct CmdFlakeInfo : FlakeCommand, MixJSON { std::string name() override { return "info"; } std::string description() override { return "list info about a given flake"; } void run(nix::ref<nix::Store> store) override { auto flake = getFlake(); stopProgressBar(); if (json) std::cout << flakeToJson(flake).dump() << std::endl; else printFlakeInfo(flake); } }; static void enumerateProvides(EvalState & state, Value & vFlake, std::function<void(const std::string & name, Value & vProvide)> callback) { state.forceAttrs(vFlake); auto vProvides = (*vFlake.attrs->get(state.symbols.create("provides")))->value; state.forceAttrs(*vProvides); for (auto & attr : *vProvides->attrs) callback(attr.name, *attr.value); } struct CmdFlakeCheck : FlakeCommand, MixJSON { bool build = true; CmdFlakeCheck() { mkFlag() .longName("no-build") .description("do not build checks") .set(&build, false); } std::string name() override { return "check"; } std::string description() override { return "check whether the flake evaluates and run its tests"; } void run(nix::ref<nix::Store> store) override { auto state = getEvalState(); auto flake = resolveFlake(); PathSet drvPaths; { Activity act(*logger, lvlInfo, actUnknown, "evaluating flake"); auto vFlake = state->allocValue(); flake::callFlake(*state, flake, *vFlake); enumerateProvides(*state, *vFlake, [&](const std::string & name, Value & vProvide) { Activity act(*logger, lvlChatty, actUnknown, fmt("checking flake output '%s'", name)); try { state->forceValue(vProvide); if (name == "checks") { state->forceAttrs(vProvide); for (auto & aCheck : *vProvide.attrs) { try { auto drvInfo = getDerivation(*state, *aCheck.value, false); if (!drvInfo) throw Error("flake output 'check.%s' is not a derivation", aCheck.name); drvPaths.insert(drvInfo->queryDrvPath()); // FIXME: check meta attributes? } catch (Error & e) { e.addPrefix(fmt("while checking flake check '" ANSI_BOLD "%s" ANSI_NORMAL "':\n", aCheck.name)); throw; } } } } catch (Error & e) { e.addPrefix(fmt("while checking flake output '" ANSI_BOLD "%s" ANSI_NORMAL "':\n", name)); throw; } }); } if (build) { Activity act(*logger, lvlInfo, actUnknown, "running flake checks"); store->buildPaths(drvPaths); } } }; struct CmdFlakeAdd : MixEvalArgs, Command { FlakeUri alias; FlakeUri uri; std::string name() override { return "add"; } std::string description() override { return "upsert flake in user flake registry"; } CmdFlakeAdd() { expectArg("alias", &alias); expectArg("flake-uri", &uri); } void run() override { FlakeRef aliasRef(alias); Path userRegistryPath = getUserRegistryPath(); auto userRegistry = readRegistry(userRegistryPath); userRegistry->entries.erase(aliasRef); userRegistry->entries.insert_or_assign(aliasRef, FlakeRef(uri)); writeRegistry(*userRegistry, userRegistryPath); } }; struct CmdFlakeRemove : virtual Args, MixEvalArgs, Command { FlakeUri alias; std::string name() override { return "remove"; } std::string description() override { return "remove flake from user flake registry"; } CmdFlakeRemove() { expectArg("alias", &alias); } void run() override { Path userRegistryPath = getUserRegistryPath(); auto userRegistry = readRegistry(userRegistryPath); userRegistry->entries.erase(FlakeRef(alias)); writeRegistry(*userRegistry, userRegistryPath); } }; struct CmdFlakePin : virtual Args, EvalCommand { FlakeUri alias; std::string name() override { return "pin"; } std::string description() override { return "pin flake require in user flake registry"; } CmdFlakePin() { expectArg("alias", &alias); } void run(nix::ref<nix::Store> store) override { auto evalState = getEvalState(); Path userRegistryPath = getUserRegistryPath(); FlakeRegistry userRegistry = *readRegistry(userRegistryPath); auto it = userRegistry.entries.find(FlakeRef(alias)); if (it != userRegistry.entries.end()) { it->second = getFlake(*evalState, it->second, true).sourceInfo.resolvedRef; writeRegistry(userRegistry, userRegistryPath); } else { std::shared_ptr<FlakeRegistry> globalReg = evalState->getGlobalFlakeRegistry(); it = globalReg->entries.find(FlakeRef(alias)); if (it != globalReg->entries.end()) { auto newRef = getFlake(*evalState, it->second, true).sourceInfo.resolvedRef; userRegistry.entries.insert_or_assign(alias, newRef); writeRegistry(userRegistry, userRegistryPath); } else throw Error("the flake alias '%s' does not exist in the user or global registry", alias); } } }; struct CmdFlakeInit : virtual Args, Command { std::string name() override { return "init"; } std::string description() override { return "create a skeleton 'flake.nix' file in the current directory"; } void run() override { Path flakeDir = absPath("."); if (!pathExists(flakeDir + "/.git")) throw Error("the directory '%s' is not a Git repository", flakeDir); Path flakePath = flakeDir + "/flake.nix"; if (pathExists(flakePath)) throw Error("file '%s' already exists", flakePath); writeFile(flakePath, #include "flake-template.nix.gen.hh" ); } }; struct CmdFlakeClone : FlakeCommand { Path destDir; std::string name() override { return "clone"; } std::string description() override { return "clone flake repository"; } CmdFlakeClone() { expectArg("dest-dir", &destDir, true); } void run(nix::ref<nix::Store> store) override { auto evalState = getEvalState(); Registries registries = evalState->getFlakeRegistries(); gitCloneFlake(getFlakeRef().to_string(), *evalState, registries, destDir); } }; struct CmdFlake : virtual MultiCommand, virtual Command { CmdFlake() : MultiCommand({make_ref<CmdFlakeList>() , make_ref<CmdFlakeUpdate>() , make_ref<CmdFlakeInfo>() , make_ref<CmdFlakeCheck>() , make_ref<CmdFlakeDeps>() , make_ref<CmdFlakeAdd>() , make_ref<CmdFlakeRemove>() , make_ref<CmdFlakePin>() , make_ref<CmdFlakeInit>() , make_ref<CmdFlakeClone>() }) { } std::string name() override { return "flake"; } std::string description() override { return "manage Nix flakes"; } void run() override { if (!command) throw UsageError("'nix flake' requires a sub-command."); command->run(); } void printHelp(const string & programName, std::ostream & out) override { MultiCommand::printHelp(programName, out); } }; static RegisterCommand r1(make_ref<CmdFlake>()); <commit_msg>nix flake check: Check defaultPackage, devShell and packages<commit_after>#include "command.hh" #include "common-args.hh" #include "shared.hh" #include "progress-bar.hh" #include "eval.hh" #include "eval-inline.hh" #include "primops/flake.hh" #include "get-drvs.hh" #include "store-api.hh" #include <nlohmann/json.hpp> #include <queue> #include <iomanip> using namespace nix; using namespace nix::flake; class FlakeCommand : virtual Args, public EvalCommand, public MixFlakeOptions { std::string flakeUri = "."; public: FlakeCommand() { expectArg("flake-uri", &flakeUri, true); } FlakeRef getFlakeRef() { if (flakeUri.find('/') != std::string::npos || flakeUri == ".") return FlakeRef(flakeUri, true); else return FlakeRef(flakeUri); } Flake getFlake() { auto evalState = getEvalState(); return flake::getFlake(*evalState, getFlakeRef(), useRegistries); } ResolvedFlake resolveFlake() { return flake::resolveFlake(*getEvalState(), getFlakeRef(), getLockFileMode()); } }; struct CmdFlakeList : EvalCommand { std::string name() override { return "list"; } std::string description() override { return "list available Nix flakes"; } void run(nix::ref<nix::Store> store) override { auto registries = getEvalState()->getFlakeRegistries(); stopProgressBar(); for (auto & entry : registries[FLAG_REGISTRY]->entries) std::cout << entry.first.to_string() << " flags " << entry.second.to_string() << "\n"; for (auto & entry : registries[USER_REGISTRY]->entries) std::cout << entry.first.to_string() << " user " << entry.second.to_string() << "\n"; for (auto & entry : registries[GLOBAL_REGISTRY]->entries) std::cout << entry.first.to_string() << " global " << entry.second.to_string() << "\n"; } }; static void printSourceInfo(const SourceInfo & sourceInfo) { std::cout << fmt("URI: %s\n", sourceInfo.resolvedRef.to_string()); if (sourceInfo.resolvedRef.ref) std::cout << fmt("Branch: %s\n",*sourceInfo.resolvedRef.ref); if (sourceInfo.resolvedRef.rev) std::cout << fmt("Revision: %s\n", sourceInfo.resolvedRef.rev->to_string(Base16, false)); if (sourceInfo.revCount) std::cout << fmt("Revisions: %s\n", *sourceInfo.revCount); if (sourceInfo.lastModified) std::cout << fmt("Last modified: %s\n", std::put_time(std::localtime(&*sourceInfo.lastModified), "%F %T")); std::cout << fmt("Path: %s\n", sourceInfo.storePath); } static void sourceInfoToJson(const SourceInfo & sourceInfo, nlohmann::json & j) { j["uri"] = sourceInfo.resolvedRef.to_string(); if (sourceInfo.resolvedRef.ref) j["branch"] = *sourceInfo.resolvedRef.ref; if (sourceInfo.resolvedRef.rev) j["revision"] = sourceInfo.resolvedRef.rev->to_string(Base16, false); if (sourceInfo.revCount) j["revCount"] = *sourceInfo.revCount; if (sourceInfo.lastModified) j["lastModified"] = *sourceInfo.lastModified; j["path"] = sourceInfo.storePath; } static void printFlakeInfo(const Flake & flake) { std::cout << fmt("ID: %s\n", flake.id); std::cout << fmt("Description: %s\n", flake.description); std::cout << fmt("Epoch: %s\n", flake.epoch); printSourceInfo(flake.sourceInfo); } static nlohmann::json flakeToJson(const Flake & flake) { nlohmann::json j; j["id"] = flake.id; j["description"] = flake.description; j["epoch"] = flake.epoch; sourceInfoToJson(flake.sourceInfo, j); return j; } static void printNonFlakeInfo(const NonFlake & nonFlake) { std::cout << fmt("ID: %s\n", nonFlake.alias); printSourceInfo(nonFlake.sourceInfo); } static nlohmann::json nonFlakeToJson(const NonFlake & nonFlake) { nlohmann::json j; j["id"] = nonFlake.alias; sourceInfoToJson(nonFlake.sourceInfo, j); return j; } // FIXME: merge info CmdFlakeInfo? struct CmdFlakeDeps : FlakeCommand { std::string name() override { return "deps"; } std::string description() override { return "list informaton about dependencies"; } void run(nix::ref<nix::Store> store) override { auto evalState = getEvalState(); evalState->addRegistryOverrides(registryOverrides); std::queue<ResolvedFlake> todo; todo.push(resolveFlake()); stopProgressBar(); while (!todo.empty()) { auto resFlake = std::move(todo.front()); todo.pop(); for (auto & nonFlake : resFlake.nonFlakeDeps) printNonFlakeInfo(nonFlake); for (auto & info : resFlake.flakeDeps) { printFlakeInfo(info.second.flake); todo.push(info.second); } } } }; struct CmdFlakeUpdate : FlakeCommand { std::string name() override { return "update"; } std::string description() override { return "update flake lock file"; } void run(nix::ref<nix::Store> store) override { auto evalState = getEvalState(); auto flakeRef = getFlakeRef(); if (std::get_if<FlakeRef::IsPath>(&flakeRef.data)) updateLockFile(*evalState, flakeRef, true); else throw Error("cannot update lockfile of flake '%s'", flakeRef); } }; struct CmdFlakeInfo : FlakeCommand, MixJSON { std::string name() override { return "info"; } std::string description() override { return "list info about a given flake"; } void run(nix::ref<nix::Store> store) override { auto flake = getFlake(); stopProgressBar(); if (json) std::cout << flakeToJson(flake).dump() << std::endl; else printFlakeInfo(flake); } }; static void enumerateProvides(EvalState & state, Value & vFlake, std::function<void(const std::string & name, Value & vProvide)> callback) { state.forceAttrs(vFlake); auto vProvides = (*vFlake.attrs->get(state.symbols.create("provides")))->value; state.forceAttrs(*vProvides); for (auto & attr : *vProvides->attrs) callback(attr.name, *attr.value); } struct CmdFlakeCheck : FlakeCommand, MixJSON { bool build = true; CmdFlakeCheck() { mkFlag() .longName("no-build") .description("do not build checks") .set(&build, false); } std::string name() override { return "check"; } std::string description() override { return "check whether the flake evaluates and run its tests"; } void run(nix::ref<nix::Store> store) override { auto state = getEvalState(); auto flake = resolveFlake(); auto checkDerivation = [&](const std::string & attrPath, Value & v) { try { auto drvInfo = getDerivation(*state, v, false); if (!drvInfo) throw Error("flake attribute '%s' is not a derivation", attrPath); // FIXME: check meta attributes return drvInfo->queryDrvPath(); } catch (Error & e) { e.addPrefix(fmt("while checking flake attribute '" ANSI_BOLD "%s" ANSI_NORMAL "':\n", attrPath)); throw; } }; PathSet drvPaths; { Activity act(*logger, lvlInfo, actUnknown, "evaluating flake"); auto vFlake = state->allocValue(); flake::callFlake(*state, flake, *vFlake); enumerateProvides(*state, *vFlake, [&](const std::string & name, Value & vProvide) { Activity act(*logger, lvlChatty, actUnknown, fmt("checking flake output '%s'", name)); try { state->forceValue(vProvide); if (name == "checks") { state->forceAttrs(vProvide); for (auto & aCheck : *vProvide.attrs) drvPaths.insert(checkDerivation( name + "." + (std::string) aCheck.name, *aCheck.value)); } else if (name == "packages") { state->forceAttrs(vProvide); for (auto & aCheck : *vProvide.attrs) checkDerivation( name + "." + (std::string) aCheck.name, *aCheck.value); } else if (name == "defaultPackage" || name == "devShell") checkDerivation(name, vProvide); } catch (Error & e) { e.addPrefix(fmt("while checking flake output '" ANSI_BOLD "%s" ANSI_NORMAL "':\n", name)); throw; } }); } if (build) { Activity act(*logger, lvlInfo, actUnknown, "running flake checks"); store->buildPaths(drvPaths); } } }; struct CmdFlakeAdd : MixEvalArgs, Command { FlakeUri alias; FlakeUri uri; std::string name() override { return "add"; } std::string description() override { return "upsert flake in user flake registry"; } CmdFlakeAdd() { expectArg("alias", &alias); expectArg("flake-uri", &uri); } void run() override { FlakeRef aliasRef(alias); Path userRegistryPath = getUserRegistryPath(); auto userRegistry = readRegistry(userRegistryPath); userRegistry->entries.erase(aliasRef); userRegistry->entries.insert_or_assign(aliasRef, FlakeRef(uri)); writeRegistry(*userRegistry, userRegistryPath); } }; struct CmdFlakeRemove : virtual Args, MixEvalArgs, Command { FlakeUri alias; std::string name() override { return "remove"; } std::string description() override { return "remove flake from user flake registry"; } CmdFlakeRemove() { expectArg("alias", &alias); } void run() override { Path userRegistryPath = getUserRegistryPath(); auto userRegistry = readRegistry(userRegistryPath); userRegistry->entries.erase(FlakeRef(alias)); writeRegistry(*userRegistry, userRegistryPath); } }; struct CmdFlakePin : virtual Args, EvalCommand { FlakeUri alias; std::string name() override { return "pin"; } std::string description() override { return "pin flake require in user flake registry"; } CmdFlakePin() { expectArg("alias", &alias); } void run(nix::ref<nix::Store> store) override { auto evalState = getEvalState(); Path userRegistryPath = getUserRegistryPath(); FlakeRegistry userRegistry = *readRegistry(userRegistryPath); auto it = userRegistry.entries.find(FlakeRef(alias)); if (it != userRegistry.entries.end()) { it->second = getFlake(*evalState, it->second, true).sourceInfo.resolvedRef; writeRegistry(userRegistry, userRegistryPath); } else { std::shared_ptr<FlakeRegistry> globalReg = evalState->getGlobalFlakeRegistry(); it = globalReg->entries.find(FlakeRef(alias)); if (it != globalReg->entries.end()) { auto newRef = getFlake(*evalState, it->second, true).sourceInfo.resolvedRef; userRegistry.entries.insert_or_assign(alias, newRef); writeRegistry(userRegistry, userRegistryPath); } else throw Error("the flake alias '%s' does not exist in the user or global registry", alias); } } }; struct CmdFlakeInit : virtual Args, Command { std::string name() override { return "init"; } std::string description() override { return "create a skeleton 'flake.nix' file in the current directory"; } void run() override { Path flakeDir = absPath("."); if (!pathExists(flakeDir + "/.git")) throw Error("the directory '%s' is not a Git repository", flakeDir); Path flakePath = flakeDir + "/flake.nix"; if (pathExists(flakePath)) throw Error("file '%s' already exists", flakePath); writeFile(flakePath, #include "flake-template.nix.gen.hh" ); } }; struct CmdFlakeClone : FlakeCommand { Path destDir; std::string name() override { return "clone"; } std::string description() override { return "clone flake repository"; } CmdFlakeClone() { expectArg("dest-dir", &destDir, true); } void run(nix::ref<nix::Store> store) override { auto evalState = getEvalState(); Registries registries = evalState->getFlakeRegistries(); gitCloneFlake(getFlakeRef().to_string(), *evalState, registries, destDir); } }; struct CmdFlake : virtual MultiCommand, virtual Command { CmdFlake() : MultiCommand({make_ref<CmdFlakeList>() , make_ref<CmdFlakeUpdate>() , make_ref<CmdFlakeInfo>() , make_ref<CmdFlakeCheck>() , make_ref<CmdFlakeDeps>() , make_ref<CmdFlakeAdd>() , make_ref<CmdFlakeRemove>() , make_ref<CmdFlakePin>() , make_ref<CmdFlakeInit>() , make_ref<CmdFlakeClone>() }) { } std::string name() override { return "flake"; } std::string description() override { return "manage Nix flakes"; } void run() override { if (!command) throw UsageError("'nix flake' requires a sub-command."); command->run(); } void printHelp(const string & programName, std::ostream & out) override { MultiCommand::printHelp(programName, out); } }; static RegisterCommand r1(make_ref<CmdFlake>()); <|endoftext|>
<commit_before>/************************************************************************* * * 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: svdoimp.hxx,v $ * $Revision: 1.14 $ * * 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_SVDOIMP_HXX #define _SVX_SVDOIMP_HXX #include <memory> #include <vector> #include <cppuhelper/weakref.hxx> #ifndef _MAPMOD_HXX //autogen #include <vcl/mapmod.hxx> #endif #include <svtools/lstner.hxx> #include <vcl/timer.hxx> #include <svx/svdsob.hxx> #include <svx/svdtypes.hxx> // fuer SdrLayerID #include <svx/svdglue.hxx> // Klebepunkte #include <svx/xdash.hxx> #include <svx/xpoly.hxx> //#ifndef _POLY3D_HXX //#include "poly3d.hxx" //#endif #include <svx/xenum.hxx> #include <basegfx/vector/b2dvector.hxx> #include <svx/rectenum.hxx> #include <basegfx/polygon/b2dpolypolygon.hxx> class SdrObject; class XOutputDevice; class XFillAttrSetItem; class XLineAttrSetItem; class SfxItemSet; class Bitmap; /////////////////////////////////////////////////////////////////////////////// // #100127# Bracket filled shapes with a comment, if recording a Mtf class ImpGraphicFill { public: ImpGraphicFill( const SdrObject& rObj, const XOutputDevice& rXOut, const SfxItemSet& rFillItemSet, bool bIsShadow=false ); ImpGraphicFill( const XOutputDevice& rXOut, const SfxItemSet& rSet,basegfx::B2DPolyPolygon& aGeometry, const SfxItemSet& rFillItemSet, bool bIsShadow ); ~ImpGraphicFill(); private: void prepare( const XOutputDevice& rXOut, const SfxItemSet& rSet, basegfx::B2DPolyPolygon& aGeometry, const SfxItemSet& rFillItemSet, bool bIsShadow ); const XOutputDevice& mrXOut; bool mbCommentWritten; }; /////////////////////////////////////////////////////////////////////////////// // #104609# Extracted from XOutputDevice::ImpCalcBmpFillStartValues /** Calc offset and size for bitmap fill This method calculates the size and the offset from the left, top position of a shape in logical coordinates @param rStartOffset The offset from the left, top position of the output rectangle is returned @param rBmpOutputSize The output size of the bitmap is returned herein @param rOutputRect Specifies the output rectangle into which the bitmap should be tiled into @param rOutputMapMode Specifies the logical coordinate system the output rectangle is in @param rFillBitmap Specifies the bitmap to fill with @param rBmpSize The desired destination bitmap size. If null, size is taken from the bitmap @param rBmpPerCent Percentage of bitmap size, relative to the output rectangle @param rBmpOffPerCent Offset for bitmap tiling, in percentage relative to bitmap output size @param bBmpLogSize True when using the preferred bitmap size, False when using the percentage value @param bBmpTile True for tiling. False only paints one instance of the bitmap @param bBmpStretch True if bitmap should be stretched to output rect dimension @param eBmpRectPoint Position of the start point relative to the bitmap */ void ImpCalcBmpFillSizes( Size& rStartOffset, Size& rBmpOutputSize, const Rectangle& rOutputRect, const MapMode& rOutputMapMode, const Bitmap& rFillBitmap, const Size& rBmpSize, const Size& rBmpPerCent, const Size& rBmpOffPerCent, BOOL bBmpLogSize, BOOL bBmpTile, BOOL bBmpStretch, RECT_POINT eBmpRectPoint ); /////////////////////////////////////////////////////////////////////////////// class ImpLineStyleParameterPack { XLineJoint meLineJoint; basegfx::B2DPolyPolygon maStartPolyPolygon; basegfx::B2DPolyPolygon maEndPolyPolygon; sal_Int32 mnLineWidth; sal_Int32 mnStartWidth; sal_Int32 mnEndWidth; ::std::vector<double> maDotDashArray; double mfFullDotDashLen; double mfDegreeStepWidth; // bitfield unsigned mbStartCentered : 1; unsigned mbEndCentered : 1; unsigned mbForceNoArrowsLeft : 1; unsigned mbForceNoArrowsRight : 1; unsigned mbForceHair : 1; // flag for LineStyle. True is XLINE_SOLID, false is XLINE_DASH unsigned mbLineStyleSolid : 1; public: ImpLineStyleParameterPack(const SfxItemSet& rSet, bool bForceHair); ~ImpLineStyleParameterPack(); sal_Int32 GetLineWidth() const { return mnLineWidth; } sal_Int32 GetDisplayLineWidth() const { return mbForceHair ? 0L : mnLineWidth; } bool IsLineStyleSolid() const { return mbLineStyleSolid; } sal_Int32 GetStartWidth() const { return mnStartWidth; } sal_Int32 GetEndWidth() const { return mnEndWidth; } const basegfx::B2DPolyPolygon& GetStartPolyPolygon() const { return maStartPolyPolygon; } const basegfx::B2DPolyPolygon& GetEndPolyPolygon() const { return maEndPolyPolygon; } double GetDegreeStepWidth() const { return mfDegreeStepWidth; } XLineJoint GetLineJoint() const { return meLineJoint; } double GetLinejointMiterMinimumAngle() const { return 15.0; } double GetFullDotDashLen() const { return mfFullDotDashLen; } const ::std::vector< double >& GetDotDash() const { return maDotDashArray; } bool IsStartCentered() const { return mbStartCentered; } bool IsEndCentered() const { return mbEndCentered; } bool IsStartActive() const; bool IsEndActive() const; void ForceNoArrowsLeft(bool bNew) { mbForceNoArrowsLeft = bNew; } void ForceNoArrowsRight(bool bNew) { mbForceNoArrowsRight = bNew; } }; //////////////////////////////////////////////////////////////////////////////////////////////////// class ImpLineGeometryCreator { const ImpLineStyleParameterPack& mrLineAttr; basegfx::B2DPolyPolygon& maAreaPolyPolygon; basegfx::B2DPolyPolygon& maLinePolyPolygon; // bitfield unsigned mbLineDraft : 1; // private support functions // help functions for line geometry creation void ImpCreateLineGeometry( const basegfx::B2DPolygon& rSourcePoly); public: ImpLineGeometryCreator( const ImpLineStyleParameterPack& rAttr, basegfx::B2DPolyPolygon& rPoPo, basegfx::B2DPolyPolygon& rPoLi) : mrLineAttr(rAttr), maAreaPolyPolygon(rPoPo), maLinePolyPolygon(rPoLi), mbLineDraft(false) { } void AddPolygon(const basegfx::B2DPolygon& rPoly) { ImpCreateLineGeometry(rPoly); } const basegfx::B2DPolyPolygon& GetAreaPolyPolygon() const { return maAreaPolyPolygon; } const basegfx::B2DPolyPolygon& GetLinePolyPolygon() const { return maLinePolyPolygon; } }; //////////////////////////////////////////////////////////////////////////////////////////////////// class SdrLineGeometry { basegfx::B2DPolyPolygon maAreaPolyPolygon; basegfx::B2DPolyPolygon maLinePolyPolygon; ImpLineStyleParameterPack maLineAttr; // bitfield unsigned mbForceOnePixel : 1; unsigned mbForceTwoPixel : 1; public: SdrLineGeometry( const basegfx::B2DPolyPolygon& rAreaPolyPolygon, const basegfx::B2DPolyPolygon& rLinePolyPolygon, const ImpLineStyleParameterPack& rLineAttr, bool bForceOnePixel, bool bForceTwoPixel) : maAreaPolyPolygon(rAreaPolyPolygon), maLinePolyPolygon(rLinePolyPolygon), maLineAttr(rLineAttr), mbForceOnePixel(bForceOnePixel), mbForceTwoPixel(bForceTwoPixel) {} const basegfx::B2DPolyPolygon& GetAreaPolyPolygon() { return maAreaPolyPolygon; } const basegfx::B2DPolyPolygon& GetLinePolyPolygon() { return maLinePolyPolygon; } const ImpLineStyleParameterPack& GetLineAttr() { return maLineAttr; } bool DoForceOnePixel() const { return mbForceOnePixel; } bool DoForceTwoPixel() const { return mbForceTwoPixel; } }; #endif // _SVX_SVDOIMP_HXX // eof <commit_msg>INTEGRATION: CWS aw033 (1.8.14); FILE MERGED 2008/07/10 13:00:54 aw 1.8.14.10: #i39532# XOutputDevice removed, PrepareDelete removed 2008/06/24 15:42:24 aw 1.8.14.9: #i39532# corrections 2008/05/14 14:07:17 aw 1.8.14.8: RESYNC: (1.12-1.14); FILE MERGED 2008/03/18 07:15:23 aw 1.8.14.7: #i39532# changes after resync 2008/03/14 13:50:09 cl 1.8.14.6: RESYNC: (1.11-1.12); FILE MERGED 2008/01/22 12:29:28 aw 1.8.14.5: adaptions and 1st stripping 2007/12/03 16:39:55 aw 1.8.14.4: RESYNC: (1.10-1.11); FILE MERGED 2007/08/09 18:31:14 aw 1.8.14.3: RESYNC: (1.9-1.10); FILE MERGED 2006/11/28 19:13:18 aw 1.8.14.2: RESYNC: (1.8-1.9); FILE MERGED 2005/10/28 11:38:17 aw 1.8.14.1: #i39532#<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: svdoimp.hxx,v $ * $Revision: 1.15 $ * * 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_SVDOIMP_HXX #define _SVX_SVDOIMP_HXX #include <vcl/mapmod.hxx> //#include <svtools/lstner.hxx> //#include <vcl/timer.hxx> //#include <svx/svdsob.hxx> //#include <svx/svdtypes.hxx> // fuer SdrLayerID //#include <svx/svdglue.hxx> // Klebepunkte //#include <svx/xdash.hxx> //#include <svx/xpoly.hxx> //#include <svx/xenum.hxx> //#include <basegfx/vector/b2dvector.hxx> #include <svx/rectenum.hxx> //#include <basegfx/polygon/b2dpolypolygon.hxx> class Bitmap; /////////////////////////////////////////////////////////////////////////////// // #104609# Extracted from old XOutDev's ImpCalcBmpFillStartValues /** Calc offset and size for bitmap fill This method calculates the size and the offset from the left, top position of a shape in logical coordinates @param rStartOffset The offset from the left, top position of the output rectangle is returned @param rBmpOutputSize The output size of the bitmap is returned herein @param rOutputRect Specifies the output rectangle into which the bitmap should be tiled into @param rOutputMapMode Specifies the logical coordinate system the output rectangle is in @param rFillBitmap Specifies the bitmap to fill with @param rBmpSize The desired destination bitmap size. If null, size is taken from the bitmap @param rBmpPerCent Percentage of bitmap size, relative to the output rectangle @param rBmpOffPerCent Offset for bitmap tiling, in percentage relative to bitmap output size @param bBmpLogSize True when using the preferred bitmap size, False when using the percentage value @param bBmpTile True for tiling. False only paints one instance of the bitmap @param bBmpStretch True if bitmap should be stretched to output rect dimension @param eBmpRectPoint Position of the start point relative to the bitmap */ void ImpCalcBmpFillSizes( Size& rStartOffset, Size& rBmpOutputSize, const Rectangle& rOutputRect, const MapMode& rOutputMapMode, const Bitmap& rFillBitmap, const Size& rBmpSize, const Size& rBmpPerCent, const Size& rBmpOffPerCent, BOOL bBmpLogSize, BOOL bBmpTile, BOOL bBmpStretch, RECT_POINT eBmpRectPoint ); //////////////////////////////////////////////////////////////////////////////////////////////////// #endif // _SVX_SVDOIMP_HXX // eof <|endoftext|>
<commit_before>#include <stdlib.h> #include <stdio.h> #include <omp.h> #include <tbb/parallel_sort.h> #include "body.h" #include "util.h" using namespace tbb; struct comparator_t { comparator_t(midlvl_t const* const mids, const size_t n) : mids(mids), n(n) {} private: midlvl_t const* const mids; const size_t n; public: int operator()(size_t a, size_t b) const { return mids[a] < mids[b]; } }; midlvl_t toMid(point_t p, lvl_t level) { mid_t m = 0; mid_t pointMask = 1; mid_t midMask = 1; size_t numBits = MORTON_BITS / DIM; mid_t max = ((mid_t) 1) << numBits; mid_t x = (mid_t) (p.x * max); mid_t y = (mid_t) (p.y * max); for (size_t i = 0; i < numBits; i++) { if (y & pointMask) m |= midMask; midMask = midMask << 1; if (x & pointMask) m |= midMask; midMask = midMask << 1; pointMask = pointMask << 1; } return midlvl(m, level); } void sortByMid(point_t const* const points, midlvl_t const* const mids, const size_t n, size_t* idxs) { #pragma omp parallel for for (size_t i = 0; i < n; i++) idxs[i] = i; parallel_sort(idxs, idxs + n, comparator_t(mids, n)); } void partition(midlvl_t const* const mids, size_t const* const idxs, const size_t n, midlvl_t* partitions) { #pragma omp parallel for for (size_t i = 0; i < n; i++) partitions[i] = mids[idxs[i]]; } <commit_msg>fixed toMid bug that flipped x/y interleaving<commit_after>#include <stdlib.h> #include <stdio.h> #include <omp.h> #include <tbb/parallel_sort.h> #include "body.h" #include "util.h" using namespace tbb; struct comparator_t { comparator_t(midlvl_t const* const mids, const size_t n) : mids(mids), n(n) {} private: midlvl_t const* const mids; const size_t n; public: int operator()(size_t a, size_t b) const { return mids[a] < mids[b]; } }; midlvl_t toMid(point_t p, lvl_t level) { mid_t m = 0; mid_t pointMask = 1; mid_t midMask = 1; size_t numBits = MORTON_BITS / DIM; mid_t max = ((mid_t) 1) << numBits; mid_t x = (mid_t) (p.x * max); mid_t y = (mid_t) (p.y * max); for (size_t i = 0; i < numBits; i++) { if (x & pointMask) m |= midMask; midMask = midMask << 1; if (y & pointMask) m |= midMask; midMask = midMask << 1; pointMask = pointMask << 1; } return midlvl(m, level); } void sortByMid(point_t const* const points, midlvl_t const* const mids, const size_t n, size_t* idxs) { #pragma omp parallel for for (size_t i = 0; i < n; i++) idxs[i] = i; parallel_sort(idxs, idxs + n, comparator_t(mids, n)); } void partition(midlvl_t const* const mids, size_t const* const idxs, const size_t n, midlvl_t* partitions) { #pragma omp parallel for for (size_t i = 0; i < n; i++) partitions[i] = mids[idxs[i]]; } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2008, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software 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 <boost/python.hpp> #include "IECoreTruelight/TruelightColorTransformOp.h" #include "IECore/CompoundObject.h" #include "IECore/bindings/IntrusivePtrPatch.h" #include "IECore/bindings/RunTimeTypedBinding.h" using namespace boost; using namespace boost::python; namespace IECoreTruelight { void bindTruelightColorTransformOp() { typedef class_< TruelightColorTransformOp, TruelightColorTransformOpPtr, boost::noncopyable, bases<IECore::ColorTransformOp> > TruelightColorTransformOpPyClass; TruelightColorTransformOpPyClass( "TruelightColorTransformOp" ) .def( "commands", &TruelightColorTransformOp::commands ) .IE_COREPYTHON_DEFRUNTIMETYPEDSTATICMETHODS(TruelightColorTransformOp) ; INTRUSIVE_PTR_PATCH( TruelightColorTransformOp, TruelightColorTransformOpPyClass ); implicitly_convertible<TruelightColorTransformOpPtr, IECore::ColorTransformOpPtr>(); } } // namespace IECoreTruelight <commit_msg>Fixed IECoreTruelight for new binding style.<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2008-2009, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software 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 "boost/python.hpp" #include "IECoreTruelight/TruelightColorTransformOp.h" #include "IECore/CompoundObject.h" #include "IECore/bindings/RunTimeTypedBinding.h" using namespace boost; using namespace boost::python; namespace IECoreTruelight { void bindTruelightColorTransformOp() { IECore::RunTimeTypedClass<TruelightColorTransformOp>() .def( init<>() ) .def( "commands", &TruelightColorTransformOp::commands ) ; } } // namespace IECoreTruelight <|endoftext|>