example.cpp 2.2 KB

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