PDA

View Full Version : need some help with mouse event/callbacks



Numberator
01-16-2010, 07:45 AM
Hi I am new to openGL, just picked it up recently and I am trying to do a program window which draws a small square wherever the mouse cursor clicks. Below is the code which I came up with and I dont know why it wont draw the square when I click. Maybe I got the logic wrong inside?


GLint winWidth, winHeight;

void init()
{
glClearColor(1.0f, 1.0f, 1.0f, 1.0f); //clears background colour to white
glClear(GL_COLOR_BUFFER_BIT); //clear the colour buffer to the colour previously set in glClearColor

}


void renderScene()
{
glFlush();
}


void winResize(GLsizei width, GLsizei height)
{
GLfloat aspectRatio;
winWidth = width;
winHeight = height;


if(height == 0)//prevent zero division
height = 1;

//set viewport to window dimensions
glViewport(0, 0, width, height);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();

aspectRatio = (GLfloat)width/(GLfloat)height;

if(width <= height)
glOrtho(-100.0, 100.0, -100.0/aspectRatio, 100.0/aspectRatio, 1.0, -1.0);

else
glOrtho(-100.0*aspectRatio, 100.0*aspectRatio, -100.0, 100.0, 1.0, -1.0);


glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

}

void mouseCallback(int button, int state, int x, int y)
{
if(button == GLUT_LEFT_BUTTON &amp;&amp; state == GLUT_DOWN)
{
y = winHeight-y; /* invert y position */
glColor3ub(static_cast<char>(rand()%256), static_cast<char>(rand()%256), static_cast<char>(rand()%256)); /* a random color */
glBegin(GL_POLYGON);
glVertex2f(x+3, y+3);
glVertex2f(x-3, y+3);
glVertex2f(x-3, y-3);
glVertex2f(x+3, y-3);
glEnd();

glutPostRedisplay();
}

}


int main()
{
glutInitDisplayMode(GLUT_RGB);
glutCreateWindow("Assessment 1");

glutDisplayFunc(renderScene);
glutReshapeFunc(winResize);

init();
glutMouseFunc(mouseCallback);
glutMainLoop();

return 0;
}

Numberator
01-17-2010, 03:10 AM
hmm am I posting this is the wrong part of the forum?

AGL_Music
01-17-2010, 01:41 PM
GLUT always calls back to "RenderScene" in order to draw stuff, you are trying to draw stuff inside of the input handling routine.

Draw the rectangle inside of the RenderScene routine. Only change it's position in the input handler.

Store the position in global variables.