PDA

View Full Version : paint program by GLUT



computeach
10-30-2014, 11:18 AM
I am going to develop paint program by GLUT

I used glutMotionFunc to read x and y position

then draw the path by GL_LINE_STRIP

but the program is not work

where is error in follow code?





#include <windows.h>
#include <GL/glut.h>

bool writeFlag=false;
float posX,posY;


void initGL()
{
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
}


void idle()
{
glutPostRedisplay();
}


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


glBegin(GL_LINE_STRIP);
while(writeFlag)
{ glVertex2f(posX, posY); }
glEnd();

glutSwapBuffers();
}


void reshape(GLsizei width, GLsizei height)
{

if (height == 0) height = 1; // To prevent divide by 0
GLfloat aspect = (GLfloat)width / (GLfloat)height;


glViewport(0, 0, width, height);


glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (width >= height)
{

gluOrtho2D(-1.0 * aspect, 1.0 * aspect, -1.0, 1.0);
}
else
{

gluOrtho2D(-1.0, 1.0, -1.0 / aspect, 1.0 / aspect);
}
}

void keyboard(unsigned char key, int x, int y)
{
switch (key)
{
case '1':
writeFlag=true;
break;
case '2':
writeFlag=false;
break;
case 27:
exit(0);
break;
}
}
void Motion(int x, int y)
{

posX=x;
posY=y;
}


int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Simple Paint program by GLUT");
glutInitWindowSize(640, 480);
glutInitWindowPosition(50, 50);
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMotionFunc(Motion); // mouse click and move
glutIdleFunc(idle);
initGL();
glutMainLoop();
return 0;
}

sueyllam
10-30-2014, 10:27 PM
First you used deprecated openGL pre programmable shaders. I suggest writing it using opengl3.3 or greater and use shaders. That would be challenging.
Now why nothing gets drawn, the mouse coordinates are in screen coordinates which are outside the region -1,1 you are displaying, You either scale the mouse coordinates to the -1,1 region or make your clipping volume same as screen dimensions.

carsten neumann
10-31-2014, 02:55 AM
Additionally you have an endless loop in your display function (once writeFlag is true). GLUT implements (like pretty much any GUI toolkit) an event driven system where certain functions (e.g. display, motion, keyboard) are called in response to events from the system. So you need to restructure your program in a way that you record mouse positions in the motion function and use those recorded positions in the display display to draw your entire scene from scratch every time display is called.
Redrawing everything is quite normal for graphics applications, because in many cases it is too difficult to figure out which pixels have been invalidated and which objects need to be redrawn to update just those pixels, so the conservative approach is taken and everything is redrawn.