OpenGL lighting problem when rotating the camera

Newbie picture Newbie · Dec 16, 2009 · Viewed 8k times · Source

I draw buildings in my game world, i shade them with the following code:

GLfloat light_ambient[] = {0.0f, 0.0f, 0.0f, 1.0f};
GLfloat light_position[] = {135.66f, 129.83f, 4.7f, 1.0f};

glShadeModel(GL_SMOOTH);

glEnable(GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL);

glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);

glColorMaterial(GL_FRONT, GL_AMBIENT);

It works nicely.

But when i start flying in the world, the lighting reacts to that as if the world was an object that is being rotated. So the lights changes when my camera angle changes.

How do i revert that rotation? so the lighting would think that i am not actually rotating the world, and then i could make my buildings have static shading which would change depending on where the sun is on the sky.

Edit: here is the rendering code:

int DrawGLScene()
{

    // stuff

    glLoadIdentity();

    glRotatef(XROT, 1.0f, 0.0f, 0.0f);
    glRotatef(YROT, 0.0f, 1.0f, 0.0f);
    glRotatef(ZROT, 0.0f, 0.0f, 1.0f);

    glTranslatef(-XPOS, -YPOS, -ZPOS);

    // draw world
}

Answer

Ron Warholic picture Ron Warholic · Dec 16, 2009

http://www.opengl.org/resources/faq/technical/lights.htm

See #18.050

In short, you need to make sure you're defining your light position in the right reference frame and applying the appropriate transforms each frame to keep it where you want it.

Edit:

With the removal of the fixed function pipeline in OpenGL 3.1 the code and answer here are deprecated. The correct answer now is to pass your light position(s) into your vertex/fragment shaders and perform your shading using that position in world space. This calculation varies based on the type of lighting you're doing (PBR, phong, deferred etc).