tux Drawing Line With DDA Algorithm using OpenGL in C++

The code is based on the popularly used dda line drawing algorithm.It picks up two point from the window and change the color of pixels which are closest to vectorial line between them.

changing color of closest pixels to vectorial line

#include <GL/glut.h>
#include <math.h>
#include <time.h>
#define W 512
#define H 512
int points[2][2];
int point_count=0;
void initialize(){
	glClearColor( 0.0, 0.0, 0.0, 0.0);//set background color to black
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(0, W,0,H);
}

void setPixel(int x, int y){	//change color of a pixel
	glColor3f(1, 1, 1);
	y=H-y;
	glBegin(GL_POINTS);
	glVertex2f(x,y);
	glEnd();
}

void LineWithDDA(int x0, int y0, int x1, int y1) {//DDa line algorithm
    int dy = y1 - y0;
    int dx = x1 - x0;
    int steps,i;
    float xinc,yinc,x=x0,y=y0;
    if( fabs(dx) > fabs(dy)){
        steps=fabs(dx);
    }else{
          steps=fabs(dy);
    }
    xinc=(float) dx/ (float) steps;
    yinc=(float) dy/ (float) steps;
    setPixel(round(x), round(y));
    for(i=0;i<steps;i++){
         x+=xinc;
         y+=yinc;
         setPixel(round(x), round(y));
    }
    glutSwapBuffers();
}
void lineSegment(){
    glClear(GL_COLOR_BUFFER_BIT);
    glutSwapBuffers();
    LineWithDDA(W/2,0,W/2,H);
    LineWithDDA(0,H/2,W,H/2);
}
void Control(int button, int state, int x, int y){

  // Respond to mouse button presses.
  // If button1 pressed, mark this state so we know in motion function.

  if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
    {
  			setPixel(x,y);
  			if(point_count<1){
					points[0][0]=x;
					points[0][1]=y;
					point_count++;
			}else{
					points[1][0]=x;
	 			    points[1][1]=y;
			        use_dda(points[0][0],points[0][1],points[1][0],points[1][1]);
			        point_count=0;
			}
	      glutSwapBuffers();
    }
}
int main(int argc, char** argv) {
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
	glutInitWindowPosition(0,0);
	glutInitWindowSize(W,H);
	glutCreateWindow("OpenGL Mouse Function");
	initialize();
	glutMouseFunc(Control);
	glutDisplayFunc(lineSegment);
	glutMainLoop();
	return 0;
}
December 6, 2009
Posted in C++, OpenGL — TaZ @ 9:38 pm

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment