用opengl写一个球体
时间: 2023-12-29 15:46:37 浏览: 49
下面是一个使用OpenGL库,创建并渲染一个球体的示例代码:
```c++
#include <GL/glut.h>
#include <cmath>
const int SLICES = 50;
const int STACKS = 50;
void drawSphere(double r, int slices, int stacks) {
for (int i = 0; i < slices; ++i) {
double lat0 = M_PI * (-0.5 + (double) (i - 1) / slices);
double z0 = sin(lat0);
double zr0 = cos(lat0);
double lat1 = M_PI * (-0.5 + (double) i / slices);
double z1 = sin(lat1);
double zr1 = cos(lat1);
glBegin(GL_QUAD_STRIP);
for (int j = 0; j <= stacks; ++j) {
double lng = 2 * M_PI * (double) (j - 1) / stacks;
double x = cos(lng);
double y = sin(lng);
glNormal3f(x * zr0, y * zr0, z0);
glVertex3f(x * zr0 * r, y * zr0 * r, z0 * r);
glNormal3f(x * zr1, y * zr1, z1);
glVertex3f(x * zr1 * r, y * zr1 * r, z1 * r);
}
glEnd();
}
}
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0, 0, -10);
glColor3f(0.5, 0.5, 1.0);
drawSphere(1.0, SLICES, STACKS);
glFlush();
glutSwapBuffers();
}
void reshape(int w, int h) {
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, (float) w / h, 0.1, 100);
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(640, 480);
glutCreateWindow("OpenGL Sphere");
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}
```
这个程序使用了OpenGL中的球体绘制函数,根据球体半径、经度和纬度的数量来绘制球体。在程序中,我们先使用`glMatrixMode`函数设置投影矩阵,然后设置模型矩阵,绘制球体。最后使用`glutMainLoop`函数进入主循环,等待用户操作。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)