Search code examples
c++openglperspectivelighting

OpenGL perspective and lighting not working?


EDIT: A few people have said to use glNormal3f() to solve my lighting problem, but I researched and implemented that just now and it didn't change anything at all.

I'm kind of new to OpenGL so I guess I'm doing something wrong, but I followed the examples in the Red Book as closely as I could and I just can't figure out what's wrong, so I figured I'd try and ask you guys.

I have two problems. One is that, even though I'm sure I'm using glFrustum correctly, it still renders an orthographic scene, and it renders objects that are both in front of and behind the camera for some reason. The other is that, even though I'm pretty sure I'm doing this lighting right (because I followed the example in the book), it's lighting the scene with a uniform color, no shading or anything. Here's my code:

#include "GraphicsManager.h"
#include <GL/gl.h>

void GraphicsManager::initialize () {
  fx = 0;
  fy = 0;  
  glEnable (GL_LIGHTING);
  glEnable (GL_LIGHT0);
  glDepthFunc (GL_LEQUAL);
  glEnable (GL_DEPTH_TEST);
  glViewport (0, 0, 800, 600);
  glMatrixMode (GL_PROJECTION);
  glLoadIdentity ();
  glFrustum (-1.0, 1.0, -1.0, 1.0, 1.5, 20.0);
  glMatrixMode (GL_MODELVIEW);
  glLoadIdentity ();
}

int GraphicsManager::draw (std::vector<float> buttoninfo) {
  // changing light_position makes no difference
  GLfloat light_position[] = { 1.0, 1.0, 1.0, 1.0 };
  int i, j, k;
  fx += buttoninfo[0];
  fy += buttoninfo[1];
  glClearColor (0.0, 0.0, 0.0, 1.0);
  glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glColor3f (0.5, 0.5, 0.8);
  glLoadIdentity ();
  glLightfv (GL_LIGHT0, GL_POSITION, light_position);�
  glRotatef (buttoninfo[3], 1.0, 0.0, 0.0);
  glRotatef (buttoninfo[2], 0.0, 1.0, 0.0);
  glTranslatef (-fx, 0, -fy);
  for (i = 0; i < 5; i ++) {
  for (j = 0; j < 5; j ++) {
  for (k = 0; k < 5; k ++) {
    glPushMatrix ();
    glTranslatef (i, j, k);
    glBegin (GL_TRIANGLE_FAN);
      glVertex3f (0.0, 0.5, 0.0);
      glVertex3f (-0.5, -0.5, -0.5);
      glVertex3f (-0.5, -0.5, 0.5);
      glVertex3f (0.5, -0.5, 0.5);
      glVertex3f (0.5, -0.5, -0.5);
      glVertex3f (-0.5, -0.5, -0.5);
    glEnd ();
    glPopMatrix ();
  }
  }
  }
  glFlush ();
  return (int)buttoninfo[5];
}

Can you help me figure out what's wrong? Thanks in advance.


Solution

  • You are drawing the elements around the origin (0,0,0) but you don't move the "camera" at the begining. so your are looking from the origin point at the scene, which is inside your elements.

    try if

    glMatrixMode (GL_MODELVIEW);
    glLoadIdentity ();
    glTranslate3f(0, 0, -10); 
    

    works to fix it

    and for Perspective rendering consider using gluPerspective. http://www.opengl.org/sdk/docs/man/xhtml/gluPerspective.xml