Lighting rotating with objects

Apologies if my problem has already been answered, I had a look, but couldn’t find anything too similar. And I do need some hand holding here.

I’m rotating a cube, by loading in the vertices, translating, then rotating it to the correct position, using:-

Triangle3D cubeVertices[] = {…};
glVertexPointer(3, GL_FLOAT, 0, cubeVertices);
glTranslatef(xOffset, yOffset, xOffset);
glDrawArrays (GL_TRIANGLES, 0, noOfVertices);

(draw other cubes)

which works fine, until I decide to light it.

I am trying to light this cube from above, using

const GLfixed lightAmbient[] = {13107, 13107, 13107, 65535};
const GLfixed lightDiffuse[] = {65535, 65535, 65535, 65535};
const GLfixed matAmbient[] = {65535, 65535, 65535, 65535};
const GLfixed matDiffuse[] = {65535, 65535, 65535, 65535};
const GLfixed lightShininess = 20;
glMaterialxv(GL_FRONT_AND_BACK, GL_AMBIENT, matAmbient);
glMaterialxv(GL_FRONT_AND_BACK, GL_DIFFUSE, matDiffuse);
glMaterialx(GL_FRONT_AND_BACK, GL_SHININESS, lightShininess);
glLightxv(GL_LIGHT0, GL_AMBIENT, lightAmbient);
glLightxv(GL_LIGHT0, GL_DIFFUSE, lightDiffuse);

const GLfixed lightPosition[] = {0, 0, 2,1};
const GLfixed lightDirection[] = {0, 0, -1};

glLightxv(GL_LIGHT0, GL_POSITION, lightPosition);
glLightxv(GL_LIGHT0, GL_SPOT_DIRECTION, lightDirection);

where lightx, lighty represent the cubes position. This code comes before the model code, so I assume the camera stays above the correct position looking down.

What I want is for the cube to be constantly lit from the top (i.e if I increase the cubes rotation and we look down on the cube it is still bright) what I am getting at the moment is (it appears) is that the cube is rendered with the lighting, then rotated, whereas I want to cube to be rotated then rendered. I.E. as the cube is rotated at the moment the light rotates with the rotation, and I want the light to stay on top facing the camera.

I’m a complete newbie to OpenGL, but been playing about with the iPhone SDK, don’t know whether this has any effect on proceedings or not.

Many thanks for any help, and if this has been asked before, I deeply apologize.

If it’s GL 1.x without shaders then you are setting light position after your matrix has been modified. You have to set LightPosition before glPushMatrix and the rest of the stuff.

gluLookAt is also affecting matrices, so it must be called after you have set the light position.

I’d even recommend to set the light position only once during init if you can. But if it’s dynamic, note the order of those things.