简体   繁体   中英

Adding a Light Source to 3D objects in OpenGL

I was wondering if anyone could help me figure out how to add a light source to my 3D objects. I have four objects that are rotating and I want the light source to be at a fixed position, and I want to be able to see lighting on the object.

I tried doing this (********):

//*******Initializing the light position
GLfloat pos[] = {-2,4,5,1};

void display() {
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 
   glMatrixMode(GL_MODELVIEW);   

   //*******adding the light to the display method
   glLoadIdentity();
   glLightfv(GL_LIGHT0, GL_POSITION, pos);

   // rectangle
   glPushMatrix();
   glTranslatef(0.0f, 2.5f, -8.0f);  
   glRotatef(angleRectangle, 0.0f, 1.0f, 0.0f);  
   drawRectangle();
   glPopMatrix();

   //small cylinder
   glPushMatrix();
   glTranslatef(0.0f, 2.0f, -8.0f);  
   glRotatef(90, 1, 0, 0);
   glRotatef(anglePyramid, 0.0f, 0.0f, 1.0f);
   drawCylinder(0.2, 0.7);
   glPopMatrix();

   //big cylinder
   glPushMatrix();
   glTranslatef(0.0f, 1.5f, -8.0f); 
   glRotatef(90, 1, 0, 0);
   glRotatef(anglePyramid, 0.0f, 0.0f, 1.0f);
   drawCylinder(0.7, 2.7);
   glPopMatrix();

   //pyramid
   glPushMatrix();
   glTranslatef(0.0f, -2.2f, -8.0f);  
   glRotatef(180, 1, 0, 0);
   glRotatef(anglePyramid, 0.0f, 1.0f, 0.0f);  
   drawPyramid();
   glPopMatrix();

   glutSwapBuffers(); 

   anglePyramid += k * 0.2f;  //- is CW, + is CCW
   angleRectangle += -k * 0.2f;

}

//******* Then i added these to the main method
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);

However when I do this and I run the entire program, my objects turn gray, and at certain points in the rotation they turn white. And this isnt what I want. I want to keep my colorful objects, but I want to be able to see the light source on them.

Any help would be greatly appreciated. Also let me know if you need to see more of my code to figure out the issue. Thanks

When lighting ( GL_LIGHTING ) is enabled, then the color is taken from the material parameters ( glMaterial ).

If you still want to use the current color, the you have to enable GL_COLOR_MATERIAL and to set the color material paramters ( glColorMaterial ):

glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);

See also Basic OpenGL Lighting .


But note, that drawing by glBegin / glEnd sequences, the fixed function pipeline matrix stack and fixed function pipeline per vertex light model, is deprecated since decades. Read about Fixed Function Pipeline and see Vertex Specification and Shader for a state of the art way of rendering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM