帮助在OpenGL ES中绘制球体

时间:2009-09-26 22:45:26

标签: algorithm opengl-es

我有以下代码,但我找不到错误。这似乎是一个与记忆相关的问题。原始代码取自OpenGL superbible附带的3d库,我正在尝试将其用于openGL es。关于为什么它一直是segfaulting的任何想法?

    - (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();
}

1 个答案:

答案 0 :(得分:2)

您的j循环正在进行iSlices + 1次迭代,因此您需要分配

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

个字节。