OpenGL绘制茶壶实体模型,设置简化光照模型,设置黄铜材质,鼠标移动控制茶壶旋转
时间: 2023-07-27 14:27:55 浏览: 115
好的,下面是代码示例:
```
#include <GL/glut.h>
GLdouble teapotSize = 1.5;
GLfloat lightPosition[] = {0.0f, 5.0f, 5.0f, 1.0f};
GLfloat lightAmbient[] = {0.0f, 0.0f, 0.0f, 1.0f};
GLfloat lightDiffuse[] = {1.0f, 1.0f, 1.0f, 1.0f};
GLfloat lightSpecular[] = {1.0f, 1.0f, 1.0f, 1.0f};
GLfloat matAmbient[] = {0.329412f, 0.223529f, 0.027451f, 1.0f};
GLfloat matDiffuse[] = {0.780392f, 0.568627f, 0.113725f, 1.0f};
GLfloat matSpecular[] = {0.992157f, 0.941176f, 0.807843f, 1.0f};
GLfloat matShininess[] = {27.8974f};
int lastX, lastY;
bool rotate = false;
void init() {
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glShadeModel(GL_FLAT);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
glLightfv(GL_LIGHT0, GL_AMBIENT, lightAmbient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, lightDiffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, lightSpecular);
glMaterialfv(GL_FRONT, GL_AMBIENT, matAmbient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, matDiffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, matSpecular);
glMaterialfv(GL_FRONT, GL_SHININESS, matShininess);
}
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glTranslatef(0.0f, -1.0f, 0.0f);
glRotatef(-90.0f, 1.0f, 0.0f, 0.0f);
if (rotate) {
glRotatef((float) (glutGet(GLUT_ELAPSED_TIME) / 10.0), 0.0f, 1.0f, 0.0f);
}
glutSolidTeapot(teapotSize);
glPopMatrix();
glutSwapBuffers();
}
void reshape(int width, int height) {
glViewport(0, 0, (GLsizei) width, (GLsizei) height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0, (GLfloat) width / (GLfloat) height, 1.0, 20.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0, 0.0, -5.0);
}
void mouse(int button, int state, int x, int y) {
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
lastX = x;
lastY = y;
rotate = true;
} else if (button == GLUT_LEFT_BUTTON && state == GLUT_UP) {
rotate = false;
}
}
void motion(int x, int y) {
if (rotate) {
int deltaX = x - lastX;
int deltaY = y - lastY;
lastX = x;
lastY = y;
glRotatef(deltaX, 0.0, 1.0, 0.0);
glRotatef(deltaY, 1.0, 0.0, 0.0);
glutPostRedisplay();
}
}
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("Teapot");
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMouseFunc(mouse);
glutMotionFunc(motion);
glutMainLoop();
return 0;
}
```
这段代码实现了使用 OpenGL 绘制茶壶实体模型,并设置简化光照模型和黄铜材质。同时,通过鼠标移动控制茶壶旋转。具体实现细节可以参考代码注释。
阅读全文