example.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include <igl/marching_cubes.h>
  2. #include "igl/MCTables.hh"
  3. typedef float ScalarType;
  4. typedef unsigned IndexType;
  5. int main(int argc, char * argv[])
  6. {
  7. Eigen::Matrix<ScalarType, 1, 3> bb_min, bb_max;
  8. bb_min<<0.,0.,0.;
  9. bb_max<<1.,1.,1.;
  10. //diagonal
  11. Eigen::Matrix<ScalarType, 1, 3> diff = bb_max - bb_min;
  12. //center of the sphere
  13. Eigen::Matrix<ScalarType, 1, 3> center = 0.5 * (bb_min + bb_max);
  14. IndexType xres, yres, zres;
  15. xres = yres = zres = 10;
  16. ScalarType radius = 0.42;
  17. //steps in x,y,z direction
  18. ScalarType dx = diff[0] / (ScalarType)(xres-1);
  19. ScalarType dy = diff[1] / (ScalarType)(yres-1);
  20. ScalarType dz = diff[2] / (ScalarType)(zres-1);
  21. Eigen::Matrix<ScalarType, Eigen::Dynamic, 3> points(xres*yres*zres,3);
  22. Eigen::Matrix<ScalarType, Eigen::Dynamic, 1> values(xres*yres*zres,1);
  23. Eigen::Matrix<ScalarType, Eigen::Dynamic, 3> vertices;
  24. Eigen::Matrix<IndexType, Eigen::Dynamic, 3> faces;
  25. std::cerr<<"Sphere -- construct grid"<<std::endl;
  26. for (unsigned int x=0; x<xres; ++x)
  27. for (unsigned int y=0; y<yres; ++y)
  28. for (unsigned int z=0; z<zres; ++z)
  29. {
  30. int index = x + y*xres + z*xres*yres;
  31. points.row(index) = bb_min +
  32. ScalarType(x)*Eigen::Matrix<ScalarType, 1, 3>(dx,0.,0.) +
  33. ScalarType(y)*Eigen::Matrix<ScalarType, 1, 3>(0.,dy,0.) +
  34. ScalarType(z)*Eigen::Matrix<ScalarType, 1, 3>(0.,0.,dz);
  35. values[index] = (points.row(index) - center).squaredNorm() - radius*radius;
  36. }
  37. std::cerr<<"Sphere -- marching cubes"<<std::endl;
  38. igl::marching_cubes(values,
  39. points,
  40. xres,
  41. yres,
  42. zres,
  43. vertices,
  44. faces);
  45. std::cerr<<"Sphere -- saving"<<std::endl;
  46. FILE * fid = fopen("sphere.obj","w");
  47. for (unsigned i = 0; i<vertices.rows(); ++i)
  48. fprintf(fid,"v %.10g %.10g %.10g\n",vertices(i,0),vertices(i,1),vertices(i,2));
  49. for (unsigned i = 0; i<faces.rows(); ++i)
  50. fprintf(fid,"f %d %d %d\n",faces(i,0)+1,faces(i,1)+1,faces(i,2)+1);
  51. fclose(fid);
  52. std::cerr<<"Sphere -- done."<<std::endl;
  53. return 0;
  54. }