<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' || _key == GLFW_KEY_ESCAPE){
        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 RPI macro on esc to close the app.<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() {
    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());
        }
    }

#ifdef PLATFORM_RPI
    _key = getchar();
    if (_key == 27) {
        bPlay = false;
    }
#else
    if ( _key == 'q' || _key == 'Q' || _key == GLFW_KEY_ESCAPE){
        bPlay = false;
    }
#endif
}

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>#include <cstdio>
#include <SDL2/SDL.h>
#include "draw.hpp"
#include "font.hpp"

const char * game_name = "Game Of Life On Surface";
const wchar_t tmp_str[] = L"FPS: %.2f; theta: %.2f; phi: %.2f";
int screen_width = 640;
int screen_height = 640;
float R = 200;
int px, py;
vec3s delta = { 0, 0, 0 };
vec3s view_direction = {1, M_PI / 4, 0 };
field f(16, 32);
bool quit_flag = false;
bool button_set = false;
SDL_Window * window = NULL;
SDL_Renderer * render = NULL;
SDL_Event event;
font_table_t * ft = NULL;

void game_send_error( int code ) {
    printf( "[error]: %s\n", SDL_GetError() );
    exit( code );
}

float get_fps( void ) {
    static float NewCount = 0.0f, LastCount = 0.0f, FpsRate = 0.0f;
    static int FrameCount = 0;

    NewCount = (float) SDL_GetTicks();
    if ( ( NewCount - LastCount ) > 1000.0f ) {
        FpsRate = ( FrameCount * 1000.0f ) / ( NewCount - LastCount );
        LastCount = NewCount;
        FrameCount = 0;
    }
    FrameCount++;
    return FpsRate;
}

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;
                case SDLK_UP:
                    view_direction.theta -= 0.01f;
                    break;
                case SDLK_DOWN:
                    view_direction.theta += 0.01f;
                    break;
                case SDLK_LEFT:
                    view_direction.phi -= 0.01f;
                    break;
                case SDLK_RIGHT:
                    view_direction.phi += 0.01f;
                    break;
                default:
                    break;
            }
        case SDL_MOUSEMOTION:
            if ( button_set ) {
                delta.phi = ( event->button.x - px ) / 100.0f;
                delta.theta = ( event->button.y - py ) / 100.0f;
                px = event->button.x;
                py = event->button.y;
                view_direction -= delta;
            }
            break;
        case SDL_MOUSEBUTTONDOWN:
            switch ( event->button.button ) {
                case SDL_BUTTON_LEFT:
                    if ( button_set == false ) {
                        px = event->button.x;
                        py = event->button.y;
                    }
                    break;
                default:
                    break;
            }
            button_set = true;
            break;
        case SDL_MOUSEBUTTONUP:
            button_set = false;
            break;
        default:
            break;
    }
}

void game_loop( void ) {
    // insert code
}

void game_render( void ) {
    const std::size_t BUFFER_SIZE = 128;
    wchar_t buffer[BUFFER_SIZE];

    SDL_RenderClear( render );
    set_coloru( COLOR_WHITE );
    draw_sphere( view_direction, {screen_width / 2, screen_height / 2}, R, f );
    swprintf( buffer, BUFFER_SIZE, tmp_str, get_fps(), view_direction.theta, view_direction.phi );
    font_draw( render, ft, buffer, 5, screen_height - 16 );
    set_coloru( COLOR_BLACK );
    SDL_RenderPresent( render );
}

void game_destroy( void ) {
    font_destroy( ft );
    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 );
    font_load( render, &ft, "./data/font.cfg" );

    // тестовое заполнение
    for ( size_t i = 0; i < 100; i++ ) {
        f.f[rand()%16][rand()%32] = true;
    }
}

int main( int argc, char * argv[] ) {
    game_init();
    while ( quit_flag == false ) {
        game_event( &event );
        game_loop();
        game_render();
    }
    game_destroy();
    return EXIT_SUCCESS;
}
<commit_msg>[add] help menu, random_fill, game_loop<commit_after>#include <cstdio>
#include <ctime>
#include <SDL2/SDL.h>
#include "draw.hpp"
#include "font.hpp"
#include "logics.hpp"

const char * game_name = "Game Of Life On Surface";
const wchar_t tmp_str[] = L"(%s) FPS: %.2f; theta: %.2f; phi: %.2f; delay %d";
const wchar_t * game_status[] = {
    (const wchar_t *) "pause",
    (const wchar_t *) "play"
};
const wchar_t help_info[] =
    L"help menu:\n\n"
    L"   F1 -- this menu\n"
    L"  ESC -- quit\n"
    L"SPACE -- play/pause\n"
    L"    F -- random fill\n"
    L"    > -- speed up\n"
    L"    < -- speed down\n"
    L" []{} -- rotate";
int game_counter = 0, MAX_COUNT = 5;
int screen_width = 640;
int screen_height = 640;
const int border_size = 24;
const int help_box_width = 200;
const int help_box_height = 80;
float R = 200;
int px, py;
vec3s delta = { 0, 0, 0 };
vec3s view_direction = {1, M_PI / 4, 0 };
field f(16, 32);
bool quit_flag = false;
bool button_set = false;
bool game_step = false;
bool help_flag = false;
SDL_Window * window = NULL;
SDL_Renderer * render = NULL;
SDL_Event event;
font_table_t * ft = NULL;

void game_send_error( int code ) {
    printf( "[error]: %s\n", SDL_GetError() );
    exit( code );
}

float get_fps( void ) {
    static float NewCount = 0.0f, LastCount = 0.0f, FpsRate = 0.0f;
    static int FrameCount = 0;

    NewCount = (float) SDL_GetTicks();
    if ( ( NewCount - LastCount ) > 1000.0f ) {
        FpsRate = ( FrameCount * 1000.0f ) / ( NewCount - LastCount );
        LastCount = NewCount;
        FrameCount = 0;
    }
    FrameCount++;
    return FpsRate;
}

void random_fill( void ) {
    for ( size_t i = 0; i < 128; i++ ) {
        f.f[rand()%16][rand()%32] = true;
    }
}

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;
                case SDLK_SPACE:
                    game_step = !game_step;
                    break;
                case SDLK_F1:
                    help_flag = !help_flag;
                    event->key.keysym.sym = 0;
                    break;
                case SDLK_UP:
                    view_direction.theta -= 0.01f;
                    break;
                case SDLK_DOWN:
                    view_direction.theta += 0.01f;
                    break;
                case SDLK_LEFT:
                    view_direction.phi -= 0.01f;
                    break;
                case SDLK_RIGHT:
                    view_direction.phi += 0.01f;
                    break;
                case SDLK_PERIOD:
                    if ( MAX_COUNT > 0 ) {
                        MAX_COUNT -= 1;
                    }
                    break;
                case SDLK_COMMA:
                    MAX_COUNT += 1;
                    break;
                case SDLK_f:
                    random_fill();
                    break;
                default:
                    break;
            }
            break;
        case SDL_MOUSEMOTION:
            if ( button_set ) {
                delta.phi = ( event->button.x - px ) / 100.0f;
                delta.theta = ( event->button.y - py ) / 100.0f;
                px = event->button.x;
                py = event->button.y;
                view_direction -= delta;
            }
            break;
        case SDL_MOUSEBUTTONDOWN:
            switch ( event->button.button ) {
                case SDL_BUTTON_LEFT:
                    if ( button_set == false ) {
                        px = event->button.x;
                        py = event->button.y;
                    }
                    break;
                default:
                    break;
            }
            button_set = true;
            break;
        case SDL_MOUSEBUTTONUP:
            button_set = false;
            break;
        default:
            break;
    }
}

void game_loop( void ) {
    if ( game_step && game_counter >= MAX_COUNT ) {
        nextStep( f );
        game_counter = 0;
    } else {
        game_counter++;
    }
}

void game_render( void ) {
    const std::size_t BUFFER_SIZE = 128;
    wchar_t buffer[BUFFER_SIZE];

    SDL_RenderClear( render );
    set_coloru( COLOR_WHITE );
    draw_sphere( view_direction, {screen_width / 2, screen_height / 2}, R, f );
    swprintf( buffer, BUFFER_SIZE, tmp_str, game_status[int(game_step)], get_fps(),
              view_direction.theta, view_direction.phi, MAX_COUNT );
    font_draw( render, ft, buffer, 5, screen_height - 16 );
    if ( help_flag ) {
        set_color4u( 0x00, 0x00, 0xff, 0x96 );
        draw_rectangle_param( ( screen_width - help_box_width ) / 2,
                              ( screen_height - help_box_height ) / 2,
                              help_box_width, help_box_height, true );
        font_draw( render, ft, help_info, ( screen_width - help_box_width ) / 2,
                   ( screen_height - help_box_height ) / 2 + 4 );
    }
    set_coloru( COLOR_BLACK );
    SDL_RenderPresent( render );
}

void game_destroy( void ) {
    font_destroy( ft );
    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 );
    font_load( render, &ft, "./data/font.cfg" );
    srand( time( NULL ) );
    random_fill();
}

int main( int argc, char * argv[] ) {
    game_init();
    while ( quit_flag == false ) {
        game_event( &event );
        game_loop();
        game_render();
    }
    game_destroy();
    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "lexer/lexer.hpp"
#include <iostream>
#include "utils/debug.hpp"
#include "parser/parser.hpp"
using namespace lambda;
int main(int argc, char const *argv[])
{
        Parser par;

        // i'll add value-blocks later. so '{...}' would be <expression> too.

        using namespace Syntax;

        // <if> ::= 'if' <expression> '{' <expression> '}' 'else' '{' <expression> '}'
        par.defExpr(L"if-then-else",
                defSyntax(
                        (L"if"), expr,
                                (L"{"), expr, (L"}"),
                        (L"else"),
                                (L"{"), expr, (L"}")
                ),
                [](Parser::ParseInfo & info ){
                        return new Expression();
                }
        );
        // <when> ::= 'when' <expression> '{' <statement> '}'
        par.defStmt(L"when",
                defSyntax(
                        (L"when"), expr,
                                (L"{"), stmt, (L"}")
                ),
                [](Parser::ParseInfo & info ){
                        std::wcerr << L"when alloc\n";
                        return new Statement();
                }
        );
        // like <when>, but condition must be false.
        // <unless> ::= 'when' <expression> '{' <statement> '}'
        par.defStmt(L"unless",
                defSyntax(
                        (L"unless"), expr,
                                (L"{"), stmt, (L"}")
                ),
                [](Parser::ParseInfo & info ){
                        return new Statement();
                }
        );

        // new syntax :)
        // <let> ::= 'let' <identifer> '=' <expression>
        auto let = par.defStmt(L"let",
                defSyntax(L"let",id,L"=",expr),
                [](Parser::ParseInfo&){
                        std::wcerr << L"let alloc\n";
                        return new Statement();
                }
        );
        // now looks like BNF
        // <def> ::= 'def' <identifer> '=' <expression>
        par.defStmt(L"def",
                defSyntax(L"def",id,L"=",expr),
                [](Parser::ParseInfo&){
                        return new Statement();
                }
        );
        // <block> ::= '{' <statement>* '}'
        par.defStmt(L"block",ParseVal::Token(L"{"), [](Parser& par,Lexer& lex){
                auto end = lex.TryRecognize(L"}");
                while(lex.nextTok().id!=end){
                        par.expectStatement();
                }
                std::wcerr << L"block alloc\n";
                return new Statement();
        });
        // <for> ::= 'for' <let> ('let' <identifer> '=' <expression>) 'to' <expression> 'do' <statement>
        par.defStmt(L"for", defSyntax(L"for",let,L"to",expr,L"do",stmt),
                [](Parser::ParseInfo&){std::wcerr<<L"for alloc\n";return new Statement();});
        par.addData(L"for let i = 1 to 10 do { when a b let c = 10 }", L"test");
        par.Parse();
        par.showRules();
        par.showError();
        return 0;
}<commit_msg>Update main.cpp<commit_after>#include "lexer/lexer.hpp"
#include <iostream>
#include "utils/debug.hpp"
#include "parser/parser.hpp"
using namespace lambda;
int main(int argc, char const *argv[])
{
        Parser par;

        // i'll add value-blocks later. so '{...}' would be <expression> too.

        using namespace Syntax;

        // <block> ::= '{' <statement>* '}'
        auto block = par.defStmt(L"block",
                defSyntax(
                        (L"{"),infstmts, (L"}")
                ),
                [](Parser::ParseInfo&){std::wcerr << L"block alloc\n"; return new Statement();}
        );
        // ParsedInfo.size == Syntax.size. so, ParsedInfo[x].pv == Rule[x], if Rule[x] <: <expression> or <statement> then ParsedInfo[x].expr or ParsedInfo[x].stmt != nullptr. And if you want to extract data from ParsedInfo for your AST node - feel free.
        // <if> ::= 'if' <expression> '{' <expression> '}' 'else' '{' <expression> '}'
        par.defExpr(L"if-then-else",
                defSyntax(
                        (L"if"), expr,
                                (L"{"), expr, (L"}"),
                        (L"else"),
                                (L"{"), expr, (L"}")
                ),
                [](Parser::ParseInfo & info ){
                        return new Expression();
                }
        );
        // <when> ::= 'when' <expression> '{' <statement> '}'
        par.defStmt(L"when",
                defSyntax(
                        (L"when"), expr,block
                ),
                [](Parser::ParseInfo & info ){
                        std::wcerr << L"when alloc\n";
                        return new Statement();
                }
        );
        // like <when>, but condition must be false.
        // <unless> ::= 'when' <expression> '{' <statement> '}'
        par.defStmt(L"unless",
                defSyntax(
                        (L"unless"), expr,block
                ),
                [](Parser::ParseInfo & info ){
                        std::wcerr << L"unless alloc\n";
                        return new Statement();
                }
        );

        // new syntax :)
        // <let> ::= 'let' <identifer> '=' <expression>
        auto let = par.defStmt(L"let",
                defSyntax(
                        (L"let"),id,(L"="),expr
                ),
                [](Parser::ParseInfo&){
                        std::wcerr << L"let alloc\n";
                        return new Statement();
                }
        );

        // <def> ::= 'def' <identifer> '=' <expression>
        par.defStmt(L"def",
                defSyntax(
                        (L"def"),id,(L"="),expr
                ),
                [](Parser::ParseInfo&){
                        return new Statement();
                }
        );

        // <for> ::= 'for' <let> ('let' <identifer> '=' <expression>) 'to' <expression> 'do' <statement>
        par.defStmt(L"for",
                defSyntax(
                        (L"for"),let,(L"to"),expr,(L"do"),block
                ),
                [](Parser::ParseInfo&){std::wcerr<<L"for alloc\n";return new Statement();});

        par.addData(L"for let i = 1 to 10 do { when a { unless a {let c = 10.1} } let c = 10 }", L"test");
        par.Parse();

        par.showRules();
        par.showError();
        return 0;
}
<|endoftext|>


<commit_before>#include <cv.h>
#include <highgui.h>
#include <iostream>
#include <gflags/gflags.h>
#include <cstdlib>
#include <list>

using namespace std;
using namespace cv;

DEFINE_bool(display, true, "Display video in window.");
DEFINE_bool(quiet, false, "Suppress terminal output.");
DEFINE_string(save, "", "Save output to file.");
DEFINE_string(axis, "y", "Axis of rotation.");
DEFINE_bool(live, false, "Use live feed.");

enum axis_enum {
    AXIS_X,
    AXIS_Y,
    AXIS_T
};

typedef struct options_struct {
    enum axis_enum axis;
    Size size;
    int frame_count;
    VideoCapture *video_src;
    VideoWriter *video_dst;
    bool live;
} options_type;

int video_file_filter(options_type *o, char *window_name);
int video_live_filter(options_type *o, char *window_name);

options_type * create_options(int *argc, char ***argv) {
    google::ParseCommandLineFlags(argc, argv, true);
    options_type *o = (options_type *) calloc(1, sizeof(options_type));

    if (FLAGS_live && *argc == 1) {
        o->live = true;
    } else if (*argc != 2) {
        o->live = false;
        cout << "usage: " << *argv[0] << " input-video" << endl;
        free(o);
        return NULL;
    }

    // open input video
    if (o->live) {
        o->video_src = new VideoCapture(0);
    } else {
        string input_file = (*argv)[(*argc) - 1];
        o->video_src = new VideoCapture(input_file);
    }
    if(!o->video_src->isOpened()) return NULL;

    // get axis
    if (FLAGS_axis == "x") {
        o->axis = AXIS_X;
    } else if (FLAGS_axis == "y") {
        o->axis = AXIS_Y;
    } else if (FLAGS_axis == "t") {
        o->axis = AXIS_T;
    } else {
        free(o);
        return NULL;
    }

    // get size of output video
    int width = o->video_src->get(CV_CAP_PROP_FRAME_WIDTH);
    int height = o->video_src->get(CV_CAP_PROP_FRAME_HEIGHT);
    int frame_count = o->video_src->get(CV_CAP_PROP_FRAME_COUNT);
    if (o->live) {
        o->size = Size(width, height);
        o->frame_count = FLAGS_axis == "x" ? height : width;
    } else if (FLAGS_axis == "x") {
        o->size = Size(width, frame_count);
        o->frame_count = height;
    } else if (FLAGS_axis == "y") {
        o->size = Size(frame_count, height);
        o->frame_count = width;
    } else {
        free(o);
        return NULL;
    }

    // get output video
    if (!FLAGS_save.empty()) {
        o->video_dst = new VideoWriter;
        int ex = CV_FOURCC('I', 'Y', 'U', 'V');
        o->video_dst->open(
                FLAGS_save, ex,
                o->video_src->get(CV_CAP_PROP_FPS),
                o->size);
    }

    return o;

}

int main(int argc, char **argv) {

    options_type *o = create_options(&argc, &argv);
    if (o == NULL)
        return -1;

    if (FLAGS_display) {
        namedWindow(argv[0],CV_WINDOW_NORMAL);
        setWindowProperty(argv[0], CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN);
    }

    if (o->live)
        video_live_filter(o, argv[0]);
    else
        video_file_filter(o, argv[0]);

    delete o->video_src;
    delete o->video_dst;
    free(o);

    return 0;
}

int video_live_filter(options_type *o, char *window_name) {
    Mat frame_in;
    *(o->video_src) >> frame_in;
    Mat frame_out(o->size, frame_in.type());

    list<Mat> frame_list;
    for (int i = 0; i < o->frame_count; i++) {
        cout << "Frame " << i+1 << " of " << o->frame_count << endl;
        if (waitKey(1) == '')
            return 0;
        *(o->video_src) >> frame_in;
        frame_list.push_back(frame_in.clone());
    }

    int j = 0;
    int d = 1;
    for (;;) {
        int i = 0;
        for (list<Mat>::iterator it = frame_list.begin(); it != frame_list.end(); it++) {
            switch (o->axis) {
                case AXIS_X:
                    it->row(j).copyTo(frame_out.row(i));
                    break;
                case AXIS_Y:
                    it->col(j).copyTo(frame_out.col(i));
                    break;
                default:
                    cout << "UNIMPLEMENTED" << endl;
                    return -1;
            }
            i++;
        }
        if (j == o->frame_count - 1) {
            d = -1;
        } else if (j == 0) {
            d = 1;
        }
        j += d;

        imshow(window_name, frame_out);
        if (waitKey(1) == '')
            return 0;

        *(o->video_src) >> frame_in;
        frame_list.push_back(frame_in.clone());
        frame_list.pop_front();
    }

}

int video_file_filter(options_type *o, char *window_name) {
    Mat frame_in;
    *(o->video_src) >> frame_in;
    Mat frame_out(o->size, frame_in.type());

    int frame_count_src = o->video_src->get(CV_CAP_PROP_FRAME_COUNT);
    for (int j = 0; j < o->frame_count; j++) {

        // Output status to console
        if (!FLAGS_quiet)
            cout << "Frame " << j+1 << " of " << o->frame_count << "." << endl;

        // Create a new frame.
        o->video_src->set(CV_CAP_PROP_POS_FRAMES, 0);
        for (int i = 0; i < frame_count_src; i++) {
            *(o->video_src) >> frame_in;
            switch (o->axis) {
                case AXIS_X:
                    frame_in.row(j).copyTo(frame_out.row(i));
                    break;
                case AXIS_Y:
                    frame_in.col(j).copyTo(frame_out.col(i));
                    break;
                default:
                    cout << "UNIMPLEMENTED" << endl;
                    return -1;
            }
        }

        // Display window
        if (FLAGS_display) {
            imshow(window_name, frame_out);
            if (waitKey(1) == '')
                return 0;
        }

        // Save frame to file
        if (!FLAGS_save.empty())
            o->video_dst->write(frame_out);

    }
}
<commit_msg>Force ignore of control-c to keep webcam from getting messed up<commit_after>#include <signal.h>
#include <cv.h>
#include <highgui.h>
#include <iostream>
#include <gflags/gflags.h>
#include <cstdlib>
#include <list>

using namespace std;
using namespace cv;

DEFINE_bool(display, true, "Display video in window.");
DEFINE_bool(quiet, false, "Suppress terminal output.");
DEFINE_string(save, "", "Save output to file.");
DEFINE_string(axis, "y", "Axis of rotation.");
DEFINE_bool(live, false, "Use live feed.");

enum axis_enum {
    AXIS_X,
    AXIS_Y,
    AXIS_T
};

typedef struct options_struct {
    enum axis_enum axis;
    Size size;
    int frame_count;
    VideoCapture *video_src;
    VideoWriter *video_dst;
    bool live;
} options_type;

int video_file_filter(options_type *o, char *window_name);
int video_live_filter(options_type *o, char *window_name);

options_type * create_options(int *argc, char ***argv) {
    google::ParseCommandLineFlags(argc, argv, true);
    options_type *o = (options_type *) calloc(1, sizeof(options_type));

    if (FLAGS_live && *argc == 1) {
        o->live = true;
    } else if (*argc != 2) {
        o->live = false;
        cout << "usage: " << *argv[0] << " input-video" << endl;
        free(o);
        return NULL;
    }

    // open input video
    if (o->live) {
        o->video_src = new VideoCapture(0);
    } else {
        string input_file = (*argv)[(*argc) - 1];
        o->video_src = new VideoCapture(input_file);
    }
    if(!o->video_src->isOpened()) return NULL;

    // get axis
    if (FLAGS_axis == "x") {
        o->axis = AXIS_X;
    } else if (FLAGS_axis == "y") {
        o->axis = AXIS_Y;
    } else if (FLAGS_axis == "t") {
        o->axis = AXIS_T;
    } else {
        free(o);
        return NULL;
    }

    // get size of output video
    int width = o->video_src->get(CV_CAP_PROP_FRAME_WIDTH);
    int height = o->video_src->get(CV_CAP_PROP_FRAME_HEIGHT);
    int frame_count = o->video_src->get(CV_CAP_PROP_FRAME_COUNT);
    if (o->live) {
        o->size = Size(width, height);
        o->frame_count = FLAGS_axis == "x" ? height : width;
    } else if (FLAGS_axis == "x") {
        o->size = Size(width, frame_count);
        o->frame_count = height;
    } else if (FLAGS_axis == "y") {
        o->size = Size(frame_count, height);
        o->frame_count = width;
    } else {
        free(o);
        return NULL;
    }

    // get output video
    if (!FLAGS_save.empty()) {
        o->video_dst = new VideoWriter;
        int ex = CV_FOURCC('I', 'Y', 'U', 'V');
        o->video_dst->open(
                FLAGS_save, ex,
                o->video_src->get(CV_CAP_PROP_FPS),
                o->size);
    }

    return o;

}

int main(int argc, char **argv) {
   signal(SIGINT, SIG_IGN);

    options_type *o = create_options(&argc, &argv);
    if (o == NULL)
        return -1;

    if (FLAGS_display) {
        namedWindow(argv[0],CV_WINDOW_NORMAL);
        setWindowProperty(argv[0], CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN);
    }

    if (o->live)
        video_live_filter(o, argv[0]);
    else
        video_file_filter(o, argv[0]);

    delete o->video_src;
    delete o->video_dst;
    free(o);

    return 0;
}

int video_live_filter(options_type *o, char *window_name) {
    Mat frame_in;
    *(o->video_src) >> frame_in;
    Mat frame_out(o->size, frame_in.type());

    list<Mat> frame_list;
    for (int i = 0; i < o->frame_count; i++) {
        cout << "Frame " << i+1 << " of " << o->frame_count << endl;
        if (waitKey(1) == '')
            return 0;
        *(o->video_src) >> frame_in;
        frame_list.push_back(frame_in.clone());
    }

    int j = 0;
    int d = 1;
    for (;;) {
        int i = 0;
        for (list<Mat>::iterator it = frame_list.begin(); it != frame_list.end(); it++) {
            switch (o->axis) {
                case AXIS_X:
                    it->row(j).copyTo(frame_out.row(i));
                    break;
                case AXIS_Y:
                    it->col(j).copyTo(frame_out.col(i));
                    break;
                default:
                    cout << "UNIMPLEMENTED" << endl;
                    return -1;
            }
            i++;
        }
        if (j == o->frame_count - 1) {
            d = -1;
        } else if (j == 0) {
            d = 1;
        }
        j += d;

        imshow(window_name, frame_out);
        if (waitKey(1) == '')
            return 0;

        *(o->video_src) >> frame_in;
        frame_list.push_back(frame_in.clone());
        frame_list.pop_front();
    }

}

int video_file_filter(options_type *o, char *window_name) {
    Mat frame_in;
    *(o->video_src) >> frame_in;
    Mat frame_out(o->size, frame_in.type());

    int frame_count_src = o->video_src->get(CV_CAP_PROP_FRAME_COUNT);
    for (int j = 0; j < o->frame_count; j++) {

        // Output status to console
        if (!FLAGS_quiet)
            cout << "Frame " << j+1 << " of " << o->frame_count << "." << endl;

        // Create a new frame.
        o->video_src->set(CV_CAP_PROP_POS_FRAMES, 0);
        for (int i = 0; i < frame_count_src; i++) {
            *(o->video_src) >> frame_in;
            switch (o->axis) {
                case AXIS_X:
                    frame_in.row(j).copyTo(frame_out.row(i));
                    break;
                case AXIS_Y:
                    frame_in.col(j).copyTo(frame_out.col(i));
                    break;
                default:
                    cout << "UNIMPLEMENTED" << endl;
                    return -1;
            }
        }

        // Display window
        if (FLAGS_display) {
            imshow(window_name, frame_out);
            if (waitKey(1) == '')
                return 0;
        }

        // Save frame to file
        if (!FLAGS_save.empty())
            o->video_dst->write(frame_out);

    }
}
<|endoftext|>


<commit_before>/**
 * @file edge.cpp
 * @brief Simple test for OpenCV
 * @author Denis Deryugin <deryugin.denis@gmail.com>
 * @version
 * @date 03.06.2019
 */

#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <stdio.h>

#include <drivers/video/fb.h>

using namespace cv;
using namespace std;

static void help() {
	printf("\nThis sample demonstrates Canny edge detection\n"
			"Call:\n"
			"	./edge [threshold]\n\n");
}

static const char* keys = {
	"{help h||}{@repeat |1     | number}"
};

int main(int argc, const char** argv) {
	int edgeThresh = 2;
	Mat image, gray, edge, cedge;

	struct fb_info *fbi = fb_lookup(0);

	CommandLineParser parser(argc, argv, keys);
	if (parser.has("help"))  {
		help();
		return 0;
	}

	edgeThresh = parser.get<int>(0);
	string filename = "fruits.png";
	image = imread(filename, 1);
	if(image.empty()) {
		printf("Cannot read image file: %s\n", filename.c_str());
		help();
		return -1;
	}

	cedge.create(image.size(), image.type());
	cvtColor(image, gray, COLOR_BGR2GRAY);

	blur(gray, edge, Size(3,3));
	Canny(edge, edge, edgeThresh, edgeThresh*3, 3);
	cedge = Scalar::all(0);

	image.copyTo(cedge, edge);

	printf("Framebuffer: %dx%d %dbpp\n", fbi->var.xres, fbi->var.yres, fbi->var.bits_per_pixel);
	printf("Image: %dx%d; Threshold=%d\n", cedge.cols, cedge.rows, edgeThresh);

	for (int i = 0; i < cedge.cols; i++) {
		for (int j = 0; j < cedge.rows; j++) {
			Vec3b intensity = cedge.at<Vec3b>(j, i);
			unsigned rgb888	=
				0xFF000000 |
				intensity.val[0] |
				((intensity.val[1]) << 8) |
				((intensity.val[2]) << 16);

			((uint32_t *) fbi->screen_base)[fbi->var.xres * j + i] = rgb888;
		}
	}

	return 0;
}
<commit_msg>edges: Pass image as a parameter<commit_after>/**
 * @file edge.cpp
 * @brief Simple test for OpenCV
 * @author Denis Deryugin <deryugin.denis@gmail.com>
 * @version
 * @date 03.06.2019
 */

#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <stdio.h>

#include <drivers/video/fb.h>

using namespace cv;
using namespace std;

static void help(void) {
	printf("\nThis sample demonstrates Canny edge detection\n"
			"Call:\n"
			"	./edge [image [threshold]] \n\n");
}

static const char* keys = {
	"{help h||}"
	"{@image        | \"fruits.png\" | source image   }"
	"{@repeat |1     | number}"
};

int main(int argc, const char** argv) {
	int edgeThresh = 2;
	Mat image, gray, edge, cedge;

	struct fb_info *fbi = fb_lookup(0);

	CommandLineParser parser(argc, argv, keys);
	if (parser.has("help"))  {
		help();
		return 0;
	}

	edgeThresh = parser.get<int>(1);
	string filename = parser.get<String>("@image");
	image = imread(filename, 1);
	if(image.empty()) {
		printf("Cannot read image file: %s\n", filename.c_str());
		help();
		return -1;
	}

	cedge.create(image.size(), image.type());
	cvtColor(image, gray, COLOR_BGR2GRAY);

	blur(gray, edge, Size(3,3));
	Canny(edge, edge, edgeThresh, edgeThresh*3, 3);
	cedge = Scalar::all(0);

	image.copyTo(cedge, edge);

	printf("Framebuffer: %dx%d %dbpp\n", fbi->var.xres, fbi->var.yres, fbi->var.bits_per_pixel);
	printf("Image: %dx%d; Threshold=%d\n", cedge.cols, cedge.rows, edgeThresh);

	for (int i = 0; i < cedge.cols; i++) {
		for (int j = 0; j < cedge.rows; j++) {
			Vec3b intensity = cedge.at<Vec3b>(j, i);
			unsigned rgb888	=
				0xFF000000 |
				intensity.val[0] |
				((intensity.val[1]) << 8) |
				((intensity.val[2]) << 16);

			((uint32_t *) fbi->screen_base)[fbi->var.xres * j + i] = rgb888;
		}
	}

	return 0;
}
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <tuple>

// template <class... Types> class tuple;

// template <class... Types>
//   class tuple_size<tuple<Types...>>
//     : public integral_constant<size_t, sizeof...(Types)> { };

// UNSUPPORTED: c++98, c++03

#include <tuple>
#include <array>
#include <type_traits>

struct Dummy1 {};
struct Dummy2 {};
struct Dummy3 {};

template <>
class std::tuple_size<Dummy1> {
public:
  static size_t value;
};

template <>
class std::tuple_size<Dummy2> {
public:
  static void value() {}
};

template <>
class std::tuple_size<Dummy3> {};

int main()
{
  // Test that tuple_size<const T> is not incomplete when tuple_size<T>::value
  // is well-formed but not a constant expression.
  {
    // expected-error@__tuple:* 1 {{is not a constant expression}}
    (void)std::tuple_size<const Dummy1>::value; // expected-note {{here}}
  }
  // Test that tuple_size<const T> is not incomplete when tuple_size<T>::value
  // is well-formed but not convertible to size_t.
  {
    // expected-error@__tuple:* 1 {{value of type 'void ()' is not implicitly convertible to 'unsigned long'}}
    (void)std::tuple_size<const Dummy2>::value; // expected-note {{here}}
  }
  // Test that tuple_size<const T> generates an error when tuple_size<T> is
  // complete but ::value isn't a constant expression convertible to size_t.
  {
    // expected-error@__tuple:* 1 {{no member named 'value'}}
    (void)std::tuple_size<const Dummy3>::value; // expected-note {{here}}
  }
}
<commit_msg>Fix verify test on 32 bit systems<commit_after>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <tuple>

// template <class... Types> class tuple;

// template <class... Types>
//   class tuple_size<tuple<Types...>>
//     : public integral_constant<size_t, sizeof...(Types)> { };

// UNSUPPORTED: c++98, c++03

#include <tuple>
#include <array>
#include <type_traits>

struct Dummy1 {};
struct Dummy2 {};
struct Dummy3 {};

template <>
class std::tuple_size<Dummy1> {
public:
  static size_t value;
};

template <>
class std::tuple_size<Dummy2> {
public:
  static void value() {}
};

template <>
class std::tuple_size<Dummy3> {};

int main()
{
  // Test that tuple_size<const T> is not incomplete when tuple_size<T>::value
  // is well-formed but not a constant expression.
  {
    // expected-error@__tuple:* 1 {{is not a constant expression}}
    (void)std::tuple_size<const Dummy1>::value; // expected-note {{here}}
  }
  // Test that tuple_size<const T> is not incomplete when tuple_size<T>::value
  // is well-formed but not convertible to size_t.
  {
    // expected-error@__tuple:* 1 {{value of type 'void ()' is not implicitly convertible to}}
    (void)std::tuple_size<const Dummy2>::value; // expected-note {{here}}
  }
  // Test that tuple_size<const T> generates an error when tuple_size<T> is
  // complete but ::value isn't a constant expression convertible to size_t.
  {
    // expected-error@__tuple:* 1 {{no member named 'value'}}
    (void)std::tuple_size<const Dummy3>::value; // expected-note {{here}}
  }
}
<|endoftext|>


<commit_before>/**
 * @file edge.cpp
 * @brief Simple test for OpenCV
 * @author Denis Deryugin <deryugin.denis@gmail.com>
 * @version
 * @date 03.06.2019
 */

#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <stdio.h>

#include <drivers/video/fb.h>

using namespace cv;
using namespace std;

static void help(void) {
	printf("\nThis sample demonstrates Canny edge detection\n"
			"Call:\n"
			"	./edge [image [threshold]] \n\n");
}

static const char* keys = {
	"{help h||}"
	"{@image        | \"fruits.png\" | source image   }"
	"{@repeat |1     | number}"
};

int main(int argc, const char** argv) {
	int edgeThresh = 2;
	Mat image, gray, edge, cedge;

	struct fb_info *fbi = fb_lookup(0);

	CommandLineParser parser(argc, argv, keys);
	if (parser.has("help"))  {
		help();
		return 0;
	}

	edgeThresh = parser.get<int>(1);
	string filename = parser.get<String>("@image");
	image = imread(filename, 1);
	if(image.empty()) {
		printf("Cannot read image file: %s\n", filename.c_str());
		help();
		return -1;
	}

	cedge.create(image.size(), image.type());
	cvtColor(image, gray, COLOR_BGR2GRAY);

	blur(gray, edge, Size(3,3));
	Canny(edge, edge, edgeThresh, edgeThresh*3, 3);
	cedge = Scalar::all(0);

	image.copyTo(cedge, edge);

	printf("Framebuffer: %dx%d %dbpp\n", fbi->var.xres, fbi->var.yres, fbi->var.bits_per_pixel);
	printf("Image: %dx%d; Threshold=%d\n", cedge.cols, cedge.rows, edgeThresh);

	for (int x = 0; x < cedge.cols; x++) {
		for (int y = 0; y < cedge.rows; y++) {
			Vec3b intensity = cedge.at<Vec3b>(y, x);
			unsigned rgb888	=
				0xFF000000 |
				intensity.val[0] |
				((intensity.val[1]) << 8) |
				((intensity.val[2]) << 16);

			((uint32_t *) fbi->screen_base)[fbi->var.xres * y + x] = rgb888;
		}
	}

	return 0;
}
<commit_msg>reordered iteration over Y/X dimensions of image for better cache usage<commit_after>/**
 * @file edge.cpp
 * @brief Simple test for OpenCV
 * @author Denis Deryugin <deryugin.denis@gmail.com>
 * @version
 * @date 03.06.2019
 */

#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <stdio.h>

#include <drivers/video/fb.h>

using namespace cv;
using namespace std;

static void help(void) {
	printf("\nThis sample demonstrates Canny edge detection\n"
			"Call:\n"
			"	./edge [image [threshold]] \n\n");
}

static const char* keys = {
	"{help h||}"
	"{@image        | \"fruits.png\" | source image   }"
	"{@repeat |1     | number}"
};

int main(int argc, const char** argv) {
	int edgeThresh = 2;
	Mat image, gray, edge, cedge;

	struct fb_info *fbi = fb_lookup(0);

	CommandLineParser parser(argc, argv, keys);
	if (parser.has("help"))  {
		help();
		return 0;
	}

	edgeThresh = parser.get<int>(1);
	string filename = parser.get<String>("@image");
	image = imread(filename, 1);
	if(image.empty()) {
		printf("Cannot read image file: %s\n", filename.c_str());
		help();
		return -1;
	}

	cedge.create(image.size(), image.type());
	cvtColor(image, gray, COLOR_BGR2GRAY);

	blur(gray, edge, Size(3,3));
	Canny(edge, edge, edgeThresh, edgeThresh*3, 3);
	cedge = Scalar::all(0);

	image.copyTo(cedge, edge);

	printf("Framebuffer: %dx%d %dbpp\n", fbi->var.xres, fbi->var.yres, fbi->var.bits_per_pixel);
	printf("Image: %dx%d; Threshold=%d\n", cedge.cols, cedge.rows, edgeThresh);

	for (int y = 0; y < cedge.rows; y++) {
		for (int x = 0; x < cedge.cols; x++) {
			Vec3b intensity = cedge.at<Vec3b>(y, x);
			unsigned rgb888	=
				0xFF000000 |
				intensity.val[0] |
				((intensity.val[1]) << 8) |
				((intensity.val[2]) << 16);

			((uint32_t *) fbi->screen_base)[fbi->var.xres * y + x] = rgb888;
		}
	}

	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <cstdio>
#include <stdexcept>

#include "parse.h"

#include "API.hpp"
#include "CatalogManager.hpp"
#include "IndexManager.hpp"
#include "RecordManager.hpp"
#include "BufferManager.hpp"

using namespace std;
void printList (const Entries& rlist, const TableDefinition& tdef);

int main() {

    char dmnb[] =
        "       _   __  __   _  _    _      \n"
        "    __| | |  \\/  | | \\| |  | |__   \n"
        "   / _` | | |\\/| | | .` |  | '_ \\  \n"
        "   \\__,_| |_|__|_| |_|\\_|  |_.__/  \n"
        "  _|\"\"\"\"\"|_|\"\"\"\"\"|_|\"\"\"\"\"|_|\"\"\"\"\"| \n"
        "  \"`-0-0-'\"`-0-0-'\"`-0-0-'\"`-0-0-' \n"
        ;

    char sepr[] =
        " ---------------------------------\n"
        ;

    char fail[] =
        "    ___ _____ ____\n"
        "   / _ \\_   _|_  /\n"
        "  | (_) || |  / / \n"
        "   \\___/ |_| /___|\n"
        "   init failed :( \n"
        ;

    char byee[] =
        " BBBByyyyeeee ~~~~\n"
        ;

    char welcm[] =
        " Welcome to DminiB system(exclaimation),\n"
        " enter command below\n"
        ;

    cout << dmnb << sepr;

    try {
        BufferManager bufferManager;
        CatalogManager catlogManager;
        RecordManager recordManager(bufferManager);
        IndexManager indexManager(bufferManager);

        API api(catlogManager,
                recordManager,
                indexManager);

        cout << welcm << endl;

        string str, temp;
        do {

            str.clear(); temp.clear();
            if (!cin) { cout << endl; break; } // check if ^D
            cout << "dMNb> ";

            do {

                getline(cin, temp);
                str += " " + temp;

            } while (temp.find(';') == string::npos && cin);

            if (str == " exit;" || str == " exit") break;
            if (str == " " ) break;

            PlanList& plist = parse(str);

            // call api according to plist
            for (PlanList::iterator plan = plist.begin();
                    plan != plist.end(); ++plan) {

                std::string tname = plan->tname;
                // seperate function call accoring to acti
                Action acti = plan->acti;
                WrapperList &wlist = plan->wlist;

                try {
                    switch(acti) {
                        case DELV: if ( !wlist.size() ) {
                                       cout << "del item num: " << api.remove(tname) << endl;
                                   }
                                   else {
                                       cout << "del item num: " << api.remove(tname, wlist) << endl;
                                   }
                                   break;

                        case SELV: if ( !wlist.size() ) {
                                       const Entries rlist = api.select(tname);
                                       printList(rlist, catlogManager.getTableDef(tname));
                                   }
                                   else {
                                       const Entries rlist = api.select(tname, wlist);
                                       printList(rlist, catlogManager.getTableDef(tname));
                                   }
                                   break;
                        case CTBL: api.createTable(tname, wlist); break;
                        case DTBL: api.dropTable(tname); break;
                        case CIDX: api.createIndex(tname, wlist.begin()->name,
                                           wlist.begin()->strv); break;
                        case INSV:
                                   //cout << "[main] api.insertEntry calling..." << endl;
                                   cout.flush();

                                   api.insertEntry(tname, wlist); break;
                        case DIDX: api.dropIndex(tname); break;
                        default: cerr << "unhandled action\n"; break;
                    }
                }
                catch (exception const& e) {
                    cerr << "err: " << e.what() << endl;
                }
                //cout << str << endl;
                /*
                   for (WrapperList::const_iterator j = plan->wlist.begin();
                   j != plan->wlist.end(); j++)
                   j->debug();
                   */
            }

        } while (1);

    }
    catch (exception const& e) {
        cerr << "err: " << e.what() << endl;
        return(-1);
    }
    catch (...) {

        cout << fail << endl;
        return(-1);

    }

    cout << byee;
    return 0;
}

void printList (const Entries& rlist, const TableDefinition& tdef) {

    if ( rlist.size() ) {
        for (TableDefinition::const_iterator i = tdef.begin();
                i != tdef.end(); i++) {
            //if ( i->type == utls::CHAR) cout.width(i->intv);
            //else cout.width(10);
            cout << i->name << "    ";
        }

        cout << endl;
    }

    for (Entries::const_iterator i = rlist.begin();
            i != rlist.end(); i++) {
        for (Entry::const_iterator j = i->begin();
                j != i->end(); j++) {
            j->debug();
        }
        cout << endl;
    }
    cout << rlist.size() << " rows selected" << endl;
}
<commit_msg>mod: ....<commit_after>#include <iostream>
#include <string>
#include <cstdio>
#include <stdexcept>

#include "parse.h"

#include "API.hpp"
#include "CatalogManager.hpp"
#include "IndexManager.hpp"
#include "RecordManager.hpp"
#include "BufferManager.hpp"

using namespace std;
void printList (const Entries& rlist, const TableDefinition& tdef);

int main() {

    char dmnb[] =
        "       _   __  __   _  _    _      \n"
        "    __| | |  \\/  | | \\| |  | |__   \n"
        "   / _` | | |\\/| | | .` |  | '_ \\  \n"
        "   \\__,_| |_|__|_| |_|\\_|  |_.__/  \n"
        "  _|\"\"\"\"\"|_|\"\"\"\"\"|_|\"\"\"\"\"|_|\"\"\"\"\"| \n"
        "  \"`-0-0-'\"`-0-0-'\"`-0-0-'\"`-0-0-' \n"
        ;

    char sepr[] =
        " ---------------------------------\n"
        ;

    char fail[] =
        "    ___ _____ ____\n"
        "   / _ \\_   _|_  /\n"
        "  | (_) || |  / / \n"
        "   \\___/ |_| /___|\n"
        "   init failed :( \n"
        ;

    char byee[] =
        " BBBByyyyeeee ~~~~\n"
        ;

    char welcm[] =
        " Welcome to DminiB system(exclaimation),\n"
        " enter command below\n"
        ;

    cout << dmnb << sepr;

    try {
        BufferManager bufferManager;
        CatalogManager catlogManager;
        RecordManager recordManager(bufferManager);
        IndexManager indexManager(bufferManager);

        API api(catlogManager,
                recordManager,
                indexManager);

        cout << welcm << endl;

        string str, temp;
        do {

            str.clear(); temp.clear();
            if (!cin) { cout << endl; break; } // check if ^D
            cout << "dMNb> ";

            do {

                getline(cin, temp);
                str += " " + temp;

            } while (temp.find(';') == string::npos && cin);

            if (str == " exit;" || str == " exit") break;
            if (str == " " ) break;

            if ( str.substr(0, 4) == "exec" ) {
                str.erase(0, 5); str.erase(str.length() -1, 1);
                cout << str; break;
            }

            PlanList& plist = parse(str);

            // call api according to plist
            for (PlanList::iterator plan = plist.begin();
                    plan != plist.end(); ++plan) {

                std::string tname = plan->tname;
                // seperate function call accoring to acti
                Action acti = plan->acti;
                WrapperList &wlist = plan->wlist;

                try {
                    switch(acti) {
                        case DELV: if ( !wlist.size() ) {
                                       cout << "del item num: " << api.remove(tname) << endl;
                                   }
                                   else {
                                       cout << "del item num: " << api.remove(tname, wlist) << endl;
                                   }
                                   break;

                        case SELV: if ( !wlist.size() ) {
                                       const Entries rlist = api.select(tname);
                                       printList(rlist, catlogManager.getTableDef(tname));
                                   }
                                   else {
                                       const Entries rlist = api.select(tname, wlist);
                                       printList(rlist, catlogManager.getTableDef(tname));
                                   }
                                   break;
                        case CTBL: api.createTable(tname, wlist); break;
                        case DTBL: api.dropTable(tname); break;
                        case CIDX: api.createIndex(tname, wlist.begin()->name,
                                           wlist.begin()->strv); break;
                        case INSV:
                                   //cout << "[main] api.insertEntry calling..." << endl;
                                   cout.flush();

                                   api.insertEntry(tname, wlist); break;
                        case DIDX: api.dropIndex(tname); break;
                        default: cerr << "unhandled action\n"; break;
                    }
                }
                catch (exception const& e) {
                    cerr << "err: " << e.what() << endl;
                }
                //cout << str << endl;
                /*
                   for (WrapperList::const_iterator j = plan->wlist.begin();
                   j != plan->wlist.end(); j++)
                   j->debug();
                   */
            }

        } while (1);

    }
    catch (exception const& e) {
        cerr << "err: " << e.what() << endl;
        return(-1);
    }
    catch (...) {

        cout << fail << endl;
        return(-1);

    }

    cout << byee;
    return 0;
}

void printList (const Entries& rlist, const TableDefinition& tdef) {

    if ( rlist.size() ) {
        for (TableDefinition::const_iterator i = tdef.begin();
                i != tdef.end(); i++) {
            //if ( i->type == utls::CHAR) cout.width(i->intv);
            //else cout.width(10);
            cout << i->name << "    ";
        }

        cout << endl;
    }

    for (Entries::const_iterator i = rlist.begin();
            i != rlist.end(); i++) {
        for (Entry::const_iterator j = i->begin();
                j != i->end(); j++) {
            j->debug();
        }
        cout << endl;
    }
    cout << rlist.size() << " rows selected" << endl;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string.h>
#include <lux/index.h>
#include <lux/types.h>

static void
usage()
{
    std::cout << "usage:" << std::endl;
    std::cout << "  luxcmd init db" << std::endl;
    std::cout << "  luxcmd put db id [attr=value]...." << std::endl;
}

static bool
open_db(Lux::Engine engine, const char* path, Lux::db_flags_t oflags=Lux::DB_RDWR)
{
    if (!engine.open(path, oflags)) {
        std::cerr << "opening engine failed - " << path << std::endl;
        return false;
    }
    return true;
}

static int
init(Lux::Engine engine, const char* db, int argc, char* argv[])
{
    return open_db(engine, db, Lux::DB_CREAT) ? 0 : 1;
}

static int
put(Lux::Engine engine, const char* db, int argc, char* argv[])
{
    if (!open_db(engine, db)) {
        return 1;
    }

    Lux::Indexer indexer(engine);
    Lux::Document doc(argv[0]);
    int i;
    for (i = 1; i < argc; i++) {
        char* pair = strdupa(argv[i]);
        char* pc = strchr(pair, '=');
        const char* val;
        if (pc != NULL) {
            *pc = '\0';
            val = pc + 1;
        }
        else {
            val = &pair[strlen(pair)];
        }
        const char* key = pair;
        doc.add(Lux::Field::create(key, val));
    }
    indexer.add(doc);

    return 0;
}

int
main(int argc, char* argv[])
{
    if (argc < 3) {
        usage();
        return 1;
    }

    const char* db = argv[2];
    Lux::Config::Document config;
    if (!Lux::DocumentConfigParser::parse(db, config)) {
        std::cerr << "parse failed - " << db << std::endl;
        return 1;
    }
    Lux::Engine engine(config);

    const char* cmd = argv[1];
    if (strcmp(cmd, "init") == 0) {
        return init(engine, db, argc - 4, argv + 4);
    }
    if (strcmp(cmd, "put") == 0) {
        return put(engine, db, argc - 4, argv + 4);
    }

    return 0;
}

// vim: tabstop=4 shiftwidth=4 expandtab softtabstop=4
<commit_msg>Implemented search command.<commit_after>#include <iostream>
#include <string.h>
#include <lux/index.h>
#include <lux/search.h>
#include <lux/types.h>

static void
usage()
{
    std::cout << "usage:" << std::endl;
    std::cout << "  luxcmd init db" << std::endl;
    std::cout << "  luxcmd put db id [attr=value]...." << std::endl;
    std::cout << "  luxcmd search db phrase" << std::endl;
}

static bool
open_db(Lux::Engine engine, const char* path, Lux::db_flags_t oflags=Lux::DB_RDWR)
{
    if (!engine.open(path, oflags)) {
        std::cerr << "opening engine failed - " << path << std::endl;
        return false;
    }
    return true;
}

static int
init(Lux::Engine engine, const char* db, int argc, char* argv[])
{
    return open_db(engine, db, Lux::DB_CREAT) ? 0 : 1;
}

static void
print_line()
{
    std::cout << "--------------------------------" << std::endl;
}

static int
search(Lux::Engine engine, int argc, char* argv[])
{
    Lux::SortCondition scond(Lux::SORT_SCORE, Lux::DESC);
    Lux::Paging paging(100);
    Lux::Condition cond(scond, paging);

    Lux::Searcher searcher(engine);
    Lux::ResultSet rs = searcher.search(argv[0], cond);
    std::cout << "total hits: " << rs.get_total_num() << std::endl;
    rs.init_iter();
    while (rs.has_next()) {
        Lux::Result r = rs.get_next();
        print_line();
        std::cout << "[id] " << r.get_id() << std::endl;
    }

    return 0;
}

static int
put(Lux::Engine engine, int argc, char* argv[])
{
    Lux::Indexer indexer(engine);
    Lux::Document doc(argv[0]);
    int i;
    for (i = 1; i < argc; i++) {
        char* pair = strdupa(argv[i]);
        char* pc = strchr(pair, '=');
        const char* val;
        if (pc != NULL) {
            *pc = '\0';
            val = pc + 1;
        }
        else {
            val = &pair[strlen(pair)];
        }
        const char* key = pair;
        doc.add(Lux::Field::create(key, val));
    }
    indexer.add(doc);

    return 0;
}

int
main(int argc, char* argv[])
{
    if (argc < 3) {
        usage();
        return 1;
    }

    const char* db = argv[2];
    Lux::Config::Document config;
    if (!Lux::DocumentConfigParser::parse(db, config)) {
        std::cerr << "parse failed - " << db << std::endl;
        return 1;
    }
    Lux::Engine engine(config);

    const char* cmd = argv[1];
    if (strcmp(cmd, "init") == 0) {
        return init(engine, db, argc - 3, argv + 3);
    }

    if (!open_db(engine, db)) {
        return 1;
    }
    if (strcmp(cmd, "put") == 0) {
        return put(engine, argc - 3, argv + 3);
    }
    if (strcmp(cmd, "search") == 0) {
        return search(engine, argc - 3, argv + 3);
    }

    return 0;
}

// vim: tabstop=4 shiftwidth=4 expandtab softtabstop=4
<|endoftext|>