Opengl创建几何实体——四棱锥和立方体

//#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();
}

 

运行效果:

 

转载于:https://www.cnblogs.com/herd/p/8371607.html

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值