Reputation: 299
I've been trying to code a sphere in opengl using various code snippets online, but after running the code theres a stray vertex and I'm not sure where my code has missed it:
CODE:
float Lats = 1/(float)(longitude-1);
float Longs = 1/(float)(latitude-1);
int r,s;
vector<GLfloat> vertices;
vector<GLfloat> normals;
vector<GLfloat> texcoords;
vector<GLushort> indices;
for(r = 0; r < longitude; r++)
{
for(s = 0; s < latitude; s++)
{
float const x = cos(2*M_PI * s * Longs) * sin( M_PI * r * Lats );
float const y = sin( -M_PI_2 + M_PI * r * Lats );
float const z = sin(2*M_PI * s * Longs) * sin( M_PI * r * Lats );
vertices.push_back(x * getR());
vertices.push_back(y * getR());
vertices.push_back(z * getR());
normals.push_back(x);
normals.push_back(y);
normals.push_back(z);
texcoords.push_back(s*Lats);
texcoords.push_back(r*Longs);
}
}
for(r = 0; r < longitude; r++)
{
for(s = 0; s < latitude; s++)
{
indices.push_back(r * latitude + s);
indices.push_back(r * latitude + (s+1));
indices.push_back((r+1) * latitude + (s+1));
indices.push_back((r+1) * latitude + s);
}
}
Can anyone see where I have gone wrong?
Upvotes: 0
Views: 781
Reputation: 626
You are computing,
float Lats = 1/(float)(longitude-1);
float Longs = 1/(float)(latitude-1);
The north pole of the sphere is causing a division by 0.
Updated
After looking at your code again I think the issue may be a bit more subtle.
You are assuming
2*M_PI/* double */ * (latitude - 1)/*int*/ * 1/(float)(latitude - 1)/*float*/ == 2*M_PI
Because of floating point issues that may not be true. This applies to all the other expressions in sin() & cos()
Probably you are dealing with a loss of precision.
Since it is deterministic you could even fix it up manually at the end. This still applies though.
Interestingly your Front-face, back-face color coding clearly indicates the problem, There is a "knot" at the top
Upvotes: 1