#include <GL/glut.h>
#include <cmath>
void drawSphere(float radius, int slices, int stacks) {
for (int i = 0; i < stacks; i++) {
float lat0 = M_PI * (-0.5 + (float)(i) / stacks);
float z0 = radius * sin(lat0);
float zr0 = radius * cos(lat0);
float lat1 = M_PI * (-0.5 + (float)(i + 1) / stacks);
float z1 = radius * sin(lat1);
float zr1 = radius * cos(lat1);
glBegin(GL_QUAD_STRIP);
for (int j = 0; j <= slices; j++) {
float lng = 2 * M_PI * (float)(j) / slices;
float x = cos(lng);
float y = sin(lng);
glColor3f((float)j/slices, 0.5f, (float)(slices-j)/slices);
glVertex3f(x * zr0, y * zr0, z0);
glVertex3f(x * zr1, y * zr1, z1);
}
glEnd();
}
}
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -5.0f);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 };
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
drawSphere(1.0, 30, 30);
glFlush();
}
void init() {
glEnable(GL_DEPTH_TEST);
glClearColor(0.0, 0.0, 0.0, 1.0);
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("3D Rainbow Sphere");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}