Sierpinski镂垫是一个有趣的图形,在分形几何中是重要的研究对象。可以参看wiki. 本文通过两种方式,递归和非递归来展示如何绘制Sierpinski镂垫。 Sierphiski镂垫的构造函数如下:
++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
#include <GL\glut.h> #include <stdlib.h> void reshape(int w,int h) { glViewport(0,0,w,h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); GLfloat nrange = 10; if(w>h) { glOrtho(-nrange*w/h,nrange*w/h,-nrange,nrange,-nrange,nrange); } else { glOrtho(-nrange,nrange,-nrange*h/w,nrange*h/w,-nrange,nrange); } glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0,0,5,0,0,0,0,1,0); } void renderScene() { glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glColor3f(1.0,0.3,0.3); GLfloat vertices[3][3] = \{\{0.0,5.0,0.0},{-5.0,-5.0,0.0},{5.0,-5.0,0.0\}\}; //平面z里任意一个三角形 GLfloat p[3] = {0.0,0.0,0.0}; //三角形内任意一点 int j,k; int rand(); glBegin(GL_POINTS); for(k=0; k<5000; k++) { j = rand()%3; //从0,1,2中随机选择一个点 p[0] = (p[0]+vertices[j][0])/2; p[1] = (p[1]+vertices[j][1])/2; glVertex3fv(p); //显示新的点 } glEnd(); glutSwapBuffers(); } int main(int argc, char** argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE); glutInitWindowSize(640,480); glutInitWindowPosition(100,100); glutCreateWindow("Sierphiski triangle"); glutReshapeFunc(reshape); glutDisplayFunc(renderScene); glutMainLoop(); } |
另一种方法是采用递归的形式来绘制三角形,更改的代码部分如下:
++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
void triangle(GLfloat *a,GLfloat *b,GLfloat *c) { glVertex3fv(a); glVertex3fv(b); glVertex3fv(c); } void divide_triangle(GLfloat *a,GLfloat *b, GLfloat *c,int k) { GLfloat ab[2],ac[2],bc[2]; int j=0; if(k>0) { for(j=0;j<2;j++) { ab[j] = (a[j]+b[j])/2; ac[j] = (a[j]+c[j])/2; bc[j] = (b[j]+c[j])/2; } divide_triangle(a,ab,ac,k-1); divide_triangle(c,ac,bc,k-1); divide_triangle(b,ab,bc,k-1); } else triangle(a,b,c); } void renderScene() { glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); GLfloat vertices[3][3] = { {0.0,5.0,0.0},{-5.0,-5.0,0.0},{5.0,-5.0,0.0} }; //平面z里任意一个三角形 int n = 5; glColor3f(1.0,0.3,0.3); glBegin(GL_TRIANGLES); divide_triangle(vertices[0],vertices[1],vertices[2],n); glEnd(); glutSwapBuffers(); } |
原文:http://www.cnblogs.com/cupcoffee/p/3561590.html