1. 程式人生 > >Opengl創建幾何實體——四棱錐和立方體

Opengl創建幾何實體——四棱錐和立方體

效果 oop body open glcolor3f buffer project correct 運行

//#include <gl\glut.h>
#include <GL\glut.h>
#include <iostream>

using namespace std;

float rtri;
float rquad;

GLfloat points0[5][3] = { {0,1,0},{-1,-1,1},{1,-1,1},{1,-1,-1},{-1,-1,-1} };
GLfloat points1[8][3] = { {1,1,-1},{-1,1,-1},{-1,1,1},{1,1,1},{1,-1,1},{-1,-1,1},{-1,-1,-1},{1,-1,-1} };
//四棱錐顏色
GLfloat Colors0[4][3] = { {1,0,0},{0,1,0},{0,0,1},{1,1,0} };
//立方體顏色
GLfloat Colors1[6][3] = { {0,1,0},{1,0.5,0},{1,0,0},{1,1,0},{0,0,1},{1,0,1} };

//四棱錐頂點序列號
int vertice0[4][3] = { {0,1,2},{0,2,3},{0,3,4},{0,4,1} };
//立方體頂點序列號
int vertice1[6][4] = { {0,1,2,3},{4,5,6,7},{3,2,5,4},{7,6,1,0},{2,1,6,5},{0,3,4,7} };

void InitGl(GLvoid)
{
  glShadeModel(GL_SMOOTH);
  glClearColor(1.0f,1.0f,1.0f,1.0f);
  glClearDepth(1.0f);

  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);
  glEnable(GL_COLOR_MATERIAL);

  glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST);
}

/*
創建棱錐體
*/
void CreatePyramid()
{
  glBegin(GL_TRIANGLES);
  for (int i=0;i<4;i++)
  {
    glColor3fv(Colors0[i]);
    for (int j=0;j<3;j++)
    {
      int VtxId = vertice0[i][j];
      glVertex3fv(points0[VtxId]);
    }
  }

glEnd();
  //構建底面
glBegin(GL_QUADS);
glColor3f(1.0f,1.0f,1.0f);

for (int k=0;k<4;k++)
  {
   glVertex3fv(points0[k]);
  }
glEnd();
}

/*
創建立方體
*/
void CreateCube()
{
glBegin(GL_QUADS);
for (int i=0;i<6;i++)
  {
   glColor3fv(Colors1[i]);
   for (int j=0;j<4;j++)
    {
     int VtxId = vertice1[i][j];
     glVertex3fv(points1[VtxId]);
    }
  }
  glEnd();
}

void display(void)
{
  glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
  glLoadIdentity();
  glPushMatrix();

  glTranslatef(-1.5f,0.0f,-6.0f);//平移至左側
  glRotatef(rtri,0.0f,1.0f,0.0f);//旋轉一個角度
  CreatePyramid();//創建三棱錐

  glLoadIdentity();//將矩陣歸一化回原樣
  glTranslatef(1.5f,0.0f,-6.0f);//平移至右側
  glRotatef(rquad,1.0f,0.0f,0.0f);//旋轉一個角度

  CreateCube();//創建立方體
  glPopMatrix();//
  
  rtri += 0.02f;//修改三角塔旋轉角度
  rquad -= 0.05f;//修改立方體旋轉角度
  glutSwapBuffers();
}

void reshape(int width,int height)
{
  if (height == 0)
  {
    height = 1;
  }
  
  glViewport(0,0,width,height);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();

  gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
}

void main(int argc,char** argv)
{
  glutInit(&argc,argv);
  glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE);
  glutInitWindowSize(600,460);

  glutCreateWindow("椎體和立方體");
  InitGl();
  glutDisplayFunc(display);

  glutReshapeFunc(reshape);
  glutIdleFunc(display);
  glutMainLoop();
}

運行效果:

技術分享圖片

Opengl創建幾何實體——四棱錐和立方體