#include #include #include #include using namespace std; /* return current time (in seconds) */ static int current_time(void) { struct timeval tv; #ifdef __VMS (void) gettimeofday(&tv, NULL ); #else struct timezone tz; (void) gettimeofday(&tv, &tz); #endif return (int) tv.tv_sec; } #ifndef M_PI #define M_PI 3.14159265 #endif int rot = 0; void drawTorus(float r, float R, int nsides, int rings) { float ringDelta = 2.0f * M_PI / rings; float sideDelta = 2.0f * M_PI / nsides; float theta = 0.0f, cosTheta = 1.0f, sinTheta = 0.0f; for (int i = rings - 1; i >= 0; i--) { float theta1 = theta + ringDelta; float cosTheta1 = (float) cos(theta1); float sinTheta1 = (float) sin(theta1); glBegin(GL_QUAD_STRIP); float phi = 0.0f; for (int j = nsides; j >= 0; j--) { phi += sideDelta; float cosPhi = (float) cos(phi); float sinPhi = (float) sin(phi); float dist = R + r * cosPhi; glNormal3f(cosTheta1 * cosPhi, -sinTheta1 * cosPhi, sinPhi); glVertex3f(cosTheta1 * dist, -sinTheta1 * dist, r * sinPhi); glNormal3f(cosTheta * cosPhi, -sinTheta * cosPhi, sinPhi); glVertex3f(cosTheta * dist, -sinTheta * dist, r * sinPhi); } glEnd(); theta = theta1; cosTheta = cosTheta1; sinTheta = sinTheta1; } } void myInit(char *progname) { glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); glutInitWindowSize(640, 480); glutInitWindowPosition(0,0); glutCreateWindow(progname); glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glColor3f(1.0f, 0.0f, 0.0f); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glClearDepth(1.0); glLineWidth(2); glEnable(GL_DEPTH_TEST); } void myIdle() { glutPostRedisplay(); /* calc framerate */ { static int t0 = -1; static int frames = 0; int t = current_time(); if (t0 < 0) t0 = t; frames++; if (t - t0 >= 5.0) { GLfloat seconds = t - t0; GLfloat fps = frames / seconds; printf("%d frames in %3.1f seconds = %6.3f FPS\n", frames, seconds, fps); t0 = t; frames = 0; } } } void myDisplay() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor(.3f, .5f, .8f, 1.0f); glLoadIdentity(); glTranslatef(0.0f, 0.0f, -10.0f); float frot = rot; glRotatef(0.15f * rot, 2.0f * frot, 10.0f * frot, 1.0f); glRotatef(0.3f * rot, 3.0f * frot, 1.0f * frot, 1.0f); rot++; glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glColor3f(0.9f, 0.9f, 0.9f); drawTorus(1, 1.9f + ((float) sin((0.004f * frot))), 15, 15); glutSwapBuffers(); } void myReshape(int width, int height) { float fAspect = width / height; glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0f, fAspect, 0.5f, 400.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } int main(int argc, char** argv) { glutInit(&argc, argv); myInit(argv[0]); glutReshapeFunc(myReshape); glutIdleFunc(myIdle); glutDisplayFunc(myDisplay); glutMainLoop(); return 0; }