OpenGL始めました
ラインで立方体描く!
マウス左ボタンで立方体が回転!
(ただのメモ書きなんて言えない…)
#include <stdlib.h> #include <GL/glut.h> #include <string> using namespace std; #define MAX_POINTS 100 // 記憶する点の数 GLint point[MAX_POINTS][2]; // 座標を記憶する配列 int pointNum = 0; // 記憶した座標の数 int rubberBand = 0; // ラバーバンドの消去 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 edge[][2] = { { 0, 1 }, { 1, 2 }, { 2, 3 }, { 3, 0 }, { 4, 5 }, { 5, 6 }, { 6, 7 }, { 7, 4 }, { 0, 4 }, { 1, 5 }, { 2, 6 }, { 3, 7 } }; void Display(); void Init(); void Resize(int w, int h); void Mouse(int button, int state, int x, int y); void Keybord(unsigned char key, int x, int y); void Idle(); int main(int argc, char* argv[]) { string winName = "test window"; // OpenGL初期化 glutInit(&argc, argv); // ディスプレイの表示モード設定 glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE); // ウィンドウ生成 glutInitWindowPosition(0, 0); glutInitWindowSize(400, 400); glutCreateWindow(winName.c_str()); // ウィンドウが開かれたり、隠れて再び現れたりするとウィンドウを再描画する関数 glutDisplayFunc(Display); // なにこれ glutReshapeFunc(Resize); // マウス glutMouseFunc(Mouse); // キーボード glutKeyboardFunc(Keybord); // アプリケーション初期化 Init(); // メインループ glutMainLoop(); return 0; } void Display() { // ウィンドウのクリア関数 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); // 図形の回転 static int rot = 0; glRotated((double)rot, 0.0, 1.0, 0.0); // 図形の描画 glColor3d(0.0, 1.0, 0.0); glBegin(GL_LINES); for (int i = 0; i < 12; i++) { glVertex3dv(vertex[edge[i][0]]); glVertex3dv(vertex[edge[i][1]]); } glEnd(); glutSwapBuffers(); // 1周回ったら回転角を0に戻す if (++rot >= 360) rot = 0; } 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 Idle() { glutPostRedisplay(); } 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 Keybord(unsigned char key, int x, int y) { switch (key) { case 'q': case 'Q': case '\033': // '\033'はESCのASCIIコード exit(0); default: break; } } void Init() { glClearColor(0.3, 0.3, 0.3, 1.0); }
参考サイト:
GLUTによる「手抜き」OpenGL入門