Tutorial -4
IS F311
Computer Graphics
Date: 23/09/14
Objective: Understanding how to build an interactive graphics application. In this tutorial we will see
how one can use the mouse for interacting with the scene.
Type in the following code and see the result:
#include <windows.h>
#include <GL/glut.h>
//struct to store (x,y)
struct GLintPoint{
GLint x,y;
};
//corners of a rectangle
GLintPoint corner[2];
//global variables
bool selected = false;
bool closed = false;
int screenwidth = 640, screenheight = 480;
//setting up projection matrix
void myinit(void)
{
glClearColor(0.7, 0.7, 0.7, 0.0); /* gray background */
glMatrixMode(GL_PROJECTION);
/* In World coordinates: */
glLoadIdentity();
gluOrtho2D( 0, screenwidth, 0, screenheight);
glMatrixMode(GL_MODELVIEW);
}
//The display function
void myDisplay(){
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glColor3f(1.0,1.0,1.0);
if(selected){
glBegin(GL_QUADS);
glVertex2i(corner[0].x,corner[0].y);
glVertex2i(corner[0].x,corner[1].y);
glVertex2i(corner[1].x,corner[1].y);
glVertex2i(corner[1].x,corner[0].y);
glEnd();
}
glutSwapBuffers();
}
void myMouse(int button, int state, int x, int y)
{
if(button== GLUT_LEFT_BUTTON && state == GLUT_DOWN){
corner[0].x = x;
corner[0].y = screenheight - y;
selected = true;
closed = false;
}
if(button== GLUT_RIGHT_BUTTON && state == GLUT_DOWN){
corner[1].x = x;
corner[1].y = screenheight - y;
closed = true;
}
glutPostRedisplay();
}
void myPassiveMotion(int x, int y)
{
if(!closed){
corner[1].x = x;
corner[1].y = screenheight - y;
}
glutPostRedisplay();
}
int main(int argc, char** argv)
{
glutInit(&argc,argv);
glutInitWindowSize( screenwidth, screenheight );
glutInitWindowPosition(0,0);
glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE);
glutCreateWindow("Rubber Rect Demo"); /*window title*/
myinit();
/* set attributes */
glutMouseFunc(myMouse);
glutDisplayFunc(myDisplay);
/* tell OpenGL main loop what */
glutPassiveMotionFunc(myPassiveMotion);
glutMainLoop();
/* pass control to the main loop*/
return 0;
}