<commit_before>//For colored output
#define ANSI_COLOR_RED     "\x1b[31m"
#define ANSI_COLOR_GREEN   "\x1b[32m"
#define ANSI_COLOR_YELLOW  "\x1b[33m"
#define ANSI_COLOR_BLUE    "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN    "\x1b[36m"
#define ANSI_COLOR_RESET   "\x1b[0m"

#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include "Program.h"
using namespace std;

const GLuint SCREEN_WIDTH = 500;
const GLuint SCREEN_HEIGHT = 500;

GLfloat timer;
bool show3d;
Program *program;
GLFWwindow* gWindow = NULL;

static void Render() {
    //White Background
    glClearColor(1, 1, 1, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    //Update Timer
    timer+=0.01;
    GLuint timerLoc = glGetUniformLocation(program->getID(), "timer");
    glUniform1f(timerLoc, timer);

    if(show3d){
      //Draw Cube
      glDrawArrays(GL_TRIANGLES,0, 36);
    }else{
      //Draw Triangle
      glDrawArrays(GL_TRIANGLES, 0, 3);
    }

    glfwSwapBuffers(gWindow);
}

//Compile Link and Create Shader Program
void createShaders(){
    Shader vertex("./shaders/vert.glsl",GL_VERTEX_SHADER);
    Shader fragment("./shaders/frag.glsl",GL_FRAGMENT_SHADER);

    program = new Program();

    program->attachShader(vertex);
    program->attachShader(fragment);

    program->link();
    program->use();

    if(Logger::show){
        program->printActiveAttribs();
        program->printActiveUniforms();
    }
}

//Generate VBO and VAO
void createAttributes(float  positionData[],int sizePos, float  colorData[], int sizeColor){

    //Generate vertex buffer objects
    GLuint vboHandles[2];
    glGenBuffers(2,vboHandles);

    //Hold onto an vbo id
    GLuint positionBufferHandle = vboHandles[0];
    GLuint colorBufferHandle = vboHandles[1];

    //Position Binding - bind data to vbo
    glBindBuffer(GL_ARRAY_BUFFER,positionBufferHandle);
    glBufferData(GL_ARRAY_BUFFER, sizePos, positionData, GL_STATIC_DRAW);

    //Color binding - bind data to vbo
    glBindBuffer(GL_ARRAY_BUFFER,colorBufferHandle);
    glBufferData(GL_ARRAY_BUFFER, sizeColor, colorData, GL_STATIC_DRAW);

    //generate a single vao
    GLuint vao;
    glGenVertexArrays(1,&vao);
    glBindVertexArray(vao);

    //Link attribute name with location or you can do it in the shader
    GLuint positionLocation = 0;
    GLuint colorLocation = 1;
    glBindAttribLocation(program->getID(), positionLocation,"VertexPosition");
    glBindAttribLocation(program->getID(), colorLocation,"VertexColor");

    //Make location an array type
    glEnableVertexAttribArray(positionLocation);
    glEnableVertexAttribArray(colorLocation);

    //bind vao to vbo
    glBindBuffer(GL_ARRAY_BUFFER, positionBufferHandle);
    //specify datatype and info of vao
    glVertexAttribPointer(positionLocation, 3, GL_FLOAT, GL_FALSE, 0, NULL);

    //do the same for color buffer
    glBindBuffer(GL_ARRAY_BUFFER, colorBufferHandle);
    glVertexAttribPointer(colorLocation, 3, GL_FLOAT, GL_FALSE, 0, NULL);
}

void triangleSetup(){
    //Triangle Vertices Coordinates (Model Coordinates)
    float positionData[] ={
        -0.8f,-0.8f,0.0f,
        0.8f,-0.8f,0.0f,
        0.0f,0.8f,0.0f
    };
    //Triangle Vertice Colors
    float colorData[]={
        1.0f,0.0f,0.0f,
        0.0f,0.0f,1.0f,
        0.0f,1.0f,0.0f
    };

    createAttributes(positionData, sizeof(positionData), colorData, sizeof(colorData));
}

void cubeSetup(){
    //Cube Vertices Coordinates (Model Coordinates)
    float positionData[] ={

        -1.0f,-1.0f,-1.0f,
        -1.0f,-1.0f, 1.0f,
        -1.0f, 1.0f, 1.0f,

        1.0f, 1.0f,-1.0f,
        -1.0f,-1.0f,-1.0f,
        -1.0f, 1.0f,-1.0f,

        1.0f,-1.0f, 1.0f,
        -1.0f,-1.0f,-1.0f,
        1.0f,-1.0f,-1.0f,

        1.0f, 1.0f,-1.0f,
        1.0f,-1.0f,-1.0f,
        -1.0f,-1.0f,-1.0f,

        -1.0f,-1.0f,-1.0f,
        -1.0f, 1.0f, 1.0f,
        -1.0f, 1.0f,-1.0f,

        1.0f,-1.0f, 1.0f,
        -1.0f,-1.0f, 1.0f,
        -1.0f,-1.0f,-1.0f,

        -1.0f, 1.0f, 1.0f,
        -1.0f,-1.0f, 1.0f,
        1.0f,-1.0f, 1.0f,

        1.0f, 1.0f, 1.0f,
        1.0f,-1.0f,-1.0f,
        1.0f, 1.0f,-1.0f,

        1.0f,-1.0f,-1.0f,
        1.0f, 1.0f, 1.0f,
        1.0f,-1.0f, 1.0f,

        1.0f, 1.0f, 1.0f,
        1.0f, 1.0f,-1.0f,
        -1.0f, 1.0f,-1.0f,

        1.0f, 1.0f, 1.0f,
        -1.0f, 1.0f,-1.0f,
        -1.0f, 1.0f, 1.0f,

        1.0f, 1.0f, 1.0f,
        -1.0f, 1.0f, 1.0f,
        1.0f,-1.0f, 1.0f
    };
    //Cube vertice colors, one face has 2 triangles with different colors to show that it is made up with triangles
    float colorData[]={

        0.583f,  0.771f,  0.014f,
        0.583f,  0.771f,  0.014f,
        0.583f,  0.771f,  0.014f,

        1.000f,  0.000f,  0.000f,
        1.000f,  0.000f,  0.000f,
        1.000f,  0.000f,  0.000f,

        0.583f,  0.771f,  0.014f,
        0.583f,  0.771f,  0.014f,
        0.583f,  0.771f,  0.014f,

        0.800f,  0.000f,  0.000f,
        0.800f,  0.000f,  0.000f,
        0.800f,  0.000f,  0.000f,

        0.583f,  0.771f,  0.014f,
        0.583f,  0.771f,  0.014f,
        0.583f,  0.771f,  0.014f,

        0.583f,  0.771f,  0.014f,
        0.583f,  0.771f,  0.014f,
        0.583f,  0.771f,  0.014f,

        1.000f,  0.000f,  0.000f,
        1.000f,  0.000f,  0.000f,
        1.000f,  0.000f,  0.000f,

        0.000f,  1.000f,  0.000f,
        0.000f,  1.000f,  0.000f,
        0.000f,  1.000f,  0.000f,

        0.000f,  1.000f,  0.000f,
        0.000f,  1.000f,  0.000f,
        0.000f,  1.000f,  0.000f,

        0.000f,  0.000f,  1.000f,
        0.000f,  0.000f,  1.000f,
        0.000f,  0.000f,  1.000f,

        0.000f,  0.000f,  1.000f,
        0.000f,  0.000f,  1.000f,
        0.000f,  0.000f,  1.000f,

        1.000f,  0.000f,  0.000f,
        1.000f,  0.000f,  0.000f,
        1.000f,  0.000f,  0.000f,
    };
    createAttributes(positionData, sizeof(positionData), colorData, sizeof(colorData));

}

void printInfo(){
    char buff[255];

    //Print OpenGl Info
    Logger::log(ANSI_COLOR_CYAN "*****************************************************************************" ANSI_COLOR_RESET);
    snprintf(buff, sizeof(buff), "OpenGL version: %s", glGetString(GL_VERSION));
    Logger::log(buff);

    snprintf(buff, sizeof(buff), "GLSL version: %s", glGetString(GL_SHADING_LANGUAGE_VERSION));
    Logger::log(buff);

    snprintf(buff, sizeof(buff), "Vendor: %s", glGetString(GL_VENDOR));
    Logger::log(buff);

    snprintf(buff, sizeof(buff), "Renderer: %s", glGetString(GL_RENDERER));
    Logger::log(buff);

    //Print Window Position Info
    Logger::log(ANSI_COLOR_CYAN"--------------------------------------------------------------------------------" ANSI_COLOR_RESET);
    int xpos, ypos;
    glfwGetWindowPos(gWindow, &xpos, &ypos);
    snprintf(buff, sizeof(buff), "Window Position\n x: %d, y: %d",xpos,ypos);
    Logger::log(buff);
    Logger::log("Set Window Postion in the makefile otherwise it defaults to center of screen.");
    Logger::log(ANSI_COLOR_CYAN "-----------------------------------------------------------------------------" ANSI_COLOR_RESET);
    Logger::log(ANSI_COLOR_CYAN "********************************************************************************\n" ANSI_COLOR_RESET);

}
void OnError(int errorCode, const char* msg) {
    throw std::runtime_error(msg);
}
void key_press(GLFWwindow* window, int key, int scancode, int action, int mods){

    //Recompile Shaders on C key press
    if (glfwGetKey(window, GLFW_KEY_C) == GLFW_PRESS){
        Logger::log(ANSI_COLOR_MAGENTA "================================================================================");
        Logger::log("                              Recompiling Shaders                               ");
        Logger::log("================================================================================");
        createShaders();
        Logger::log("================================================================================");
        Logger::log("                              Compilation Complete                              ");
        Logger::log("================================================================================ " ANSI_COLOR_RESET);
    }
    //Use the Cube
    if(glfwGetKey(window, GLFW_KEY_2) == GLFW_PRESS){
        show3d=true;
        Logger::log(ANSI_COLOR_MAGENTA "================================================================================");
        Logger::log("                              Using Cube                                        ");
        Logger::log("================================================================================" ANSI_COLOR_RESET);
        cubeSetup();
    }
    //Use the Triangle
    if(glfwGetKey(window, GLFW_KEY_1) == GLFW_PRESS){
        show3d=false;
        triangleSetup();
        Logger::log(ANSI_COLOR_MAGENTA "================================================================================");
        Logger::log("                              Using Triangle                  ");
        Logger::log("================================================================================" ANSI_COLOR_RESET);
    }
}
int main(int argc, char **argv)
{
    Logger::log(ANSI_COLOR_CYAN "################################################################################");
    Logger::log("                              Starting GLFW and OpenGL           ");
    Logger::log("################################################################################" ANSI_COLOR_RESET);
    //Logger::show =false;
    show3d=false;
    glfwSetErrorCallback(OnError);
    if(!glfwInit())
        throw std::runtime_error("glfwInit failed");

    // open a window with GLFW
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    gWindow = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "OpenGL Tutorial", NULL, NULL);

    //Set Window Position or center of screen if not specified
    if(argc >2 && atoi(argv[1]) != -1 && atoi(argv[2]) != -1){
        glfwSetWindowPos(gWindow,atoi(argv[1]),atoi(argv[2]));
    }
    //Disallow Resizing
    glfwWindowHint(GLFW_RESIZABLE,GL_FALSE);

    if(!gWindow)
        throw std::runtime_error("glfwCreateWindow failed. Can your hardware handle OpenGL 4.1?");

    // GLFW settings
    glfwMakeContextCurrent(gWindow);

    // initialise GLEW with core
    glewExperimental = GL_TRUE;
    if(glewInit() != GLEW_OK)
        throw std::runtime_error("glewInit failed");

    // print out some environment info
    printInfo();

    createShaders();

    triangleSetup();

    //Link after Compilation and VBO and VAO are created
    program->link();
    program->use();

    if(Logger::show){
        program->printActiveAttribs();
        program->printActiveUniforms();
    }

    //Hide things that are behind others
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);

    //start timer
    timer = 0.0;

    //Create a screen size uniform
    GLuint location = glGetUniformLocation(program->getID(),"screen");
    glUniform2f(location,SCREEN_WIDTH, SCREEN_HEIGHT);

    //Handle Key events
    glfwSetKeyCallback(gWindow, key_press);
    //Run Loop
    while(!glfwWindowShouldClose(gWindow)){
        glfwPollEvents();
        Render();
    }
    glfwTerminate();

}

<commit_msg>fix location bug<commit_after>//For colored output
#define ANSI_COLOR_RED     "\x1b[31m"
#define ANSI_COLOR_GREEN   "\x1b[32m"
#define ANSI_COLOR_YELLOW  "\x1b[33m"
#define ANSI_COLOR_BLUE    "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN    "\x1b[36m"
#define ANSI_COLOR_RESET   "\x1b[0m"

#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include "Program.h"
using namespace std;

const GLuint SCREEN_WIDTH = 500;
const GLuint SCREEN_HEIGHT = 500;

GLfloat timer;
bool show3d;
Program *program;
GLFWwindow* gWindow = NULL;

static void Render() {
    //White Background
    glClearColor(1, 1, 1, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    //Update Timer
    timer+=0.01;
    GLuint timerLoc = glGetUniformLocation(program->getID(), "timer");
    glUniform1f(timerLoc, timer);

    if(show3d){
      //Draw Cube
      glDrawArrays(GL_TRIANGLES,0, 36);
    }else{
      //Draw Triangle
      glDrawArrays(GL_TRIANGLES, 0, 3);
    }

    glfwSwapBuffers(gWindow);
}

//Compile Link and Create Shader Program
void createShaders(){
    Shader vertex("./shaders/vert.glsl",GL_VERTEX_SHADER);
    Shader fragment("./shaders/frag.glsl",GL_FRAGMENT_SHADER);

    program = new Program();

    program->attachShader(vertex);
    program->attachShader(fragment);

    //Link attribute name with location or you can do it in the shader
    // This code must happen each time program links!!!
    // positionLocation = 0;
    // colorLocation = 1;
    glBindAttribLocation(program->getID(), 0,"VertexPosition");
    glBindAttribLocation(program->getID(), 1,"VertexColor");

    program->link();
    program->use();

    if(Logger::show){
        program->printActiveAttribs();
        program->printActiveUniforms();
    }
}

//Generate VBO and VAO
void createAttributes(float  positionData[],int sizePos, float  colorData[], int sizeColor){

    //Generate vertex buffer objects
    GLuint vboHandles[2];
    glGenBuffers(2,vboHandles);

    //Hold onto an vbo id
    GLuint positionBufferHandle = vboHandles[0];
    GLuint colorBufferHandle = vboHandles[1];

    //Position Binding - bind data to vbo
    glBindBuffer(GL_ARRAY_BUFFER,positionBufferHandle);
    glBufferData(GL_ARRAY_BUFFER, sizePos, positionData, GL_STATIC_DRAW);

    //Color binding - bind data to vbo
    glBindBuffer(GL_ARRAY_BUFFER,colorBufferHandle);
    glBufferData(GL_ARRAY_BUFFER, sizeColor, colorData, GL_STATIC_DRAW);

    //generate a single vao
    GLuint vao;
    glGenVertexArrays(1,&vao);
    glBindVertexArray(vao);

    //Attribute Location Identifiers
    GLuint positionLocation = 0;
    GLuint colorLocation = 1;

    //Make location an array type
    glEnableVertexAttribArray(positionLocation);
    glEnableVertexAttribArray(colorLocation);

    //bind vao to vbo
    glBindBuffer(GL_ARRAY_BUFFER, positionBufferHandle);
    //specify datatype and info of vao
    glVertexAttribPointer(positionLocation, 3, GL_FLOAT, GL_FALSE, 0, NULL);

    //do the same for color buffer
    glBindBuffer(GL_ARRAY_BUFFER, colorBufferHandle);
    glVertexAttribPointer(colorLocation, 3, GL_FLOAT, GL_FALSE, 0, NULL);
}

void triangleSetup(){
    //Triangle Vertices Coordinates (Model Coordinates)
    float positionData[] ={
        -0.8f,-0.8f,0.0f,
        0.8f,-0.8f,0.0f,
        0.0f,0.8f,0.0f
    };
    //Triangle Vertice Colors
    float colorData[]={
        1.0f,0.0f,0.0f,
        0.0f,0.0f,1.0f,
        0.0f,1.0f,0.0f
    };

    createAttributes(positionData, sizeof(positionData), colorData, sizeof(colorData));
}

void cubeSetup(){
    //Cube Vertices Coordinates (Model Coordinates)
    float positionData[] ={

        -1.0f,-1.0f,-1.0f,
        -1.0f,-1.0f, 1.0f,
        -1.0f, 1.0f, 1.0f,

        1.0f, 1.0f,-1.0f,
        -1.0f,-1.0f,-1.0f,
        -1.0f, 1.0f,-1.0f,

        1.0f,-1.0f, 1.0f,
        -1.0f,-1.0f,-1.0f,
        1.0f,-1.0f,-1.0f,

        1.0f, 1.0f,-1.0f,
        1.0f,-1.0f,-1.0f,
        -1.0f,-1.0f,-1.0f,

        -1.0f,-1.0f,-1.0f,
        -1.0f, 1.0f, 1.0f,
        -1.0f, 1.0f,-1.0f,

        1.0f,-1.0f, 1.0f,
        -1.0f,-1.0f, 1.0f,
        -1.0f,-1.0f,-1.0f,

        -1.0f, 1.0f, 1.0f,
        -1.0f,-1.0f, 1.0f,
        1.0f,-1.0f, 1.0f,

        1.0f, 1.0f, 1.0f,
        1.0f,-1.0f,-1.0f,
        1.0f, 1.0f,-1.0f,

        1.0f,-1.0f,-1.0f,
        1.0f, 1.0f, 1.0f,
        1.0f,-1.0f, 1.0f,

        1.0f, 1.0f, 1.0f,
        1.0f, 1.0f,-1.0f,
        -1.0f, 1.0f,-1.0f,

        1.0f, 1.0f, 1.0f,
        -1.0f, 1.0f,-1.0f,
        -1.0f, 1.0f, 1.0f,

        1.0f, 1.0f, 1.0f,
        -1.0f, 1.0f, 1.0f,
        1.0f,-1.0f, 1.0f
    };
    //Cube vertice colors, one face has 2 triangles with different colors to show that it is made up with triangles
    float colorData[]={

        0.583f,  0.771f,  0.014f,
        0.583f,  0.771f,  0.014f,
        0.583f,  0.771f,  0.014f,

        1.000f,  0.000f,  0.000f,
        1.000f,  0.000f,  0.000f,
        1.000f,  0.000f,  0.000f,

        0.583f,  0.771f,  0.014f,
        0.583f,  0.771f,  0.014f,
        0.583f,  0.771f,  0.014f,

        0.800f,  0.000f,  0.000f,
        0.800f,  0.000f,  0.000f,
        0.800f,  0.000f,  0.000f,

        0.583f,  0.771f,  0.014f,
        0.583f,  0.771f,  0.014f,
        0.583f,  0.771f,  0.014f,

        0.583f,  0.771f,  0.014f,
        0.583f,  0.771f,  0.014f,
        0.583f,  0.771f,  0.014f,

        1.000f,  0.000f,  0.000f,
        1.000f,  0.000f,  0.000f,
        1.000f,  0.000f,  0.000f,

        0.000f,  1.000f,  0.000f,
        0.000f,  1.000f,  0.000f,
        0.000f,  1.000f,  0.000f,

        0.000f,  1.000f,  0.000f,
        0.000f,  1.000f,  0.000f,
        0.000f,  1.000f,  0.000f,

        0.000f,  0.000f,  1.000f,
        0.000f,  0.000f,  1.000f,
        0.000f,  0.000f,  1.000f,

        0.000f,  0.000f,  1.000f,
        0.000f,  0.000f,  1.000f,
        0.000f,  0.000f,  1.000f,

        1.000f,  0.000f,  0.000f,
        1.000f,  0.000f,  0.000f,
        1.000f,  0.000f,  0.000f,
    };
    createAttributes(positionData, sizeof(positionData), colorData, sizeof(colorData));

}

void printInfo(){
    char buff[255];

    //Print OpenGl Info
    Logger::log(ANSI_COLOR_CYAN "*****************************************************************************" ANSI_COLOR_RESET);
    snprintf(buff, sizeof(buff), "OpenGL version: %s", glGetString(GL_VERSION));
    Logger::log(buff);

    snprintf(buff, sizeof(buff), "GLSL version: %s", glGetString(GL_SHADING_LANGUAGE_VERSION));
    Logger::log(buff);

    snprintf(buff, sizeof(buff), "Vendor: %s", glGetString(GL_VENDOR));
    Logger::log(buff);

    snprintf(buff, sizeof(buff), "Renderer: %s", glGetString(GL_RENDERER));
    Logger::log(buff);

    //Print Window Position Info
    Logger::log(ANSI_COLOR_CYAN"--------------------------------------------------------------------------------" ANSI_COLOR_RESET);
    int xpos, ypos;
    glfwGetWindowPos(gWindow, &xpos, &ypos);
    snprintf(buff, sizeof(buff), "Window Position\n x: %d, y: %d",xpos,ypos);
    Logger::log(buff);
    Logger::log("Set Window Postion in the makefile otherwise it defaults to center of screen.");
    Logger::log(ANSI_COLOR_CYAN "-----------------------------------------------------------------------------" ANSI_COLOR_RESET);
    Logger::log(ANSI_COLOR_CYAN "********************************************************************************\n" ANSI_COLOR_RESET);

}
void OnError(int errorCode, const char* msg) {
    throw std::runtime_error(msg);
}
void key_press(GLFWwindow* window, int key, int scancode, int action, int mods){

    //Recompile Shaders on C key press
    if (glfwGetKey(window, GLFW_KEY_C) == GLFW_PRESS){
        Logger::log(ANSI_COLOR_MAGENTA "================================================================================");
        Logger::log("                              Recompiling Shaders                               ");
        Logger::log("================================================================================");
        createShaders();
        Logger::log("================================================================================");
        Logger::log("                              Compilation Complete                              ");
        Logger::log("================================================================================ " ANSI_COLOR_RESET);
    }
    //Use the Cube
    if(glfwGetKey(window, GLFW_KEY_2) == GLFW_PRESS){
        show3d=true;
        Logger::log(ANSI_COLOR_MAGENTA "================================================================================");
        Logger::log("                              Using Cube                                        ");
        Logger::log("================================================================================" ANSI_COLOR_RESET);
        cubeSetup();
    }
    //Use the Triangle
    if(glfwGetKey(window, GLFW_KEY_1) == GLFW_PRESS){
        show3d=false;
        triangleSetup();
        Logger::log(ANSI_COLOR_MAGENTA "================================================================================");
        Logger::log("                              Using Triangle                  ");
        Logger::log("================================================================================" ANSI_COLOR_RESET);
    }
}
int main(int argc, char **argv)
{
    Logger::log(ANSI_COLOR_CYAN "################################################################################");
    Logger::log("                              Starting GLFW and OpenGL           ");
    Logger::log("################################################################################" ANSI_COLOR_RESET);
    //Logger::show =false;
    show3d=false;
    glfwSetErrorCallback(OnError);
    if(!glfwInit())
        throw std::runtime_error("glfwInit failed");

    // open a window with GLFW
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    gWindow = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "OpenGL Tutorial", NULL, NULL);

    //Set Window Position or center of screen if not specified
    if(argc >2 && atoi(argv[1]) != -1 && atoi(argv[2]) != -1){
        glfwSetWindowPos(gWindow,atoi(argv[1]),atoi(argv[2]));
    }
    //Disallow Resizing
    glfwWindowHint(GLFW_RESIZABLE,GL_FALSE);

    if(!gWindow)
        throw std::runtime_error("glfwCreateWindow failed. Can your hardware handle OpenGL 4.1?");

    // GLFW settings
    glfwMakeContextCurrent(gWindow);

    // initialise GLEW with core
    glewExperimental = GL_TRUE;
    if(glewInit() != GLEW_OK)
        throw std::runtime_error("glewInit failed");

    // print out some environment info
    printInfo();

    createShaders();

    triangleSetup();

    //Hide things that are behind others
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);

    //start timer
    timer = 0.0;

    //Create a screen size uniform
    GLuint location = glGetUniformLocation(program->getID(),"screen");
    glUniform2f(location,SCREEN_WIDTH, SCREEN_HEIGHT);

    //Handle Key events
    glfwSetKeyCallback(gWindow, key_press);
    //Run Loop
    while(!glfwWindowShouldClose(gWindow)){
        glfwPollEvents();
        Render();
    }
    glfwTerminate();

}

<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>

struct ModelInputData
{
    double start_army_size;             // > 0          Tamanho inicial do exército
    double start_enemy_size;            // > 0          Tamanho inicial do exército inimigo
    double loose_battle_fraction;       // 0 < x < 1:   Porcentagem do exército que define derrota
    double army_skill;                  // 0 < x <= 1   Perícia do exército em eliminar inimigos
    double enemy_skill;                 // 0 < x <= 1   Perícia do inimigo em eliminar o exército
    double start_ammo;                  // > 0          Quantidade de munição que estará disponível durante a batalha
    double army_fire_rate;              // 0 < x <= 1   Taxa com que o exército consegue atirar a munição disponível
    double ammo_diffusion_coeffient;    // > 0          Velocidade com o que a munição é distribuída para o exército
    double formation_size;              // > 0          Tamanho da formação utilizada na batalha pelo exército
    double front_line_fraction;         // 0 < x <= 1   Porcentagem do exército que atuará na linha de frente
    double enemy_front_line_fraction;   // 0 < x <= 1   Porcentagem do exército inimigo que atuará na linha de frente

    double delta_time;                  // > 0
    double delta_x;                     // > 0

    /**
     * @brief ModelInputData default input data
     */
    ModelInputData()
    {
        start_army_size             = 500.0;
        start_enemy_size            = 500.0;
        loose_battle_fraction       = 0.01;
        army_skill                  = 0.03;
        enemy_skill                 = 0.03;
        start_ammo                  = 950;
        army_fire_rate              = 0.05;
        ammo_diffusion_coeffient    = 1.0;
        formation_size              = 7;
        front_line_fraction         = 0.1;
        enemy_front_line_fraction   = 1.0;

        delta_time                  = 0.07;
        delta_x                     = 0.6;

        std::cout << "CFL = " << ammo_diffusion_coeffient * delta_time / (delta_x * delta_x) << std::endl;
    }

    friend std::ostream& operator<< (std::ostream& out, const ModelInputData& input_data)
    {
        out << "#-------------------------------------------------" << std::endl;
        out << "#--- GentlesmanBattle Input Data" << std::endl;
        out << "#-------------------------------------------------" << std::endl;
        out << "#- Start Army Size    : " << input_data.start_army_size << std::endl;
        out << "#- Start Enemy Size   : " << input_data.start_enemy_size << std::endl;
        out << "#- Army Skill         : " << input_data.army_skill << std::endl;
        out << "#- Enemy Skill        : " << input_data.enemy_skill << std::endl;
        out << "#- Start Ammo         : " << input_data.start_ammo << std::endl;
        out << "#- Ammo Diffusion Coef: " << input_data.ammo_diffusion_coeffient << std::endl;
        out << "#- Battle Field Size  : " << input_data.formation_size << std::endl;
        out << "#- Front Line Fraction: " << input_data.front_line_fraction << std::endl;
        out << "#- Delta Time         : " << input_data.delta_time << std::endl;
        out << "#- Delta X            : " << input_data.delta_x << std::endl;
        out << "#--------------------------------------------------" << std::endl;

        return out;
    }
};

struct ModelInfo
{
    double time             = 0.0;

    double new_army_size    = 0.0;
    double old_army_size    = 0.0;

    double new_enemy_size   = 0.0;
    double old_enemy_size   = 0.0;

    std::vector<double> new_ammo_amount;
    std::vector<double> old_ammo_amount;

    const ModelInputData& model_input;

    const double CFL = model_input.ammo_diffusion_coeffient * model_input.delta_time / (model_input.delta_x * model_input.delta_x);

    ModelInfo(const ModelInputData& input_data) :
        model_input(input_data)
    {
        // Setting up the mesh for the ammo diffusion
        new_ammo_amount.resize(static_cast<int>(input_data.formation_size / input_data.delta_x));
        old_ammo_amount.resize(new_ammo_amount.size());

        // Initial condition
        old_army_size = input_data.start_army_size;
        old_enemy_size = input_data.start_enemy_size;

        // Ammot starts at rear-line
        old_ammo_amount[1] = model_input.start_ammo;
    }

    void advance_time()
    {
        // Calculates the fraction of the army and enemies currently standing in the front-line
        double front_line_size = model_input.front_line_fraction * old_army_size;
        double enemy_front_line_size = model_input.front_line_fraction * old_enemy_size;

        // Army
        new_army_size = old_army_size - model_input.delta_time * model_input.enemy_skill * front_line_size * enemy_front_line_size;
        old_army_size = new_army_size;

        // Enemy
        double shoots_fired = old_ammo_amount.back() * model_input.army_fire_rate;
        new_enemy_size = old_enemy_size - model_input.delta_time * model_input.army_skill * shoots_fired * front_line_size * enemy_front_line_size;
        old_enemy_size = new_enemy_size;

        // Ammo Diffusion
        for(size_t i = 1; i < new_ammo_amount.size() - 1; ++i)
        {
            new_ammo_amount[i] = old_ammo_amount[i] + CFL * (old_ammo_amount[i-1] - 2.0 * old_ammo_amount[i] + old_ammo_amount[i+1]);
        }

        //
        // Ammo boundary conditions
        //

        // At x=0 there is no flow.
        new_ammo_amount[0] = new_ammo_amount[1];

        // At x=L the ammo is being used by the soldiers
        // Calculates the percentage of ammo used at the frontline.
        double ammo_usage_ratio = 1.0 - (1.0 / front_line_size);
        new_ammo_amount.back() = new_ammo_amount[new_ammo_amount.size() - 2] * ammo_usage_ratio;

        // Swap vectors for next time step
        new_ammo_amount.swap(old_ammo_amount);

        // Finally, advance the time
        time += model_input.delta_time;
    }

    /**
     * @brief True if the battle has came to an end
     *
     * The condition for the battle to stop is when the army size reaches a fraction defined
     * by @ref ModelInputData::loose_battle_fraction. The condition is applied for both the army
     * and the enemies.
     *
     * @return True if the battle has came to an end false otherwise
     */
    bool should_stop() const
    {
        return new_army_size <= model_input.start_army_size * model_input.loose_battle_fraction ||
                new_enemy_size <= model_input.start_enemy_size * model_input.loose_battle_fraction;
    }

    /**
     * @brief Returns true if the number of soldiers is bigger than the number of enemies soldiers at this moment
     */
    bool is_army_winning() const
    {
        return old_army_size > old_enemy_size;
    }

    friend std::ostream& operator<< (std::ostream& out, const ModelInfo& info)
    {
        out << "#-------------------------------------------------" << std::endl;
        out << "#--- GentlesmanBattle Execution Summary" << std::endl;
        out << "#-------------------------------------------------" << std::endl;
        out << "# Number of Iterations      : " << info.time / info.model_input.delta_time << std::endl;
        out << "# Total time                : " << info.time << std::endl;
        out << "# Soldiers Count            : " << info.new_army_size << std::endl;
        out << "# Enemies Count             : " << info.new_enemy_size << std::endl;
        out << "# Available Ammo at Fronline: " << info.new_ammo_amount.back() << std::endl;
        out << "# Available Ammo at Rearline: " << info.new_ammo_amount.front() << std::endl;
        out << "#-------------------------------------------------" << std::endl;
        out << "# Battle Result: ";

        if(info.is_army_winning())
        {
            out << "YOU WIN!" << std::endl;
        }
        else
        {
            out << "YOU LOOSE!" << std::endl;
        }

        out << "#-------------------------------------------------" << std::endl;

        return out;
    }
};

struct ModelOutput
{
    std::string model_output_filename;
    std::fstream output_file;
    const ModelInfo& model_info;

    ModelOutput(const std::string& prefix, const ModelInfo& _model_info, const ModelInputData& model_input)
        : model_output_filename(prefix + "_gentlemans_battle.dat"),
          model_info(_model_info)
    {
        output_file.open(model_output_filename, std::ios::out);
        output_file << model_input << std::endl << std::endl;
        output_file << "# Time  ArmySize    EnemySize" << std::endl;
    }

    void write_output_step()
    {
        output_file << std::setw(10) << std::setprecision(10) << std::fixed << std::setfill('0') <<
                       model_info.time << " " <<
                       model_info.old_army_size << " " <<
                       model_info.old_enemy_size << " " <<
                       model_info.old_ammo_amount.front() << " " <<
                       model_info.old_ammo_amount.back() << " " <<
                       std::endl;
    }

    void stop_execution(bool b_show_gnuplot = true)
    {
        // Write Execution Summary into the output file
        output_file << model_info << std::endl;

        if(output_file.is_open())
        {
            output_file.close();
        }

        if(b_show_gnuplot)
        {
            std::string output_filename_quotes = "'" + model_output_filename + "'";
            std::string gnuplot_script_filename = "_gentlemans_battle.gnu";

            std::fstream gnuplot_script_file(gnuplot_script_filename, std::ios::out);

            gnuplot_script_file << "set xlabel 'Time'" << std::endl;
            gnuplot_script_file << "set ylabel";

            std::string plot_command = "gnuplot -p -e \"plot " +
                    output_filename_quotes + " using 1:2 with lines title 'Army'," +
                    output_filename_quotes + " using 1:3 with lines title 'Enemies'," +
                    output_filename_quotes + "using 1:4 with lines title 'Ammo at rearguard'," +
                    output_filename_quotes + "using 1:5 with lines title 'Ammo at frontline'" +
                    "\"";

            std::cout << plot_command << std::endl;

            // show reaction plot
            system(plot_command.data());

            // show diffusion plot
            plot_command = "gnuplot -p -e \"plot " +
                    output_filename_quotes + "using 1:4 with lines title 'Ammo at rearguard'," +
                    output_filename_quotes + "using 1:5 with lines title 'Ammo at frontline'" +
                    "\"";
//            system(plot_command.data());
            std::cout << plot_command << std::endl;
        }
    }
};

struct GentlesmanBattleModel
{
    ModelInputData input;
    ModelOutput output;
    ModelInfo info;

    GentlesmanBattleModel() :
        output("", info, input), info(input)
    {
    }

    void run()
    {
        // Print parameters information
        std::cout << input << std::endl;

        do
        {
            output.write_output_step();
            info.advance_time();
        }
        while(!info.should_stop());

        // Print execution summary
        std::cout << info << std::endl;
    }
};

int main()
{
    GentlesmanBattleModel model;
    model.run();
    model.output.stop_execution();
    return EXIT_SUCCESS;
}

<commit_msg>Configuração do plot de reação<commit_after>#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>

struct ModelInputData
{
    double start_army_size;             // > 0          Tamanho inicial do exército
    double start_enemy_size;            // > 0          Tamanho inicial do exército inimigo
    double loose_battle_fraction;       // 0 < x < 1:   Porcentagem do exército que define derrota
    double army_skill;                  // 0 < x <= 1   Perícia do exército em eliminar inimigos
    double enemy_skill;                 // 0 < x <= 1   Perícia do inimigo em eliminar o exército
    double start_ammo;                  // > 0          Quantidade de munição que estará disponível durante a batalha
    double army_fire_rate;              // 0 < x <= 1   Taxa com que o exército consegue atirar a munição disponível
    double ammo_diffusion_coeffient;    // > 0          Velocidade com o que a munição é distribuída para o exército
    double formation_size;              // > 0          Tamanho da formação utilizada na batalha pelo exército
    double front_line_fraction;         // 0 < x <= 1   Porcentagem do exército que atuará na linha de frente
    double enemy_front_line_fraction;   // 0 < x <= 1   Porcentagem do exército inimigo que atuará na linha de frente

    double delta_time;                  // > 0
    double delta_x;                     // > 0

    /**
     * @brief ModelInputData default input data
     */
    ModelInputData()
    {
        start_army_size             = 500.0;
        start_enemy_size            = 500.0;
        loose_battle_fraction       = 0.01;
        army_skill                  = 0.03;
        enemy_skill                 = 0.03;
        start_ammo                  = 950;
        army_fire_rate              = 0.05;
        ammo_diffusion_coeffient    = 1.0;
        formation_size              = 7;
        front_line_fraction         = 0.1;
        enemy_front_line_fraction   = 1.0;

        delta_time                  = 0.07;
        delta_x                     = 0.6;

        std::cout << "CFL = " << ammo_diffusion_coeffient * delta_time / (delta_x * delta_x) << std::endl;
    }

    friend std::ostream& operator<< (std::ostream& out, const ModelInputData& input_data)
    {
        out << "#-------------------------------------------------" << std::endl;
        out << "#--- GentlesmanBattle Input Data" << std::endl;
        out << "#-------------------------------------------------" << std::endl;
        out << "#- Start Army Size    : " << input_data.start_army_size << std::endl;
        out << "#- Start Enemy Size   : " << input_data.start_enemy_size << std::endl;
        out << "#- Army Skill         : " << input_data.army_skill << std::endl;
        out << "#- Enemy Skill        : " << input_data.enemy_skill << std::endl;
        out << "#- Start Ammo         : " << input_data.start_ammo << std::endl;
        out << "#- Ammo Diffusion Coef: " << input_data.ammo_diffusion_coeffient << std::endl;
        out << "#- Battle Field Size  : " << input_data.formation_size << std::endl;
        out << "#- Front Line Fraction: " << input_data.front_line_fraction << std::endl;
        out << "#- Delta Time         : " << input_data.delta_time << std::endl;
        out << "#- Delta X            : " << input_data.delta_x << std::endl;
        out << "#--------------------------------------------------" << std::endl;

        return out;
    }
};

struct ModelInfo
{
    double time             = 0.0;

    double new_army_size    = 0.0;
    double old_army_size    = 0.0;

    double new_enemy_size   = 0.0;
    double old_enemy_size   = 0.0;

    std::vector<double> new_ammo_amount;
    std::vector<double> old_ammo_amount;

    const ModelInputData& model_input;

    const double CFL = model_input.ammo_diffusion_coeffient * model_input.delta_time / (model_input.delta_x * model_input.delta_x);

    ModelInfo(const ModelInputData& input_data) :
        model_input(input_data)
    {
        // Setting up the mesh for the ammo diffusion
        new_ammo_amount.resize(static_cast<int>(input_data.formation_size / input_data.delta_x));
        old_ammo_amount.resize(new_ammo_amount.size());

        // Initial condition
        old_army_size = input_data.start_army_size;
        old_enemy_size = input_data.start_enemy_size;

        // Ammot starts at rear-line
        old_ammo_amount[1] = model_input.start_ammo;
    }

    void advance_time()
    {
        // Calculates the fraction of the army and enemies currently standing in the front-line
        double front_line_size = model_input.front_line_fraction * old_army_size;
        double enemy_front_line_size = model_input.front_line_fraction * old_enemy_size;

        // Army
        new_army_size = old_army_size - model_input.delta_time * model_input.enemy_skill * front_line_size * enemy_front_line_size;
        old_army_size = new_army_size;

        // Enemy
        double shoots_fired = old_ammo_amount.back() * model_input.army_fire_rate;
        new_enemy_size = old_enemy_size - model_input.delta_time * model_input.army_skill * shoots_fired * front_line_size * enemy_front_line_size;
        old_enemy_size = new_enemy_size;

        // Ammo Diffusion
        for(size_t i = 1; i < new_ammo_amount.size() - 1; ++i)
        {
            new_ammo_amount[i] = old_ammo_amount[i] + CFL * (old_ammo_amount[i-1] - 2.0 * old_ammo_amount[i] + old_ammo_amount[i+1]);
        }

        //
        // Ammo boundary conditions
        //

        // At x=0 there is no flow.
        new_ammo_amount[0] = new_ammo_amount[1];

        // At x=L the ammo is being used by the soldiers
        // Calculates the percentage of ammo used at the frontline.
        double ammo_usage_ratio = 1.0 - (1.0 / front_line_size);
        new_ammo_amount.back() = new_ammo_amount[new_ammo_amount.size() - 2] * ammo_usage_ratio;

        // Swap vectors for next time step
        new_ammo_amount.swap(old_ammo_amount);

        // Finally, advance the time
        time += model_input.delta_time;
    }

    /**
     * @brief True if the battle has came to an end
     *
     * The condition for the battle to stop is when the army size reaches a fraction defined
     * by @ref ModelInputData::loose_battle_fraction. The condition is applied for both the army
     * and the enemies.
     *
     * @return True if the battle has came to an end false otherwise
     */
    bool should_stop() const
    {
        return new_army_size <= model_input.start_army_size * model_input.loose_battle_fraction ||
                new_enemy_size <= model_input.start_enemy_size * model_input.loose_battle_fraction;
    }

    /**
     * @brief Returns true if the number of soldiers is bigger than the number of enemies soldiers at this moment
     */
    bool is_army_winning() const
    {
        return old_army_size > old_enemy_size;
    }

    friend std::ostream& operator<< (std::ostream& out, const ModelInfo& info)
    {
        out << "#-------------------------------------------------" << std::endl;
        out << "#--- GentlesmanBattle Execution Summary" << std::endl;
        out << "#-------------------------------------------------" << std::endl;
        out << "# Number of Iterations      : " << info.time / info.model_input.delta_time << std::endl;
        out << "# Total time                : " << info.time << std::endl;
        out << "# Soldiers Count            : " << info.new_army_size << std::endl;
        out << "# Enemies Count             : " << info.new_enemy_size << std::endl;
        out << "# Available Ammo at Fronline: " << info.new_ammo_amount.back() << std::endl;
        out << "# Available Ammo at Rearline: " << info.new_ammo_amount.front() << std::endl;
        out << "#-------------------------------------------------" << std::endl;
        out << "# Battle Result: ";

        if(info.is_army_winning())
        {
            out << "YOU WIN!" << std::endl;
        }
        else
        {
            out << "YOU LOOSE!" << std::endl;
        }

        out << "#-------------------------------------------------" << std::endl;

        return out;
    }
};

struct ModelOutput
{
    std::string model_output_filename;
    std::fstream output_file;
    const ModelInfo& model_info;

    ModelOutput(const std::string& prefix, const ModelInfo& _model_info, const ModelInputData& model_input)
        : model_output_filename(prefix + "_gentlemans_battle.dat"),
          model_info(_model_info)
    {
        output_file.open(model_output_filename, std::ios::out);
        output_file << model_input << std::endl << std::endl;
        output_file << "# Time  ArmySize    EnemySize" << std::endl;
    }

    void write_output_step()
    {
        output_file << std::setw(10) << std::setprecision(10) << std::fixed << std::setfill('0') <<
                       model_info.time << " " <<
                       model_info.old_army_size << " " <<
                       model_info.old_enemy_size << " " <<
                       model_info.old_ammo_amount.front() << " " <<
                       model_info.old_ammo_amount.back() << " " <<
                       std::endl;
    }

    void stop_execution(bool b_show_gnuplot = true)
    {
        // Write Execution Summary into the output file
        output_file << model_info << std::endl;

        if(output_file.is_open())
        {
            output_file.close();
        }

        if(b_show_gnuplot)
        {
            std::string output_filename_quotes = "'" + model_output_filename + "'";
            std::string gnuplot_script_filename = "_gentlemans_battle.gnu";

            {
                std::fstream gnuplot_script_file(gnuplot_script_filename, std::ios::out);

                gnuplot_script_file << "set terminal 'wxt'" << std::endl;
                gnuplot_script_file << "set xlabel 'Tempo'" << std::endl;
                gnuplot_script_file << "set ylabel 'Número de Soldados'" << std::endl;
                gnuplot_script_file << "set zeroaxis" << std::endl;
                gnuplot_script_file << "set title 'Evolução do Número de Soldados no Campo de Batalha'" << std::endl;
                gnuplot_script_file << "plot " <<
                        output_filename_quotes << " using 1:2 with lines title 'Soldados'," +
                        output_filename_quotes << " using 1:3 with lines title 'Inimigos'";
            }

            // show reaction plot
            std::string plot_command = "gnuplot -p " + gnuplot_script_filename;
            std::cout << plot_command << std::endl;
            system(plot_command.data());

            // show diffusion plot
//            plot_command = "gnuplot -p -e \"plot " +
//                    output_filename_quotes + "using 1:4 with lines title 'Ammo at rearguard'," +
//                    output_filename_quotes + "using 1:5 with lines title 'Ammo at frontline'" +
//                    "\"";
////            system(plot_command.data());
//            std::cout << plot_command << std::endl;
        }
    }
};

struct GentlesmanBattleModel
{
    ModelInputData input;
    ModelOutput output;
    ModelInfo info;

    GentlesmanBattleModel() :
        output("", info, input), info(input)
    {
    }

    void run()
    {
        // Print parameters information
        std::cout << input << std::endl;

        do
        {
            output.write_output_step();
            info.advance_time();
        }
        while(!info.should_stop());

        // Print execution summary
        std::cout << info << std::endl;
    }
};

int main()
{
    GentlesmanBattleModel model;
    model.run();
    model.output.stop_execution();
    return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <algorithm>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <errno.h>
#include <stdlib.h>
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <cstring>
#include <cstddef>

using namespace std;

#define printVec(x) for(unsigned int i = 0; i < x.size(); i++) \
                        cout << x.at(i) << " "; \
                    cout << endl;

//function to print out the contents of argv
void printARGV(char **argv){
    int i = 0;
    while(argv[i] != NULL){
        cout << "Pos " << i << ": " << argv[i] << endl;
        i++;
    }
    cout << endl;
}

/*this function will get all the file descriptors or directories and put
 them into a vector of strings called file_O_dir*/

//anything that is not 'ls' or '-<flags>' is considered a file or dir

vector<string> getFiles_Dirs (char **argv){
    string targets; //this is the rest of the targest after the flags

    string ls = "ls";
    char dash = '-';

    vector<string> importantStuff;

    unsigned int pos = 1;
    while(argv[pos] != '\0'){
        string temp = argv[pos]; //keep the current argv part in a string

        if(argv[pos] == ls){
            pos++; //increment position to get next arg
            continue; //continue to next iteration
        }

        if(argv[pos][0] == dash){
            pos++; //increment position to get next arg
            continue; //continue to next iteration
        }

        importantStuff.push_back(temp); //if both cases fail, you add it!

        pos++; //increment to get next arg
    }

    return importantStuff;
}

/*Comparision function for two char* */
/*needed for sorting*/
bool compareTwo(const char* s1, const char* s2){
    return strcasecmp(s1, s2) < 0;
}

bool compareTwo_(string a, string b){
    string str1( a );
    string str2( b );
    transform( str1.begin(), str1.end(), str1.begin(), ::tolower);
    transform( str2.begin(), str2.end(), str2.begin(), ::tolower);
    return (str1 < str2);
}

/*this function takes in a directory and outputs its contents*/

/*string magic = directory */

vector<char*> open_direct(string magic){
    const char* magic_2 = magic.c_str(); //need to do some more magic
    vector<char*> filenames; //to store the filenames so we can sort

    DIR *dirp;
    if(NULL == (dirp = opendir(magic_2))){
        perror("There was an error with opendir(). ");
        exit(1);
    }
    struct dirent *filespecs;
    errno = 0;
    while(NULL != (filespecs = readdir(dirp))){
        filenames.push_back(filespecs->d_name);
        //cout << filespecs->d_name << " ";
    }

    if(errno != 0){
        perror("There was an error with readdir(). ");
        exit(1);
    }
    cout << endl;
    if(-1 == closedir(dirp)){
        perror("There was an error with closedir(). ");
        exit(1);
    }

    return filenames;
}

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

    //test and case variables
    string flags_;
    string ls = "ls";
    char dash = '-';
//  --------------------------------------------------------------------

    //vectors of flags -a, -l, -R
    vector<char> flags;
    flags.push_back('a');
    flags.push_back('l');
    flags.push_back('R');

    //vector of files & directories
    vector<string> files_dirs;
//  --------------------------------------------------------------------

    bool isFlag_a = false; //bool to determine if the flag is -a
    bool isFlag_l = false; //bool to determine if the flag is -l
    bool isFlag_R = false; //bool to determine if the flag is -R
    bool is_ls = false;    //bool to determine if the input ONLY ls
//  --------------------------------------------------------------------

    if(argc <= 1){ //assumes the user didn't type anything
        return 0;
    }
//  --------------------------------------------------------------------

    //What's in char **argv?
    //printARGV(argv);
//  --------------------------------------------------------------------

    /*if you type anything other than ls or ls with flags,
      output an error and quit the program*/
    if(argc > 1 && argc <= 2 && argv[1] != ls){
        cout << "Error: no form of ls" << endl;
        exit(1);
    }
    /*below are some cases for ls*/
    else if(argc > 1  && argv[1] == ls){ //is there a ls?
        is_ls = true;
        if(is_ls) ;

        files_dirs = getFiles_Dirs(argv); //get directories or files
        sort(files_dirs.begin(), files_dirs.end(), compareTwo_);
        printVec(files_dirs);

        //where there any directories or files that were called?
        if( !(files_dirs.size() > 0) ){
            /*call ls on the current working directory*/

            //get the current working directory
            char buf[1024];
            if(!getcwd(buf,1024)){
                perror("problem with getcwd");
            }
            string cwd(buf); //convert cstring to string for function

            //get the vector of the contents in the current directory
            vector<char*> contents = open_direct(cwd);

            /*remove any hidden files (files that begin with a '.')*/
            char dot = '.';
            unsigned int totalsize = contents.size();
            for(unsigned int i = 0; i < totalsize; ++i){
                if(*(contents.at(i)) == dot){
                    contents.erase(contents.begin() + i); //remove that file
                    totalsize--; //after you erase you -1 from size
                    i = 0; //after you -1 from size, you reset i
                }
            }

            //sort the files within directory
            sort(contents.begin(), contents.end(), compareTwo);

            //print the files to standard out
            printVec(contents);
        }
        else{
            ;
        }
    }
    else{ //is there a ls with flags and maybe files or dir
        for(int x = 0; x < argc; ++x){
            if(*(argv[x]) == dash){ //grabs flags
                flags_ = argv[x]; //put the cstring in a string
                flags_.erase(flags_.begin()); //erase the '-' at the beginning

                //go through each flag_ and compare with the vector of flags
                for(unsigned int i = 0 ; i < flags_.size(); ++i){
                    for(unsigned int j = 0; j < flags.size(); ++j){
                        if(flags_.at(i) == flags.at(j)){
                            if(flags.at(j) == 'a'){
                                isFlag_a = true;
                                if(isFlag_a) cout << "We have a!" << endl;
                            }
                            else if(flags.at(j) == 'l'){
                                isFlag_l = true;
                                if(isFlag_l) cout << "We have l!" << endl;
                            }
                            else if(flags.at(j) == 'R'){
                                isFlag_R = true;
                                if(isFlag_R) cout << "We have R!" << endl;
                            }
                        }
                    }
                }
            }
        }
    }

    //files_dirs = getFiles_Dir(argv, );
//  --------------------------------------------------------------------

    return 0;
}
<commit_msg>working on ls with multiple files<commit_after>#include <iostream>
#include <algorithm>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <errno.h>
#include <stdlib.h>
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <cstring>
#include <cstddef>

using namespace std;

#define printVec(x) for(unsigned int i = 0; i < x.size(); i++) \
                        cout << x.at(i) << " "; \
                    cout << endl;

//function to print out the contents of argv
void printARGV(char **argv){
    int i = 0;
    while(argv[i] != NULL){
        cout << "Pos " << i << ": " << argv[i] << endl;
        i++;
    }
    cout << endl;
}

/*this function will get all the file descriptors or directories and put
 them into a vector of strings called file_O_dir*/

//anything that is not 'ls' or '-<flags>' is considered a file or dir

vector<string> getFiles_Dirs (char **argv){
    string targets; //this is the rest of the targest after the flags

    string ls = "ls";
    char dash = '-';

    vector<string> importantStuff;

    unsigned int pos = 1;
    while(argv[pos] != '\0'){
        string temp = argv[pos]; //keep the current argv part in a string

        if(argv[pos] == ls){
            pos++; //increment position to get next arg
            continue; //continue to next iteration
        }

        if(argv[pos][0] == dash){
            pos++; //increment position to get next arg
            continue; //continue to next iteration
        }

        importantStuff.push_back(temp); //if both cases fail, you add it!

        pos++; //increment to get next arg
    }

    return importantStuff;
}

/*Comparision function for two char* */
/*needed for sorting*/
bool compareTwo(const char* s1, const char* s2){
    return strcasecmp(s1, s2) < 0;
}

bool compareTwo_(string a, string b){
    string str1( a );
    string str2( b );
    transform( str1.begin(), str1.end(), str1.begin(), ::tolower);
    transform( str2.begin(), str2.end(), str2.begin(), ::tolower);
    return (str1 < str2);
}

/*this function takes in a directory and outputs its contents*/

/*string magic = directory */

vector<char*> open_direct(string magic){
    const char* magic_2 = magic.c_str(); //need to do some more magic
    vector<char*> filenames; //to store the filenames so we can sort

    DIR *dirp;
    if(NULL == (dirp = opendir(magic_2))){
        perror("There was an error with opendir(). ");
        exit(1);
    }
    struct dirent *filespecs;
    errno = 0;
    while(NULL != (filespecs = readdir(dirp))){
        filenames.push_back(filespecs->d_name);
        //cout << filespecs->d_name << " ";
    }

    if(errno != 0){
        perror("There was an error with readdir(). ");
        exit(1);
    }
    cout << endl;
    if(-1 == closedir(dirp)){
        perror("There was an error with closedir(). ");
        exit(1);
    }

    return filenames;
}

void ls_multiple(vector<string> &file_dir){
    for(unsigned int i = 0; i < file_dir.size(); ++i){
        unsigned int j;

        //CHECK THIS STATEMENT!!!
        vector<char*> contents_ = open_direct((file_dir.at(i)));

        /*remove any hidden files (files that begin with a '.')*/
        char dot = '.';
        unsigned int totalsize = contents_.size();
        for(j = 0; j < totalsize; ++j){
            if(*(contents_.at(j)) == dot){
                contents_.erase(contents_.begin() + j); //remove that file
                totalsize--; //after you erase you -1 from size
                j = 0; //after you -1 from size, you reset i
            }
        }

        //sort the files within directory
        sort(contents_.begin(), contents_.end(), compareTwo);

        cout << file_dir.at(j) << ":" << endl; //formatting..

        //print the files to standard out
        printVec(contents_);

        cout << endl; //formatting..
    }
}

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

    //test and case variables
    string flags_;
    string ls = "ls";
    char dash = '-';
//  --------------------------------------------------------------------

    //vectors of flags -a, -l, -R
    vector<char> flags;
    flags.push_back('a');
    flags.push_back('l');
    flags.push_back('R');

    //vector of files & directories
    vector<string> files_dirs;
//  --------------------------------------------------------------------

    bool isFlag_a = false; //bool to determine if the flag is -a
    bool isFlag_l = false; //bool to determine if the flag is -l
    bool isFlag_R = false; //bool to determine if the flag is -R
    bool is_ls = false;    //bool to determine if the input ONLY ls
//  --------------------------------------------------------------------

    if(argc <= 1){ //assumes the user didn't type anything
        return 0;
    }
//  --------------------------------------------------------------------

    //What's in char **argv?
    //printARGV(argv);
//  --------------------------------------------------------------------

    /*if you type anything other than ls or ls with flags,
      output an error and quit the program*/
    if(argc > 1 && argc <= 2 && argv[1] != ls){
        cout << "Error: no form of ls" << endl;
        exit(1);
    }
    /*below are some cases for ls*/
    else if(argc > 1  && argv[1] == ls){ //is there a ls?
        is_ls = true;
        if(is_ls) ;

        files_dirs = getFiles_Dirs(argv); //get directories or files

        //sort dictionary files so they can be executed in order
        sort(files_dirs.begin(), files_dirs.end(), compareTwo_);

        //where there any directories or files that were called?
        if( !(files_dirs.size() > 0) ){
            /*call ls on the current working directory*/

            //get the current working directory
            char buf[1024];
            if(!getcwd(buf,1024)){
                perror("problem with getcwd");
            }
            string cwd(buf); //convert cstring to string for function

            //get the vector of the contents in the current directory
            vector<char*> contents = open_direct(cwd);

            /*remove any hidden files (files that begin with a '.')*/
            char dot = '.';
            unsigned int totalsize = contents.size();
            for(unsigned int i = 0; i < totalsize; ++i){
                if(*(contents.at(i)) == dot){
                    contents.erase(contents.begin() + i); //remove that file
                    totalsize--; //after you erase you -1 from size
                    i = 0; //after you -1 from size, you reset i
                }
            }

            //sort the files within directory
            sort(contents.begin(), contents.end(), compareTwo);

            //print the files to standard out
            printVec(contents);
        }
        else{
            files_dirs = getFiles_Dirs(argv);
            ls_multiple(files_dirs);
        }
    }
    else{ //is there a ls with flags and maybe files or dir
        for(int x = 0; x < argc; ++x){
            if(*(argv[x]) == dash){ //grabs flags
                flags_ = argv[x]; //put the cstring in a string
                flags_.erase(flags_.begin()); //erase the '-' at the beginning

                //go through each flag_ and compare with the vector of flags
                for(unsigned int i = 0 ; i < flags_.size(); ++i){
                    for(unsigned int j = 0; j < flags.size(); ++j){
                        if(flags_.at(i) == flags.at(j)){
                            if(flags.at(j) == 'a'){
                                isFlag_a = true;
                                if(isFlag_a) cout << "We have a!" << endl;
                            }
                            else if(flags.at(j) == 'l'){
                                isFlag_l = true;
                                if(isFlag_l) cout << "We have l!" << endl;
                            }
                            else if(flags.at(j) == 'R'){
                                isFlag_R = true;
                                if(isFlag_R) cout << "We have R!" << endl;
                            }
                        }
                    }
                }
            }
        }
    }

    //files_dirs = getFiles_Dir(argv, );
//  --------------------------------------------------------------------

    return 0;
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbConnectedComponentSegmentation.h"

#include <iostream>
#include "otbCommandLineArgumentParser.h"

#include <iostream>
#include <iomanip>
#include <fstream>
#include "itkExceptionObject.h"
#include "otbImage.h"
#include "otbMath.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"

#include "otbParser.h"

#include "itkRelabelComponentImageFilter.h"
#include <itkLabelMap.h>
#include <otbLabelMapWithAdjacency.h>

//#include <itkLabelImageToLabelMapFilter.h>
#include <otbLabelImageToLabelMapWithAdjacencyFilter.h>

#include <itkScalarToRGBPixelFunctor.h>
#include <itkUnaryFunctorImageFilter.h>
#include "otbConnectedComponentMuParserFunctor.h"
#include <itkConnectedComponentFunctorImageFilter.h>

#include "otbMaskMuParserFilter.h"

#include <otbAttributesMapLabelObject.h>
#include <itkAttributeLabelObject.h>
#include "otbBandsStatisticsAttributesLabelMapFilter.h"
#include <itkStatisticsLabelObject.h>
#include <itkShapeLabelMapFilter.h>
#include <otbShapeAttributesLabelMapFilter.h>
#include <itkLabelObject.h>
#include "itkLabelImageToShapeLabelMapFilter.h"
#include <iostream>
#include "otbLabelObjectOpeningMuParserFilter.h"

//#include <itkLabelMapToRGBImageFilter.h>
#include <itkLabelMapToLabelImageFilter.h>

#include "otbVectorDataProjectionFilter.h"
#include "otbVectorData.h"
#include "otbVectorDataFileWriter.h"
#include "itkPreOrderTreeIterator.h"

#include <otbLabelMapToVectorDataFilter.h>

namespace otb
{

  typedef float InputPixelType;
  const unsigned int     Dimension = 2;

  typedef itk::RGBPixel<unsigned char>   RGBPixelType;
  typedef otb::Image<RGBPixelType, 2>    RGBImageType;
  typedef otb::ImageFileWriter<RGBImageType>                RGBWriterType;
  //conected component typedef
  typedef otb::VectorImage<InputPixelType,  Dimension>         InputVectorImageType;
  typedef otb::ImageFileReader<InputVectorImageType>           ReaderType;

  typedef otb::Image<unsigned int, Dimension>                   InputMaskImageType;

  typedef otb::ImageFileReader<InputMaskImageType>             MaskReaderType;

  typedef otb::Image<unsigned int, Dimension>                   OutputImageType;
  typedef otb::Image<unsigned int, Dimension>                   LabelImageType;

  typedef otb::ImageFileWriter<OutputImageType>                                                   WriterType;
  typedef Functor::ConnectedComponentMuParserFunctor<InputVectorImageType::PixelType>  FunctorType;

  typedef itk::ConnectedComponentFunctorImageFilter<InputVectorImageType, OutputImageType, FunctorType, InputMaskImageType> ConnectedComponentFilterType;

  // Labelization
  typedef itk::RelabelComponentImageFilter<LabelImageType, LabelImageType> RelabelComponentFilterType;
  typedef otb::AttributesMapLabelObject<unsigned int, Dimension, double>     AttributesMapLabelObjectType;
  typedef itk::AttributeLabelObject<unsigned int, Dimension, double>   AttributesLabelObjectType;

  typedef otb::LabelMapWithAdjacency<AttributesMapLabelObjectType>                             AttributesLabelMapType;
  typedef otb::LabelImageToLabelMapWithAdjacencyFilter<LabelImageType, AttributesLabelMapType>            LabelImageToLabelMapFilterType;

  typedef otb::BandsStatisticsAttributesLabelMapFilter<AttributesLabelMapType, InputVectorImageType> RadiometricLabelMapFilterType;
  typedef otb::ShapeAttributesLabelMapFilter<AttributesLabelMapType>  ShapeLabelMapFilterType;
  typedef itk::ShapeLabelObject<unsigned int, Dimension>                            ShapeLabelObjectType;
  typedef itk::LabelObject<unsigned int, Dimension>                            LabelObjectType;
  typedef itk::LabelMap<ShapeLabelObjectType>                                     ShapeLabelMapType;

  typedef itk::LabelImageToShapeLabelMapFilter<OutputImageType, ShapeLabelMapType> LabelImageToShapeLabelMapFilterType;

  // colored label image typedef
  typedef itk::Functor::ScalarToRGBPixelFunctor<unsigned long>  ColorMapFunctorType;
  typedef itk::UnaryFunctorImageFilter<OutputImageType, RGBImageType, ColorMapFunctorType> ColorMapFilterType;

  // mask typedef
  typedef otb::MaskMuParserFilter<InputVectorImageType, OutputImageType>  MaskMuParserFilterType;

  typedef otb::LabelObjectOpeningMuParserFilter<AttributesLabelMapType>                      LabelObjectOpeningFilterType;

  typedef itk::LabelMapToLabelImageFilter<AttributesLabelMapType, OutputImageType> LabelMapToLabelImageFilterType;

  /** Vector data handling */
  typedef otb::VectorData<double, 2>                                  VectorDataType;
  typedef VectorDataType::Pointer                                    VectorDataPointerType;
  typedef otb::VectorDataFileWriter<VectorDataType>                  VectorDataFileWriterType;
  typedef VectorDataFileWriterType::Pointer                          VectorDataFileWriterPointerType;

  typedef otb::LabelMapToVectorDataFilter<AttributesLabelMapType, VectorDataType>                          LabelMapToVectorDataFilterType;

  int ConnectedComponentSegmentation::Describe(ApplicationDescriptor* descriptor)
  {
    descriptor->SetName("Connected Component Segmentation");
    descriptor->SetDescription("Connected Component Segmentation, which take mathematical formula as an Neighborhood thresholding criteria.");
    descriptor->AddInputImage();
    descriptor->AddOutputImage();
    descriptor->AddOption("OutputShapeFileName", "Output Shape file name",
                          "outshape", 1, true, ApplicationDescriptor::FileName);
    descriptor->AddOption("Expression", "Formula",
                          "expression", 1, true, ApplicationDescriptor::String);
    descriptor->AddOption("MinSize", "Min object size (area in pixel)",
                          "minsize", 1, false, ApplicationDescriptor::Real);
    descriptor->AddOption("InputImageMaskFileName", "Image for mask computation",
                        "inmask", 1, false, ApplicationDescriptor::InputImage);
    descriptor->AddOption("MaskExpression", "Mask expression (only if support image is given)",
                          "maskexpression", 1, false, ApplicationDescriptor::String);
    descriptor->AddOption("OBIAExpression", "OBIA Mu Parser expression",
                          "OBIAexpression", 1, true, ApplicationDescriptor::String);
    descriptor->AddOption("IntermediateOutput", "Save intermediate output",
                          "dbg", 0, false, ApplicationDescriptor::Boolean);

    return EXIT_SUCCESS;
  }

  int ConnectedComponentSegmentation::Execute(otb::ApplicationOptionsResult* parseResult)
  {
    ConnectedComponentFilterType::Pointer connected = ConnectedComponentFilterType::New();

    // Read the input image
    std::string inFileName = parseResult->GetParameterString("InputImage");

    ReaderType::Pointer reader = ReaderType::New();
    reader->SetFileName(inFileName);
    reader->UpdateOutputInformation();
    connected->SetInput(reader->GetOutput());

    MaskReaderType::Pointer maskReader;
    ReaderType::Pointer maskImageReader;
    MaskMuParserFilterType::Pointer maskFilter;

    WriterType::Pointer writer = WriterType::New();
    // Read the mask image
    if(parseResult->IsOptionPresent("MaskExpression"))
      {
      std::string maskFileName;
      if(parseResult->IsOptionPresent("InputImageMaskFileName"))
        {
        maskFileName = parseResult->GetParameterString("InputImageMaskFileName");
        }
      else // use image input
        {
        maskFileName = inFileName;
        }

      maskImageReader = ReaderType::New();
      maskImageReader->SetFileName(maskFileName);

      maskImageReader->UpdateOutputInformation();

      maskFilter= MaskMuParserFilterType::New();
      maskFilter->SetInput(maskImageReader->GetOutput());

      std::string maskexpression = parseResult->GetParameterString("MaskExpression");

      maskFilter->SetExpression(maskexpression);
      maskFilter->UpdateOutputInformation();
      if(parseResult->IsOptionPresent("IntermediateOutput"))
        {

        writer->SetInput(maskFilter->GetOutput());
        writer->SetFileName("binaryMask.tif");
        writer->Update();
        }

      connected->SetMaskImage(maskFilter->GetOutput());
      }
    else
      if(parseResult->IsOptionPresent("InputImageMaskFileName"))
        {
        std::string maskFileName = parseResult->GetParameterString("InputImageMaskFileName");

        maskReader = MaskReaderType::New();
        maskReader->SetFileName(maskFileName);
        maskReader->UpdateOutputInformation();
        connected->SetMaskImage(maskReader->GetOutput());

        }

    // set up formula for connected component segmentation
    std::string expression = parseResult->GetParameterString("Expression");

    connected->GetFunctor().SetExpression(expression);
    connected->Update();

    if(parseResult->IsOptionPresent("IntermediateOutput"))
      {
      writer->SetInput(connected->GetOutput());
      writer->SetFileName("connectedComponentLabelImage.tif");
      writer->Update();
      }

    // relabel component
    double minObjectSize;
    if(parseResult->IsOptionPresent("MinSize"))
      minObjectSize = parseResult->GetParameterDouble("MinSize");
    else
      minObjectSize=2;

    // relabel connected component output
    RelabelComponentFilterType::Pointer relabel = RelabelComponentFilterType::New();
    relabel->SetInput(connected->GetOutput());
    relabel->SetMinimumObjectSize(minObjectSize);

    // debug output
    if(parseResult->IsOptionPresent("IntermediateOutput"))
      {
      ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New();
      colormapper->SetInput(relabel->GetOutput());
      RGBWriterType::Pointer RGBwriter = RGBWriterType::New();
      RGBwriter->SetInput(colormapper->GetOutput());
      RGBwriter->SetFileName("RGBLabeledImage.tif");
      RGBwriter->Update();
      }

    // step 3 transformation into labelmap and object characterization

    //Attributes computation
    // LabelImage to Label Map transformation
    LabelImageToLabelMapFilterType::Pointer labelImageToLabelMap = LabelImageToLabelMapFilterType::New();
    labelImageToLabelMap->SetInput(relabel->GetOutput());
    labelImageToLabelMap->SetBackgroundValue(0);

    // intermediate step : Fusion
    // TBD

    // shape attributes computation
    ShapeLabelMapFilterType::Pointer shapeLabelMapFilter = ShapeLabelMapFilterType::New();
    shapeLabelMapFilter->SetInput(labelImageToLabelMap->GetOutput());
    shapeLabelMapFilter->SetReducedAttributeSet(false);

    // band stat attributes computation
    RadiometricLabelMapFilterType::Pointer radiometricLabelMapFilter
    = RadiometricLabelMapFilterType::New();

    radiometricLabelMapFilter->SetInput(shapeLabelMapFilter->GetOutput());
    radiometricLabelMapFilter->SetNumberOfThreads(1);

    radiometricLabelMapFilter->SetFeatureImage(reader->GetOutput());
    radiometricLabelMapFilter->SetReducedAttributeSet(false);
    radiometricLabelMapFilter->Update();

    AttributesLabelMapType::Pointer AttributesLabelMap;

    AttributesLabelMap=radiometricLabelMapFilter->GetOutput();
    //AttributesLabelMap->SetAdjacencyMap(labelImageToLabelMap->GetOutput()->GetAdjacencyMap());

    // TODO JGU  code clean is necessary
    // DBG OUTPUT
    //unsigned int nb_obj=AttributesLabelMap->GetNumberOfLabelObjects();
    //std::cout<<"number of attributes map label objects : "<<nb_obj<<std::endl;

    // step 4 OBIA Filtering using shape and radiometric object characteristics

    std::string OBIAexpression = parseResult->GetParameterString("OBIAExpression");

    LabelObjectOpeningFilterType::Pointer opening= LabelObjectOpeningFilterType::New();
    opening->SetExpression(OBIAexpression);
    opening->SetInput( radiometricLabelMapFilter->GetOutput());
    opening->Update();

    LabelMapToLabelImageFilterType::Pointer labelMapToLabelImage = LabelMapToLabelImageFilterType::New();
    labelMapToLabelImage->SetInput(opening->GetOutput());
    labelMapToLabelImage->Update();

    if(parseResult->IsOptionPresent("IntermediateOutput"))
      {

      ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New();
      colormapper->SetInput(labelMapToLabelImage->GetOutput());

      RGBWriterType::Pointer RGBwriter = RGBWriterType::New();
      RGBwriter->SetInput(colormapper->GetOutput());
      RGBwriter->SetFileName("RGBOpeningOutput.tif");
      RGBwriter->Update();

      // removed object dbg output
      LabelMapToLabelImageFilterType::Pointer labelMapToLabelImageRemoved = LabelMapToLabelImageFilterType::New();

      labelMapToLabelImageRemoved->SetInput(opening->GetOutput(1));
      labelMapToLabelImageRemoved->Update();
      //ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New();
      colormapper->SetInput(labelMapToLabelImageRemoved->GetOutput());

      //RGBWriterType::Pointer RGBwriter = RGBWriterType::New();
      RGBwriter->SetInput(colormapper->GetOutput());
      RGBwriter->SetFileName("RGBOpeningRemovedObjects.tif");
      RGBwriter->Update();

      }

    //TODO JGU  : code cleanup is needed

    //std::cout<<" new object number after opening : "<<opening->GetOutput()->GetNumberOfLabelObjects()<<std::endl;
    //std::cout<<" removed objects : "<<opening->GetOutput(1)->GetNumberOfLabelObjects()<<std::endl;

    //step 5 : Vectorization

    LabelMapToVectorDataFilterType::Pointer labelMapToVectorDataFilter = LabelMapToVectorDataFilterType::New();
    labelMapToVectorDataFilter->SetInput(opening->GetOutput());
    labelMapToVectorDataFilter->Update();

    VectorDataPointerType vectorData=labelMapToVectorDataFilter->GetOutput();

    // Instantiate the vdwriter
    std::string vdoutFilename = parseResult->GetParameterString("OutputShapeFileName");

    VectorDataFileWriterPointerType vdwriter = VectorDataFileWriterType::New();
    vdwriter->SetInput(vectorData);
    vdwriter->SetFileName(vdoutFilename);
    vdwriter->Update();

    // Instantiate the writer
    std::string outFilename = parseResult->GetParameterString("OutputImage");

    writer->SetInput(labelMapToLabelImage->GetOutput());
    writer->SetFileName(outFilename);
    writer->Update();

    return EXIT_SUCCESS;
  }
}

<commit_msg>STYLE Code cleanup<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbConnectedComponentSegmentation.h"

#include <iostream>
#include "otbCommandLineArgumentParser.h"

#include <iostream>
#include <iomanip>
#include <fstream>
#include "itkExceptionObject.h"
#include "otbImage.h"
#include "otbMath.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"

#include "otbParser.h"

#include "itkRelabelComponentImageFilter.h"
#include <itkLabelMap.h>
#include <otbLabelMapWithAdjacency.h>

#include <otbLabelImageToLabelMapWithAdjacencyFilter.h>

#include <itkScalarToRGBPixelFunctor.h>
#include <itkUnaryFunctorImageFilter.h>
#include "otbConnectedComponentMuParserFunctor.h"
#include <itkConnectedComponentFunctorImageFilter.h>

#include "otbMaskMuParserFilter.h"

#include <otbAttributesMapLabelObject.h>
#include <itkAttributeLabelObject.h>
#include "otbBandsStatisticsAttributesLabelMapFilter.h"
#include <itkStatisticsLabelObject.h>
#include <itkShapeLabelMapFilter.h>
#include <otbShapeAttributesLabelMapFilter.h>
#include <itkLabelObject.h>
#include "itkLabelImageToShapeLabelMapFilter.h"
#include <iostream>
#include "otbLabelObjectOpeningMuParserFilter.h"

#include <itkLabelMapToLabelImageFilter.h>

#include "otbVectorDataProjectionFilter.h"
#include "otbVectorData.h"
#include "otbVectorDataFileWriter.h"

#include <otbLabelMapToVectorDataFilter.h>

namespace otb
{

typedef float InputPixelType;
const unsigned int Dimension = 2;

typedef itk::RGBPixel<unsigned char> RGBPixelType;
typedef otb::Image<RGBPixelType, 2>  RGBImageType;

typedef otb::VectorImage<InputPixelType, Dimension> InputVectorImageType;
typedef otb::ImageFileReader<InputVectorImageType> ReaderType;

typedef otb::Image<unsigned int, Dimension> InputMaskImageType;

typedef otb::ImageFileReader<InputMaskImageType> MaskReaderType;

typedef otb::Image<unsigned int, Dimension> OutputImageType;
typedef otb::Image<unsigned int, Dimension> LabelImageType;

typedef otb::ImageFileWriter<OutputImageType> WriterType;
typedef otb::ImageFileWriter<RGBImageType>    RGBWriterType;

typedef Functor::ConnectedComponentMuParserFunctor<InputVectorImageType::PixelType> FunctorType;

typedef itk::ConnectedComponentFunctorImageFilter<InputVectorImageType, LabelImageType, FunctorType, InputMaskImageType>
    ConnectedComponentFilterType;

// Labelization
typedef itk::RelabelComponentImageFilter<LabelImageType, LabelImageType> RelabelComponentFilterType;
typedef otb::AttributesMapLabelObject<unsigned int, Dimension, double>   AttributesMapLabelObjectType;
typedef itk::AttributeLabelObject<unsigned int, Dimension, double>       AttributesLabelObjectType;

typedef otb::LabelMapWithAdjacency<AttributesMapLabelObjectType> AttributesLabelMapType;
typedef otb::LabelImageToLabelMapWithAdjacencyFilter<LabelImageType, AttributesLabelMapType>
    LabelImageToLabelMapFilterType;

typedef otb::BandsStatisticsAttributesLabelMapFilter<AttributesLabelMapType, InputVectorImageType>
    RadiometricLabelMapFilterType;
typedef otb::ShapeAttributesLabelMapFilter<AttributesLabelMapType> ShapeLabelMapFilterType;
typedef itk::ShapeLabelObject<unsigned int, Dimension>             ShapeLabelObjectType;
typedef itk::LabelObject<unsigned int, Dimension>                  LabelObjectType;
typedef itk::LabelMap<ShapeLabelObjectType>                        ShapeLabelMapType;

typedef itk::LabelImageToShapeLabelMapFilter<OutputImageType, ShapeLabelMapType> LabelImageToShapeLabelMapFilterType;

// colored label image typedef
typedef itk::Functor::ScalarToRGBPixelFunctor<unsigned long> ColorMapFunctorType;
typedef itk::UnaryFunctorImageFilter<LabelImageType, RGBImageType, ColorMapFunctorType> ColorMapFilterType;

// mask typedef
typedef otb::MaskMuParserFilter<InputVectorImageType, OutputImageType> MaskMuParserFilterType;

typedef otb::LabelObjectOpeningMuParserFilter<AttributesLabelMapType>            LabelObjectOpeningFilterType;
typedef itk::LabelMapToLabelImageFilter<AttributesLabelMapType, OutputImageType> LabelMapToLabelImageFilterType;

/** Vector data handling */
typedef otb::VectorData<double, Dimension>          VectorDataType;
typedef VectorDataType::Pointer                     VectorDataPointerType;
typedef otb::VectorDataFileWriter<VectorDataType>   VectorDataFileWriterType;
typedef VectorDataFileWriterType::Pointer           VectorDataFileWriterPointerType;

typedef otb::LabelMapToVectorDataFilter<AttributesLabelMapType, VectorDataType> LabelMapToVectorDataFilterType;

int ConnectedComponentSegmentation::Describe(ApplicationDescriptor* descriptor)
{
  descriptor->SetName("Connected Component Segmentation");
  descriptor->SetDescription(
                             "Connected Component Segmentation, which take mathematical formula as an Neighborhood thresholding criteria.");
  descriptor->AddOption("InputImageFileName", "Input frame file name", "in", 1, true, ApplicationDescriptor::FileName);
  descriptor->AddOption("OutputFileName", "Output file name", "out", 1, true, ApplicationDescriptor::FileName);
  descriptor->AddOption("OutputShapeFileName", "Output Shape file name", "outshape", 1, true,
                        ApplicationDescriptor::FileName);
  descriptor->AddOption("Expression", "Formula", "expression", 1, true, ApplicationDescriptor::String);
  descriptor->AddOption("MinSize", "Min object size (area in pixel)", "minsize", 1, false, ApplicationDescriptor::Real);
  descriptor->AddOption("InputImageMaskFileName", "Image for mask computation", "inmask", 1, false,
                        ApplicationDescriptor::FileName);
  descriptor->AddOption("MaskExpression", "Mask expression (only if support image is given)", "maskexpression", 1,
                        false, ApplicationDescriptor::String);
  descriptor->AddOption("OBIAExpression", "OBIA Mu Parser expression", "OBIAexpression", 1, true,
                        ApplicationDescriptor::String);
  descriptor->AddOption("IntermediateOutput", "Save intermediate output", "dbg", 0, false,
                        ApplicationDescriptor::Boolean);

  return EXIT_SUCCESS;
}

int ConnectedComponentSegmentation::Execute(otb::ApplicationOptionsResult* parseResult)
{
  ConnectedComponentFilterType::Pointer connected = ConnectedComponentFilterType::New();

  // Read the input image
  std::string inFileName = parseResult->GetParameterString("InputImageFileName");

  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(inFileName);
  reader->UpdateOutputInformation();
  connected->SetInput(reader->GetOutput());

  MaskReaderType::Pointer maskReader;
  ReaderType::Pointer maskImageReader;
  MaskMuParserFilterType::Pointer maskFilter;

  WriterType::Pointer writer = WriterType::New();
  // Read the mask image
  if (parseResult->IsOptionPresent("MaskExpression"))
    {
    std::string maskFileName;
    if (parseResult->IsOptionPresent("InputImageMaskFileName"))
      {
      maskFileName = parseResult->GetParameterString("InputImageMaskFileName");
      }
    else // use image input
      {
      maskFileName = inFileName;
      }

    maskImageReader = ReaderType::New();
    maskImageReader->SetFileName(maskFileName);

    maskImageReader->UpdateOutputInformation();

    maskFilter = MaskMuParserFilterType::New();
    maskFilter->SetInput(maskImageReader->GetOutput());

    std::string maskexpression = parseResult->GetParameterString("MaskExpression");

    maskFilter->SetExpression(maskexpression);
    maskFilter->UpdateOutputInformation();
    if (parseResult->IsOptionPresent("IntermediateOutput"))
      {

      writer->SetInput(maskFilter->GetOutput());
      writer->SetFileName("binaryMask.tif");
      writer->Update();
      }

    connected->SetMaskImage(maskFilter->GetOutput());
    }
  else
    if (parseResult->IsOptionPresent("InputImageMaskFileName"))
      {
      std::string maskFileName = parseResult->GetParameterString("InputImageMaskFileName");

      maskReader = MaskReaderType::New();
      maskReader->SetFileName(maskFileName);
      maskReader->UpdateOutputInformation();
      connected->SetMaskImage(maskReader->GetOutput());

      }

  // set up formula for connected component segmentation
  std::string expression = parseResult->GetParameterString("Expression");

  connected->GetFunctor().SetExpression(expression);
  connected->Update();

  if (parseResult->IsOptionPresent("IntermediateOutput"))
    {
    writer->SetInput(connected->GetOutput());
    writer->SetFileName("connectedComponentLabelImage.tif");
    writer->Update();
    }

  // relabel component
  double minObjectSize;
  if (parseResult->IsOptionPresent("MinSize"))
    minObjectSize = parseResult->GetParameterDouble("MinSize");
  else minObjectSize = 2;

  // relabel connected component output
  RelabelComponentFilterType::Pointer relabel = RelabelComponentFilterType::New();
  relabel->SetInput(connected->GetOutput());
  relabel->SetMinimumObjectSize(minObjectSize);

  // debug output
  if (parseResult->IsOptionPresent("IntermediateOutput"))
    {
    ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New();
    colormapper->SetInput(relabel->GetOutput());
    RGBWriterType::Pointer RGBwriter = RGBWriterType::New();
    RGBwriter->SetInput(colormapper->GetOutput());
    RGBwriter->SetFileName("RGBLabeledImage.tif");
    RGBwriter->Update();
    }

  // step 3 transformation into labelmap and object characterization

  //Attributes computation
  // LabelImage to Label Map transformation
  LabelImageToLabelMapFilterType::Pointer labelImageToLabelMap = LabelImageToLabelMapFilterType::New();
  labelImageToLabelMap->SetInput(relabel->GetOutput());
  labelImageToLabelMap->SetBackgroundValue(0);

  // intermediate step : Fusion
  // TBD

  // shape attributes computation
  ShapeLabelMapFilterType::Pointer shapeLabelMapFilter = ShapeLabelMapFilterType::New();
  shapeLabelMapFilter->SetInput(labelImageToLabelMap->GetOutput());
  shapeLabelMapFilter->SetReducedAttributeSet(false);

  // band stat attributes computation
  RadiometricLabelMapFilterType::Pointer radiometricLabelMapFilter = RadiometricLabelMapFilterType::New();

  radiometricLabelMapFilter->SetInput(shapeLabelMapFilter->GetOutput());
  radiometricLabelMapFilter->SetFeatureImage(reader->GetOutput());
  radiometricLabelMapFilter->SetReducedAttributeSet(false);
  radiometricLabelMapFilter->Update();

  AttributesLabelMapType::Pointer AttributesLabelMap;
  AttributesLabelMap = radiometricLabelMapFilter->GetOutput();
  //AttributesLabelMap->SetAdjacencyMap(labelImageToLabelMap->GetOutput()->GetAdjacencyMap());

  // step 4 OBIA Filtering using shape and radiometric object characteristics

  std::string OBIAexpression = parseResult->GetParameterString("OBIAExpression");

  LabelObjectOpeningFilterType::Pointer opening = LabelObjectOpeningFilterType::New();
  opening->SetExpression(OBIAexpression);
  opening->SetInput(radiometricLabelMapFilter->GetOutput());
  opening->Update();

  LabelMapToLabelImageFilterType::Pointer labelMapToLabelImage = LabelMapToLabelImageFilterType::New();
  labelMapToLabelImage->SetInput(opening->GetOutput());
  labelMapToLabelImage->Update();

  if (parseResult->IsOptionPresent("IntermediateOutput"))
    {
    ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New();
    colormapper->SetInput(labelMapToLabelImage->GetOutput());

    RGBWriterType::Pointer RGBwriter = RGBWriterType::New();
    RGBwriter->SetInput(colormapper->GetOutput());
    RGBwriter->SetFileName("RGBOpeningOutput.tif");
    RGBwriter->Update();

    // removed object dbg output
    LabelMapToLabelImageFilterType::Pointer labelMapToLabelImageRemoved = LabelMapToLabelImageFilterType::New();

    labelMapToLabelImageRemoved->SetInput(opening->GetOutput(1));
    labelMapToLabelImageRemoved->Update();
    //ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New();
    colormapper->SetInput(labelMapToLabelImageRemoved->GetOutput());

    //RGBWriterType::Pointer RGBwriter = RGBWriterType::New();
    RGBwriter->SetInput(colormapper->GetOutput());
    RGBwriter->SetFileName("RGBOpeningRemovedObjects.tif");
    RGBwriter->Update();

    }

  //step 5 : Vectorization

  LabelMapToVectorDataFilterType::Pointer labelMapToVectorDataFilter = LabelMapToVectorDataFilterType::New();
  labelMapToVectorDataFilter->SetInput(opening->GetOutput());
  labelMapToVectorDataFilter->Update();

  VectorDataPointerType vectorData = labelMapToVectorDataFilter->GetOutput();

  // Instantiate the vdwriter
  std::string vdoutFilename = parseResult->GetParameterString("OutputShapeFileName");

  VectorDataFileWriterPointerType vdwriter = VectorDataFileWriterType::New();
  vdwriter->SetInput(vectorData);
  vdwriter->SetFileName(vdoutFilename);
  vdwriter->Update();

  // Instantiate the writer
  std::string outFilename = parseResult->GetParameterString("OutputFileName");

  writer->SetInput(labelMapToLabelImage->GetOutput());
  writer->SetFileName(outFilename);
  writer->Update();

  return EXIT_SUCCESS;
}
}

<|endoftext|>