Skip to content

Instantly share code, notes, and snippets.

@stuartjmoore
Created July 11, 2011 19:46
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save stuartjmoore/1076642 to your computer and use it in GitHub Desktop.
Save stuartjmoore/1076642 to your computer and use it in GitHub Desktop.
Render Sphere in OpenGL ES for iOS, converted from http://www.codesampler.com/oglsrc/oglsrc_9.htm
void renderSphere(float cx, float cy, float cz, float r, int p)
{
float theta1 = 0.0, theta2 = 0.0, theta3 = 0.0;
float ex = 0.0f, ey = 0.0f, ez = 0.0f;
float px = 0.0f, py = 0.0f, pz = 0.0f;
GLfloat vertices[p*6+6], normals[p*6+6], texCoords[p*4+4];
if( r < 0 )
r = -r;
if( p < 0 )
p = -p;
for(int i = 0; i < p/2; ++i)
{
theta1 = i * (M_PI*2) / p - M_PI_2;
theta2 = (i + 1) * (M_PI*2) / p - M_PI_2;
for(int j = 0; j <= p; ++j)
{
theta3 = j * (M_PI*2) / p;
ex = cosf(theta2) * cosf(theta3);
ey = sinf(theta2);
ez = cosf(theta2) * sinf(theta3);
px = cx + r * ex;
py = cy + r * ey;
pz = cz + r * ez;
vertices[(6*j)+(0%6)] = px;
vertices[(6*j)+(1%6)] = py;
vertices[(6*j)+(2%6)] = pz;
normals[(6*j)+(0%6)] = ex;
normals[(6*j)+(1%6)] = ey;
normals[(6*j)+(2%6)] = ez;
texCoords[(4*j)+(0%4)] = -(j/(float)p);
texCoords[(4*j)+(1%4)] = 2*(i+1)/(float)p;
ex = cosf(theta1) * cosf(theta3);
ey = sinf(theta1);
ez = cosf(theta1) * sinf(theta3);
px = cx + r * ex;
py = cy + r * ey;
pz = cz + r * ez;
vertices[(6*j)+(3%6)] = px;
vertices[(6*j)+(4%6)] = py;
vertices[(6*j)+(5%6)] = pz;
normals[(6*j)+(3%6)] = ex;
normals[(6*j)+(4%6)] = ey;
normals[(6*j)+(5%6)] = ez;
texCoords[(4*j)+(2%4)] = -(j/(float)p);
texCoords[(4*j)+(3%4)] = 2*i/(float)p;
}
glVertexPointer(3, GL_FLOAT, 0, vertices);
glNormalPointer(GL_FLOAT, 0, normals);
glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
glDrawArrays(GL_TRIANGLE_STRIP, 0, (p+1)*2);
}
}
@sakrist
Copy link

sakrist commented Feb 13, 2013

thanks man! :)

@ZengruiWang
Copy link

Hi, could you explain the code a little bit or is there any reference? The link is invalid. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment