Problem displaying lines in 2D


I'm new to openGL and just trying to learn the basics. I'm having trouble with 2D images. I created a little function that displays several lines on the screen in 2D. i.e. I left the z-coordinate of glVertex3f set to 0. What I found is that every time I display the lines at different position on the screen, they change slightly.

For example, in the following, three lines are drawn on the screen, and depending on the “x” parameter, the location is different.
glBegin( GL_LINES );
glVertex3f( 0.0f + x, 0.3f, 0.0f );
glVertex3f( 0.0f + x, 0.0f, 0.0f );
glVertex3f( 0.0f + x, 0.3f, 0.0f );
glVertex3f( -0.05f + x, 0.0f, 0.0f );
glVertex3f( 0.0f + x, 0.3f, 0.0f );
glVertex3f( 0.05f + x, 0.0f, 0.0f );

Every time I change the value of “x”, the image is slightly different. i.e. some of the pixels in the line are drawn a little differently.

How can I drawn a 2D image such that it looks exactly the same every time it is displayed? I have tried setting up the view with:
glColor3f(1.0f, 0.85f, 0.35f);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();

I have also tried changing these settings but no matter what I do, I still have the same problem.


What you experience is called subpixel accuracy. It’s proper behavior and you cannot disable it. If you want line to look always the same then always increase x by such value that will move the line by exactly 1 pixel. Still there is no guarantee it will work because of floating-point precision limitations.

If you want to further understand this behavior then just take a piece of paper and draw a grid on it - every grid cell is one pixel on screen.
Then draw two identical lines half a pixel away from each other - see which “pixels” they go through - it will not be the same shape.

Hi k_szczech,

Thanks for your help. Your explanation of subpixel accuracy explanation is excellent. It really helps me understand how it works.