I don't understand code that builds 3D sphere

I'm trying to learn some lwjgl and opengl, and I was trying to make a 3d sphere etc, I found a code to do that, but I don't 100% understand the code and the math behind it and would like to get some deeper explanation about it.

This is my draw sphere method:

public void drawSphere(float radius) {
final float PI = 3.141592f;
float x, y, z, alpha, beta;
for (alpha = 0.0f; alpha < Math.PI; alpha += PI / gradation) {
glBegin(GL_TRIANGLE_STRIP);
for (beta = 0.0f; beta < 2.01f * Math.PI; beta += PI / gradation) {
x = (float) (radius * Math.cos(beta) * Math.sin(alpha));
y = (float) (radius * Math.sin(beta) * Math.sin(alpha));
z = (float) (radius * Math.cos(alpha));
glTexCoord2f(beta / (2.0f * PI), alpha / PI);
glVertex3f(x, y, z);
x = (float) (radius * Math.cos(beta) * Math.sin(alpha + PI / gradation));
y = (float) (radius * Math.sin(beta) * Math.sin(alpha + PI / gradation));
glTexCoord2f(beta / (2.0f * PI), alpha / PI + 1.0f / gradation);
glVertex3f(x, y, z);
}
glEnd();
}
}


I understand the general idea of this, and I understand how the x, y, z are calculated, but what I don't understand is the 2 nested loops aka:

for (alpha = 0.0f; alpha < Math.PI; alpha += PI / gradation)


and

for (beta = 0.0f; beta < 2.01f * Math.PI; beta += PI / gradation)


One more thing, is the glTexCoord2f that I don't quite understand the math behind it, so an explanation about this would be really nice as well for:

glTexCoord2f(beta / (2.0f * PI), alpha / PI);


and

glTexCoord2f(beta / (2.0f * PI), alpha / PI + 1.0f / gradation);


To understand the texture coordinates, you need to understand an equirectangular projection. An image in this format has its x coordinates representing the longitudes, and the y coordinates representing the latitudes. I'm assuming that the texture is in a GL_TEXTURE_2D texture target. That means that the texture coordinates need to be normalized. So the 2 lines you quoted are converting the longitude and latitude from their normal ranges (longitude = 0 to π, latitude = 0 to 2 * π), into the range 0 to 1. This makes a texture in an equirectangular projection map properly onto the sphere. The vertex at lat/long of (alpha, beta) will be assigned a texture coordinate (u, v) in such a way that the bottom of the image is at the south pole, the equator is in the middle, the top is at the north pole, and the left and right edge meet at the international date line.
• I don't think I have enough time for that now, as I need to go to a job interview very soon, but there's barely code for the texture: sunTexture = TextureLoader.getTexture("jpg", new FileInputStream("res/sun.jpg")); mercuryTexture = TextureLoader.getTexture("jpg", new FileInputStream("res/mercury.jpg")); thats the uploading texture method, then I simply enable texture_2d and bind the texture. – msacco Jun 20 '18 at 5:47