#define GLUT_DISABLE_ATEXIT_HACK
#include<stdlib.h>
#include <gl/glut.h>
float angle=0;
/** 顶点数组 */
static GLfloat vertices[] = { 1.0f,1.0f,-1.0f,
-1.0f,1.0f,-1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
-1.0f,-1.0f, 1.0f,
-1.0f,-1.0f,-1.0f,
1.0f,-1.0f,-1.0f};
/** 顶点索引数组 */
static GLbyte indexs[] =
{
0,1,2,3,/**< 顶面索引 */
5,6,7,4,/**< 底面索引 */
0,3,4,7,/**< 右面索引 */
5,4,3,2,/**< 前面索引 */
2,1,6,5,/**< 左面索引 */
7,0,1,6};/**< 后面索引 */
/** 顶点颜色数组 */
static GLfloat colors[] = {
1.f,0.f,0.f,
0.f,1.f,0.f,
0.f,0.f,1.f,
1.f,1.f,0.f,
1.f,0.f,1.f,
0.f,1.f,1.f,
0.f,0.f,0.f,
0.f,1.f,1.f};
//初始化OpenGL
void DrawCube()
{
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBegin(GL_QUADS);
for (int i = 0; i < 6; i++)
{
glArrayElement(indexs[4 * i]);
glArrayElement(indexs[4 * i + 1]);
glArrayElement(indexs[4 * i + 2]);
glArrayElement(indexs[4 * i + 3]);
}
glEnd();
glPushMatrix();
glTranslatef(-4.5f, -1.5f, -7.0f);
glRotatef(angle, 0.0f, 1.0f, 1.0f);
glColor3f(0.3f, 0.7f, 0.6f);
glutSolidSphere(1, 17, 9);
glPopMatrix();
}
void init(void)
{
glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
glClearDepth(1.0f);
glDepthFunc(GL_LEQUAL);
glEnable(GL_DEPTH_TEST);
/** 启用顶点数组和颜色数组 */
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
/** 指定数组中的数据 */
glVertexPointer(3,GL_FLOAT,0,vertices);
glColorPointer(3,GL_FLOAT,0,colors);
glShadeModel(GL_FLAT);
}
//主要的绘制过程
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);//清除颜色缓存
glLoadIdentity();
glTranslatef(0,0,-5);
glRotatef(angle,1,1,1);
glColor3f(1.0,0,0);
DrawCube();
glFlush();
}
//在窗口改变大小时调用
void reshape(int w, int h){
glViewport(0, 0, w, h);//设置视口
glMatrixMode(GL_PROJECTION);//设置当前为投影变换模式
glLoadIdentity();//用单位矩阵替换当前变换矩阵
gluPerspective(80, (float)w/h, 3, 100.0);//设置正交投影视图体
glMatrixMode (GL_MODELVIEW);
glLoadIdentity();
}
void TimerFunction(int value)
{
angle+=10;
if(angle==360)
angle=0;
// Redraw the scene with new coordinates
glutPostRedisplay();
glutTimerFunc(500,TimerFunction, 1);
}
void main( )
{
glutCreateWindow("Basic");//设置窗口标题
init();//初始化OpenGL
glutDisplayFunc(display);//设置显示回调函数
glutReshapeFunc(reshape);//设置reshape回调函数
glutTimerFunc(500,TimerFunction, 1);
glutMainLoop();//进入主循环
}
Opengl顶点数组绘制旋转立方体与球
最新推荐文章于 2022-09-04 22:06:37 发布