请帮我用OpenGL写一个有光照环境的旋转茶壶的代码
时间: 2024-05-11 21:20:04 浏览: 104
好的,以下是一个基于OpenGL的旋转茶壶的代码,包含了光照环境:
```c++
#include <GL/glut.h>
#include <cmath>
// 定义三维向量结构体
struct Vector3
{
GLfloat x, y, z;
};
// 法向量计算函数
void calculateNormal(Vector3 p1, Vector3 p2, Vector3 p3, Vector3& normal)
{
Vector3 v1, v2;
v1.x = p2.x - p1.x;
v1.y = p2.y - p1.y;
v1.z = p2.z - p1.z;
v2.x = p3.x - p1.x;
v2.y = p3.y - p1.y;
v2.z = p3.z - p1.z;
normal.x = v1.y * v2.z - v1.z * v2.y;
normal.y = v1.z * v2.x - v1.x * v2.z;
normal.z = v1.x * v2.y - v1.y * v2.x;
}
void display()
{
static GLfloat angle = 0.0f;
// 设置光源位置
GLfloat lightPosition[] = { 0.0f, 0.0f, 1.0f, 0.0f };
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// 设置相机位置
gluLookAt(0.0f, 0.0f, 10.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
// 设置旋转角度
glRotatef(angle, 1.0f, 1.0f, 1.0f);
// 绘制茶壶
GLfloat ambient[] = { 0.0f, 0.0f, 1.0f, 1.0f };
GLfloat diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
GLfloat specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
GLfloat shininess[] = { 50.0f };
glMaterialfv(GL_FRONT, GL_AMBIENT, ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, specular);
glMaterialfv(GL_FRONT, GL_SHININESS, shininess);
glutSolidTeapot(2.0f);
// 开启光照
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
// 设置光源参数
glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
// 设置环境光
GLfloat ambientLight[] = { 0.2f, 0.2f, 0.2f, 1.0f };
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientLight);
// 绘制法向量
glColor3f(1.0f, 0.0f, 0.0f);
glBegin(GL_LINES);
for (int i = 0; i < 325; i += 3)
{
Vector3 p1, p2, p3, normal;
p1.x = glutSolidTeapot_data[i];
p1.y = glutSolidTeapot_data[i + 1];
p1.z = glutSolidTeapot_data[i + 2];
p2.x = glutSolidTeapot_data[i + 3];
p2.y = glutSolidTeapot_data[i + 4];
p2.z = glutSolidTeapot_data[i + 5];
p3.x = glutSolidTeapot_data[i + 6];
p3.y = glutSolidTeapot_data[i + 7];
p3.z = glutSolidTeapot_data[i + 8];
calculateNormal(p1, p2, p3, normal);
glVertex3f(p1.x, p1.y, p1.z);
glVertex3f(p1.x + normal.x, p1.y + normal.y, p1.z + normal.z);
}
glEnd();
// 关闭光照
glDisable(GL_LIGHTING);
// 更新旋转角度
angle += 0.5f;
if (angle >= 360.0f)
{
angle = 0.0f;
}
glutSwapBuffers();
}
void reshape(int width, int height)
{
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, (float)width / height, 0.1f, 100.0f);
}
void init()
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glShadeModel(GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glEnable(GL_NORMALIZE);
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(640, 480);
glutCreateWindow("Rotating Teapot with Lighting");
glutDisplayFunc(display);
glutReshapeFunc(reshape);
init();
glutMainLoop();
return 0;
}
```
注:该代码使用了OpenGL的固定函数管线,不过仍然可以用现代OpenGL的着色器来实现。
阅读全文