nemesis
nemesis

Reputation: 263

can't render shape in openGL

I was trying to follow example codes to simply display a rectangle on a black background, but it didn't seem to be displaying. What I did was

    private static void initGL(){
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity(); 
    glOrtho(0,Display.getWidth(),0,Display.getHeight(),-1,1);
    glMatrixMode(GL_MODELVIEW);

    glDisable(GL_DEPTH_TEST); //2D mode

    glColor3f(0.5f, 0.0f, 1.0f); 
    glBegin(GL_QUADS); 
        glVertex2f(-0.75, 0.75);
        glVertex2f(-0.75, -0.75);
        glVertex2f(0.75, -0.75);
        glVertex2f(0.75, 0.75);
    glEnd();
}

It doesn't display anything on the screen except for a black background. Does anyone know what I might have done wrong? I'm using lwjgl in eclipse.

Upvotes: 1

Views: 249

Answers (2)

Jerome Baldridge
Jerome Baldridge

Reputation: 528

glVertex2f uses same size units as your glOrtho so unless your display width and height are in units of ones, like 10 or less, you may not see anything!

Upvotes: 0

Leo Izen
Leo Izen

Reputation: 4289

First things first: You only have to run the whole

glMatrixMode(GL_PROJECTION);
glLoadIdentity(); 
glOrtho(0,Display.getWidth(),0,Display.getHeight(),-1,1);
glMatrixMode(GL_MODELVIEW);

thing once during your program, probably shortly after you run Display.create().

Also, you're tessellating using the wrong vertices. You wrote

glVertex2f(-0.75, 0.75);
glVertex2f(-0.75, -0.75);
glVertex2f(0.75, -0.75);
glVertex2f(0.75, 0.75); 

which means draw a rectangle from (-0.75, -0.75) pixels to (0.75, 0.75) pixels. This is too small to be noticed. My guess is you assumed glVertex2f deals with fractions of the display width. It does not. glVertex2f deals with actual coordinates, it just allows fractional pixels, unlike glVertex2i (this is useful believe it or not, it helps with smoother animations). Something like

glVertex2f(100F, 100F);

places a vertex at (100, 100), and is effectively equivalent to

glVertex2i(100, 100);

Also, remember that negative pixels will be rendered off the screen, because OpenGL's origin of the coordinate system, (0, 0), is in the lower left and behaves like the first quadrant from the coordinate system in math class, not like the traditional computer coordinate system with (0, 0) in the upper left.

As for the the black background, LWJGL's Display has a black background by default, so it's recommended to draw a quad with your background color that covers the entire display width and height. One quad won't really affect your performance.

Upvotes: 1

Related Questions