/* Sphere.C: Sphere nodes (public source) */

#include "Sphere.H"
#include "renderer.H"

namespace xrml {

void Sphere::render(void)
{
  world->renderer->sphere(this);
}

void Sphere::discretize(void)
{
  int i,j;

  int nqcd = world->renderer->nrQuartCircleDivisions;
  int ni = 2*nqcd, nj = 4*nqcd, n = (ni+1) * nj;

  if (co) delete co;
  co = new MFVec3f(n);
  co->size = n;
  if (norm) delete norm;
  norm = new MFVec3f(n);
  norm->size = n;
  if (texco) delete texco;
  texco = new MFVec2f(n);
  texco->size = n;

  int k = 0;
  for (i=0; i<=ni; i++) {
    float phi = (float)i/(float)ni * M_PI;
    float cp = cos(phi);
    float sp = sin(phi);
    for (j=0; j<nj; j++, k++) {
      float theta = (float)j/(float)nj * 2.*M_PI;
      float c = -cos(theta);
      float s = -sin(theta);
      (*co)[k] = SFVec3f(radius * s * sp, radius * cp, radius * c * sp);
      (*norm)[k] = SFVec3f(s * sp, cp, c * sp);
      (*texco)[k] = SFVec2f(theta / (2.*M_PI), 1. - phi / M_PI);
    }
  }

  coordIndex.size = 0;
  coordIndex.grow(ni*nj*5);
  normalIndex.size = 0;		// use coordIndex
  texCoordIndex.size = 0;	// use coordIndex
  k = 0;
  for (i=0; i<ni; i++) {
    for (j=0; j<nj; j++, k+=5) {
      coordIndex[k  ] = (i+1) * nj + j;
      coordIndex[k+1] = (i+1) * nj + (j+1)%nj;
      coordIndex[k+2] = i * nj + (j+1)%nj;
      coordIndex[k+3] = i * nj + j;
      coordIndex[k+4] = -1;	// end of face marker
    }
  }
}

}  // namespace xrml
