开发者

Creating a fixed light source that preserves its world coordinates

I want to put a light in the scene that is fixed at a certain spot. Here's what the OpenGL site has to say about this:

How can I make my light stay fixed relative to my scene? How can I put a light in the corner and make开发者_开发知识库 it stay there while I change my view?

As your view changes, your ModelView matrix also changes. This means you'll need to respecify the light position, usually at the start of every frame. A typical application will display a frame with the following pseudocode:

  • Set the view transform.
  • *Set the light position //glLightfv(GL_LIGHT_POSITION,…)*
  • Send down the scene or model geometry.
  • Swap buffers.

If your light source is part of a light fixture, you also may need to specify a modeling transform, so the light position is in the same location as the surrounding fixture geometry.

So I added this to the paintGL() function.

glMatrixMode(GL_MODELVIEW);
glPushMatrix();
gluLookAt(0.0, 5.0, 0.0,
    0.0, 0.0, 0.0,
    0.0, 1.0, 0.0);
GLfloat l0pos[] = {0.0, 0.0, 0.0, 1.0};
glLightfv(GL_LIGHT0, GL_POSITION, l0pos);
glPopMatrix();

It seems okay when I'm standing still, but when I move the camera's eye position or the camera's center position, the light flickers. What am I doing wrong?


Update2: I ended up using this code, but I'm still having issues. The light no longer moves, but its position isn't accurate. The matrix on top of the stack is the matrix generated by a gluLookAt command that represents the camera position.

glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef(xCoordinate, yCoordinate, zCoordinate);
GLfloat lpos[] = {0.0, 0.0, 0.0, w};
glLightfv(GL_LIGHT0, GL_POSITION, lpos);
glPopMatrix();


I'm not entirely sure if this is what is causing your symptoms, however:

glMatrixMode(GL_MODELVIEW);
glPushMatrix();
gluLookAt(0.0, 5.0, 0.0,
    0.0, 0.0, 0.0,
    0.0, 1.0, 0.0);

There are a few things you would want to look at here.

First, according to the documentation online, gluLookAt multiplies the matrix at the top of the stack by a camera transformation matrix, rather than setting it (furthermore, glPushMatrix preserves the current matrix). For this reason, it's a good idea to make sure the current matrix is the identity matrix before doing your camera transformation. A push/pop is generally enough but if you call gluLookAt after or "within" any other transformation, bad things can happen.

Second, you'll want to use your actual camera coordinates, so that GL can transform the light position properly. Otherwise the light won't appear to move with the scene geometry. I'd suggest doing gluLookAt once, then transforming lights and drawing your geometry all in one go before popping the camera transformation matrix again. That way you can be certain that your lights and geometry stay together as expected.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜