4

OpenGL: no light for a simple glut cube

Hi, i'm trying to study lights in opengl and glut but I have problems quite early. I have this code for making a lighted cube in a custom position with custom camera setting:

void testApp::draw(){
    static float amb[] =  {0.4, 0.4, 0.4, 0.0};
    static float dif[] =  {1.0, 1.0, 1.0, 0.0};
    
    float light_diffuse[] = {1.0, 0.0, 1.0, 1.0}; 
    float light_position[] = {-1.0, 1.0, 1.0, 0.0}; // i tried a lot of positions here!
    
    // set camera
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(0, 200, 1200, 0,0,0, 0,1,0);

    // set lights
    glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
    glLightfv(GL_LIGHT0, GL_POSITION, light_position);
    glEnable(GL_LIGHT0);
    glEnable(GL_LIGHT1);
    glEnable(GL_LIGHTING);
    glMaterialfv(GL_FRONT, GL_AMBIENT, amb);
    glMaterialfv(GL_FRONT, GL_DIFFUSE, dif);

    // draw scene
    ofScale(50, 50, 50);
    glPushMatrix();

    glutSolidCube(2);

    // close everything
    glPopMatrix();
    glDisable(GL_LIGHT0);
    glDisable(GL_LIGHT1);
    glDisable(GL_LIGHTING); }

I see only a black cube, no light, I think the problem is the light position, I've tried a lot of positions but it does not work: black cube.

insumity
  • 5,311
  • 8
  • 36
  • 64
nkint
  • 11,513
  • 31
  • 103
  • 174

1 Answers1

5

You are really far away from your cube. Make it smaller and move it closer. Alternatively, change your lighting like this:

float light_diffuse[] = {100.0, 0.0, 100.0, 100.0}; 
float light_position[] = {-100.0, 100.0, 1.0, 0.0};

You will hardly see any light effects on a cube. Consider using a teapot.

Piotr Praszmo
  • 17,928
  • 1
  • 57
  • 65
  • ok great, it works perfectly. but i didn't understand why: i had no translations so the cube (now a teapot ^__^) is at 0,0,0 in world coordinate.. light positions should be near this point.. or not? – nkint Jun 18 '11 at 14:14
  • The center is at (0,0,0) but the faces are 100 units away from center. Your light wasn't strong enough to affect them. – Piotr Praszmo Jun 18 '11 at 14:18
  • @Banthar `light_diffuse` sets the color which is in range `0.0` to `1.0` right? The position change is the key in your answer. – Lekensteyn Nov 29 '13 at 21:27