[C言語]GLUTの隠面消去処理

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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <stdlib.h>
#include <GL/glut.h>
 
GLdouble vertex[][3] = {
    {0.0, 0.0, 0.0},
    {1.0, 0.0, 0.0},
    {1.0, 1.0, 0.0},
    {0.0, 1.0, 0.0},
    {0.0, 0.0, 1.0},
    {1.0, 0.0, 1.0},
    {1.0, 1.0, 1.0},
    {0.0, 1.0, 1.0}
};
 
int face[][4] = {
    {0, 1, 2, 3},
    {1, 5, 6, 2},
    {5, 4, 7, 6},
    {4, 0, 3, 7},
    {4, 5, 1, 0},
    {3, 2, 6, 7},
};
 
GLdouble color[][3] = {
    {1.0, 0.0, 0.0},
    {0.0, 1.0, 0.0},
    {0.0, 0.0, 1.0},
    {1.0, 1.0, 0.0},
    {1.0, 0.0, 1.0},
    {0.0, 1.0, 1.0},
};
 
void idle(void){
    glutPostRedisplay();
}
 
void display(void){
    int i;
    int j;
    static int r = 0; /* 回転角 */
 
    glClear(GL_COLOR_BUFFER_BIT);
     
    glLoadIdentity();
 
    /* 視点位置と視点方向 */
    gluLookAt(3.0, 4.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
 
    /* 図形の回転 */
    glRotated((double)r, 0.0, 1.0, 0.0);
 
    /* 図形の描画 */
    glBegin(GL_QUADS);
    for(j = 0; j < 6; ++j){
        glColor3dv(color&#91;j&#93;);
        for(i = 0; i < 4; ++i){
            glVertex3dv(vertex&#91;face&#91;j&#93;&#91;i&#93;&#93;);
        }
    }
    glEnd();
     
    glutSwapBuffers();
 
    /* 一周回ったら回転角を0に戻す */
    if(++r >= 360) r = 0;
}
 
void resize(int w, int h){
    glViewport(0, 0, w, h);
 
    /* 透視変換行列の設定 */
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(30.0, (double)w / (double)h, 1.0, 100.0);
 
    /* モデルビュー変換行列の設定*/
    glMatrixMode(GL_MODELVIEW);
}
 
void mouse(int button, int state, int x, int y){
    switch(button){
        case GLUT_LEFT_BUTTON:
            if(state == GLUT_DOWN){
                glutIdleFunc(idle);
            } else {
                glutIdleFunc(0);
            }
            break;
        case GLUT_RIGHT_BUTTON:
            if (state == GLUT_DOWN){
                glutPostRedisplay();
            }
            break;
        default:
            break;
    }
}
 
void keyboard(unsigned char key, int x, int y){
    switch(key){
        case 'q':
        case 'Q':
        case '\033':
            exit(0);
        default:
            break;
    }
}
 
void init(void){
    glClearColor(1.0, 1.0, 1.0, 1.0);
}
 
int main(int argc, char *argv[]){
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGBA);
    glutCreateWindow(argv[0]);
    glutDisplayFunc(display);
    glutReshapeFunc(resize);
    glutMouseFunc(mouse);
    glutKeyboardFunc(keyboard);
    init();
    glutMainLoop();
    return 0;
}