Computer Graphics – 11. Mouse Click Polyline

[wpdm_package id=’1235′]
Sample Input –Write a program that creates a polyline using a series of mouse clicks. Right click should clear the screen. The window should have resize abilities.
Sample Output –Mouse_Click_Polyline

[sourcecode lang=”cpp”]
#include<GL/glut.h>

struct base{
GLint x;
GLint y;
}b[2];
int flag=0;

GLint screen_height=600;
GLint screen_width=600;

void free_dots(void){
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
}

void line(GLint x1, GLint y1, GLint x2, GLint y2){
glBegin(GL_LINE_STRIP);
glColor3f(1.0,0.0,1.0);
glVertex2d(x1,y1);
glVertex2d(x2,y2);
glEnd();
glFlush();
}

void reshape(GLsizei w, GLsizei h){
screen_width=w;
screen_height=h;

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,w,0,h);
glViewport(0,0,w,h);
}

void poly(GLint x, GLint y){
b[flag].x=x;
b[flag].y=y;
flag+=1;
if(flag==2){
line(b[0].x,b[0].y,b[1].x,b[1].y);
b[0].x=b[1].x;
b[0].y=b[1].y;
b[1].x=0;
b[1].y=0;
flag-=1;
}
}
void my_mouse(int button, int state, int x, int y){

if((button==GLUT_LEFT_BUTTON) && (state==GLUT_DOWN)){
poly(x,screen_height – y);
}
else if((button==GLUT_RIGHT_BUTTON)&&(state==GLUT_DOWN)){
flag=0;
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
}
}
void init(){
glClearColor(1.0f,1.0f,1.0f,0.0f);
glColor3f(0.0f,0.0f,0.0f);
glPointSize(8);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,screen_width,0,screen_height);
}

int main(int argc,char **argv){
glutInit(&argc,argv);
glutInitWindowSize(600,600);
glutInitWindowPosition(60,60);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutCreateWindow("Mouse_Click_Polyline");

glutDisplayFunc(free_dots);
glutMouseFunc(my_mouse);
glutReshapeFunc(reshape);

init();

glutMainLoop();
return 0;
}
[/sourcecode]

To compile the above program in ubuntu terminal –
# g++ -lGL -lGLU -lglut Mouse_Click_Polyline.cpp
# ./a.out

Leave a Reply

Your email address will not be published. Required fields are marked *