Andrei Tanasescu
Andrei Tanasescu

Reputation: 638

Help with drawing a sphere in OpenGL ES

I have the following code, but I can't find the bug. It seems to be a memory-related issue. The original code is taken from the 3d library which comes with the OpenGL superbible, and i'm trying to adapt it for openGL es. Any ideas as to why it's segfaulting all the time?

    - (void)drawSphereOfRadius:(GLfloat)fRadius nbSlices:(GLint)iSlices nbStacks:(GLint)iStacks
{
 GLfloat *vertexPointer = malloc(sizeof(GLfloat) * iStacks * iSlices * 3 * 2);

 GLfloat drho = (GLfloat)(3.141592653589) / (GLfloat) iStacks;
 GLfloat dtheta = 2.0f * (GLfloat)(3.141592653589) / (GLfloat) iSlices;
 GLfloat ds = 1.0f / (GLfloat) iSlices;
 GLfloat dt = 1.0f / (GLfloat) iStacks;
 GLfloat t = 1.0f; 
 GLfloat s = 0.0f;
 GLint i, j;     // Looping variables


 int idx = 0;
 for (i = 0; i < iStacks; i++) 
 {
  GLfloat rho = (GLfloat)i * drho;
  GLfloat srho = (GLfloat)(sin(rho));
  GLfloat crho = (GLfloat)(cos(rho));
  GLfloat srhodrho = (GLfloat)(sin(rho + drho));
  GLfloat crhodrho = (GLfloat)(cos(rho + drho));


  s = 0.0f;

  for ( j = 0; j <= iSlices; j++) 
  {
   GLfloat theta = (j == iSlices) ? 0.0f : j * dtheta;
   GLfloat stheta = (GLfloat)(-sin(theta));
   GLfloat ctheta = (GLfloat)(cos(theta));

   GLfloat x = stheta * srho;
   GLfloat y = ctheta * srho;
   GLfloat z = crho;


   glNormal3f(x, y, z);

   vertexPointer[idx] = x * fRadius;
   vertexPointer[idx + 1] = y * fRadius;
   vertexPointer[idx + 2] = z * fRadius;

   x = stheta * srhodrho;
   y = ctheta * srhodrho;
   z = crhodrho;

   s += ds;
   glNormal3f(x, y, z);
   vertexPointer[idx + 3] = x * fRadius;
   vertexPointer[idx + 4] = y * fRadius;
   vertexPointer[idx + 5] = z * fRadius;
   idx += 6;

  }


  t -= dt;
 }


 glVertexPointer(3, GL_FLOAT, 0, vertexPointer);
 glEnableClientState(GL_VERTEX_ARRAY);

 glDrawArrays(GL_TRIANGLE_STRIP, 0, iStacks * iSlices * 2 );

 free(vertexPointer);
 //glPopMatrix();
}

Upvotes: 0

Views: 3322

Answers (1)

Troubadour
Troubadour

Reputation: 13421

Your j loop is doing iSlices + 1 iterations so you need to allocate

sizeof(GLfloat) * iStacks * ( iSlices + 1 ) * 3 * 2

bytes for vertexPointer.

Upvotes: 2

Related Questions