close
開學第一個功課就是印出平面的Gasket,這次的功課是印一個3D_Gasket而且做法也稍有不同。這次做法是取每個邊的中點,一直遞迴的做,再依序的印出面即可。
結果:
程式碼:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/******************** | |
Computer Graghics | |
Author:SHEN ZHI-XUN | |
Time:2016/11/2 | |
********************/ | |
#include <iostream> | |
#include <GL/glut.h> | |
#include <ctime> | |
using namespace std; | |
void triangle(GLfloat *a, GLfloat *b, GLfloat *c); | |
void tetra(GLfloat *a, GLfloat *b, GLfloat *c, GLfloat *d); | |
void divide_tetra(GLfloat *a, GLfloat *b, GLfloat *c, GLfloat *d, int m); | |
void display() { | |
glOrtho(-70, 70, -70, 70, -70, 70); | |
GLfloat v[4][3] = { {0,0,0},{25,50,10},{50,0,25},{25,10,25} }; | |
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); | |
glBegin(GL_TRIANGLES); | |
divide_tetra(v[0],v[1],v[2],v[3],3); | |
glEnd(); | |
glFlush(); | |
} | |
//畫平面三角形 | |
void triangle(GLfloat *a, GLfloat *b, GLfloat *c) { | |
glVertex3fv(a); | |
glVertex3fv(b); | |
glVertex3fv(c); | |
} | |
//畫四面體(由四個三角形形成),並給上不同顏色以便區別 | |
void tetra(GLfloat *a, GLfloat *b, GLfloat *c, GLfloat *d) { | |
GLfloat colors[4][3] = { {1,0,0},{0,1,0},{0,0,1},{1,1,0} }; | |
glColor3fv(colors[0]); | |
triangle(a, b, c); | |
glColor3fv(colors[1]); | |
triangle(a, c, d); | |
glColor3fv(colors[2]); | |
triangle(a, d, b); | |
glColor3fv(colors[3]); | |
triangle(b, d, c); | |
} | |
//取邊的中點 | |
void divide_tetra(GLfloat *a,GLfloat *b,GLfloat *c, GLfloat *d,int m) { | |
GLfloat mid[6][3]; | |
int j; | |
if (m > 0) { | |
for (j = 0; j < 3; j++) mid[0][j] = (a[j] + b[j]) / 2; | |
for (j = 0; j < 3; j++) mid[1][j] = (a[j] + c[j]) / 2; | |
for (j = 0; j < 3; j++) mid[2][j] = (a[j] + d[j]) / 2; | |
for (j = 0; j < 3; j++) mid[3][j] = (b[j] + c[j]) / 2; | |
for (j = 0; j < 3; j++) mid[4][j] = (b[j] + d[j]) / 2; | |
for (j = 0; j < 3; j++) mid[5][j] = (c[j] + d[j]) / 2; | |
divide_tetra(a, mid[0], mid[1], mid[2], m - 1); | |
divide_tetra(mid[0], b, mid[3], mid[4], m - 1); | |
divide_tetra(mid[1], mid[3], c, mid[5], m - 1); | |
divide_tetra(mid[2], mid[4], mid[5], d, m - 1); | |
}else { | |
tetra(a,b,c,d); | |
} | |
} | |
//維持內容物比例不變 | |
void Reshape(int w, int h) { | |
GLfloat aspectRatio; | |
if (h == 0) h = 1; | |
glViewport(0, 0, w, h); | |
glMatrixMode(GL_PROJECTION); | |
glLoadIdentity(); | |
aspectRatio = (GLfloat)w / (GLfloat)h; | |
if (w <= h) glOrtho(-1, 1, -1 / aspectRatio, 1 / aspectRatio, 1, -1); | |
else glOrtho(-1 * aspectRatio, 1 * aspectRatio, -1, 1, 1, -1); | |
glMatrixMode(GL_MODELVIEW); | |
glLoadIdentity(); | |
} | |
int main(int argc, char **argv) { | |
glutInitWindowSize(500, 500); | |
glutCreateWindow("3D_Gasket"); | |
glutDisplayFunc(display); | |
glutReshapeFunc(Reshape); | |
glutMainLoop(); | |
} |
全站熱搜