torus
Megjelenés
Főnév
torus (tsz. toruses)
Graphical Donut using OpenGL (GLUT)
#include <GL/glut.h>
#include <cmath>
float A = 0.0f, B = 0.0f;
const float R1 = 1.0f; // Inner radius
const float R2 = 2.0f; // Outer radius
const int numTheta = 100, numPhi = 100; // Resolution
void drawDonut() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -7.0f); // Move the torus back
glRotatef(A, 1.0f, 0.0f, 0.0f); // Rotate around X-axis
glRotatef(B, 0.0f, 1.0f, 0.0f); // Rotate around Y-axis
glColor3f(1.0f, 1.0f, 1.0f); // White torus
glBegin(GL_POINTS);
for (int i = 0; i < numTheta; i++) {
float theta = i * 2.0f * M_PI / numTheta;
float cosTheta = cos(theta), sinTheta = sin(theta);
for (int j = 0; j < numPhi; j++) {
float phi = j * 2.0f * M_PI / numPhi;
float cosPhi = cos(phi), sinPhi = sin(phi);
// Compute 3D torus points
float x = (R2 + R1 * cosTheta) * cosPhi;
float y = (R2 + R1 * cosTheta) * sinPhi;
float z = R1 * sinTheta;
glVertex3f(x, y, z);
}
}
glEnd();
glutSwapBuffers();
}
void update(int value) {
A += 1.0f; // Increment rotation angles
B += 1.0f;
glutPostRedisplay();
glutTimerFunc(16, update, 0); // Call every 16ms (~60 FPS)
}
void initOpenGL() {
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, 1.0, 1.0, 50.0);
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(600, 600);
glutCreateWindow("3D Spinning Donut");
initOpenGL();
glutDisplayFunc(drawDonut);
glutTimerFunc(16, update, 0);
glutMainLoop();
return 0;
}
How It Works
✅ Uses OpenGL (GLUT) for rendering instead of ASCII characters.
✅ Generates a 3D torus using trigonometry with glBegin(GL_POINTS)
.
✅ Implements smooth real-time rotation using glRotatef()
.
✅ Uses a timer function for animation (glutTimerFunc
).
✅ Enables depth testing (glEnable(GL_DEPTH_TEST)
) for correct rendering.
How to Compile & Run (Linux/macOS)
Install OpenGL and GLUT (if not installed):
sudo apt-get install freeglut3-dev # Ubuntu/Debian brew install freeglut # macOS (Homebrew)
Compile the program:
g++ donut.cpp -o donut -lGL -lGLU -lglut
Run the program:
./donut