OpenGL 练习05 3D Recursive Triangles

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值