您的位置:首页 > 运维架构

OpenGL 练习05 3D Recursive Triangles

2014-05-11 10:12 239 查看
#include<gl/glut.h>
#include<math.h>
#include<stdlib.h>

//a point data type
typedef GLfloat point3[3];

//initial triangle
point3 v[] = {{-1.0, -1.0, -1.0}, {1.0, -1.0, -1.0}, {0.0, 1.0, -1.0}, {0.0, 0.0, 1.0}};
int n = 10000;//number of recursive steps

void triangle(point3 a, point3 b, point3 c)
{
glVertex2fv(a);
glVertex2fv(b);
glVertex2fv(c);
}

void divide_triangle(point3 a, point3 b, point3 c, int k)
{
point3 ab = {(a[0]+b[0])/2, (a[1]+b[1])/2};
point3 ac = {(a[0]+c[0])/2, (a[1]+c[1])/2};
point3 bc = {(b[0]+c[0])/2, (b[1]+c[1])/2};
if (k > 0)
{
divide_triangle(a, ab, ac, k-1);
divide_triangle(b, ab, bc, k-1);
divide_triangle(c, ac, bc, k-1);
}
else {
triangle(a, b, c);
}
}

void tetra(point3 a, point3 b, point3 c, point3 d, int k)
{
glColor3f(0.0, 1.0, 1.0);
divide_triangle(a, b, c, k);
glColor3f(1.0, 1.0, 0.0);
divide_triangle(a, c, d, k);
glColor3f(0.0, 0.0, 1.0);
divide_triangle(a, d, b, k);
glColor3f(0.0, 1.0, 0.0);
divide_triangle(b, d, c, k);
}

void renderScene(void)
{
glClearColor(1.0, 1.0, 1.0, 0.0);//注意事项:要在glClear之前设置color!

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// 清除屏幕及深度缓存
glLoadIdentity();// 重置当前的模型观察矩阵

/*glBegin(GL_TRIANGLES);//绘制线段
glColor3f(0.0f, 0.0f, 1.0f);//设置顶点颜色
glVertex2fv(v[0]);
glVertex2fv(v[1]);
glVertex2fv(v[2]);
glEnd();*/

glBegin(GL_TRIANGLES);
glColor3f(0.0f, 0.0f, 1.0f);//设置顶点颜色
tetra(v[0], v[1], v[2], v[3], 6);
glEnd();

/*
glBegin(GL_POINTS);
for (int i=0; i<n; i++){
int j = rand() % 3;
point2 p1;
p1[0] = (p0[0] + v[j][0]) / 2;
p1[1] = (p0[1] + v[j][1]) / 2;
p0[0] = p1[0];
p0[1] = p1[1];
glVertex2fv(p1);
//drawPoint(p1);
}
glEnd();
*/

glutSwapBuffers();//当窗口模式为双缓存时,此函数的功能就是把后台缓存的内容交换到前台显示。当然,只有单缓存时,使用它的功能跟用glFlush()一样。而使用双缓存是为了把完整图画一次性显示在窗口上,或者是为了实现动画。
}

int main(int argc, char *argv[])
{
glutInit(&argc, argv);//初始化GLUT
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);//设置图形显示模式。GLUT_DEPTH:使用深度缓存;GLUT_DOUBLE:使用双缓存;
glutInitWindowPosition(100, 100);//设置窗口显示位置
glutInitWindowSize(600,600);//设置窗口大小
glutCreateWindow("Sierpinski");//创建带标题的窗口
glutDisplayFunc(renderScene);//为当前窗口设置显示回调函数
glutMainLoop();//进入GLUT事件处理循环
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: