Pages

Sunday, March 20, 2011

OpenGL - Dragging Points

/**
 * This program will do the particle generation. Then directs the
 * particles move as the mouse moves.
 * The hope of the program is that the particle will move to the
 * right direction if the particle position
 * lies in left side than the mouse cursor. And reciprocally.
 *
 * @author   : irfanudin ridho
 * @email    : irfan.ub@gmail.com
 * @version  : 1.0
 * @date     : March 20, 2011
 */


#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

#include <ctime>
#include <cstdlib>

#include <iostream>

using namespace std;
typedef struct{
    float x;
    float y;
}point;

#define nn 1000
point titik[nn];

// record the previous state
int prev_x = 0, prev_y=0;

void init(){
    glClearColor(1.0,1.0,1.0,1.0);
    gluOrtho2D(0,400,0,300);

    srand((unsigned)time(NULL));
    for(int i=0;i<nn;i++){
        titik[i].x = rand()/100;
        titik[i].y = rand()/100;
    }
}

void display(){
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(0.0,0.0,1.0);

    glPointSize(2.0);
    glBegin(GL_POINTS);
        for(int i=0; i<nn; i++){
            glVertex2f(titik[i].x, titik[i].y);
        }
    glEnd();

    glFlush();
}

void keyboard(unsigned char key, int x, int ){
    switch(key){
        case 27:
            exit(1);
            break;
    }
}


void motion(int x, int y){

    // horizontal dragging
    if(x > prev_x){
        for(int i=0; i<nn; i++){
            titik[i].x++;
        }
    }else if(x < prev_x){
         for(int i=0; i<nn; i++){
            titik[i].x--;
         }
    }

    // vertical dragging: reverse
    if(y < prev_y){
        for(int i=0; i<nn; i++){
            titik[i].y++;
        }
    }else if(y > prev_y){
        for(int i=0; i<nn; i++){
            titik[i].y--;
        }
    }

    prev_x = x;
    prev_y = y;

    glutPostRedisplay();
}

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

    system("color 2f");

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
    glutInitWindowSize(400,300);
    glutInitWindowPosition(200,100);
    glutCreateWindow("Simulation App");

    init();
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutMotionFunc(motion);

    glutMainLoop();

    return 0;
}

No comments:

Post a Comment