opengl画三维坐标轴,可以通过鼠标控制其旋转。
opengl画三维坐标轴代码:
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 |
#include <windows.h> #include <stdio.h> #include <GL/glut.h> void init(void); void reshape(int w, int h); void mouse(int button, int state, int x, int y); void motion(int x, int y); void display(void); void drawCoordinates(void); int mx, my; //position of mouse; float x_angle, y_angle; //angle of eye void init(void) { } void reshape(int w, int h) { glViewport(0, 0, w, h); } void mouse(int button, int state, int x, int y) { if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { mx = x; my = y; } } void motion(int x, int y) { int dx, dy; //offset of mouse; dx = x - mx; dy = y - my; y_angle += dx * 0.01f; x_angle += dy * 0.01f; mx = x; my = y; glutPostRedisplay(); } void display(void) { int rect[4]; float w, h; glGetIntegerv(GL_VIEWPORT, rect); w = rect[2]; h = rect[3]; glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (w > h) glOrtho(-w / h, w / h, -1.0f, 1.0f, -1.0f, 1.0f); else glOrtho(-1.0f, 1.0f, -h / w, h / w, -1.0f, 1.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glRotatef(x_angle, 1.0f, 0.0f, 0.0f); glRotatef(y_angle, 0.0f, 1.0f, 0.0f); drawCoordinates(); glFlush(); glutSwapBuffers(); } void drawCoordinates(void) { glLineWidth(3.0f); glColor3f(1.0f, 0.0f, 0.0f); //画红色的x轴 glBegin(GL_LINES); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(1.0f, 0.0f, 0.0f); glEnd(); glColor3f(0.0, 1.0, 0.0); //画绿色的y轴 glBegin(GL_LINES); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, 1.0f, 0.0f); glEnd(); glColor3f(0.0, 0.0, 1.0); //画蓝色的z轴 glBegin(GL_LINES); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, 0.0f, 1.0f); glEnd(); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(500, 500); glutInitWindowPosition(0, 0); glutCreateWindow("gl_1_2"); init(); glutDisplayFunc(display); glutReshapeFunc(reshape); glutMouseFunc(mouse); glutMotionFunc(motion); glutMainLoop(); return 0; } |
opengl画三维坐标轴测试结果: