readWRL.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #include "readWRL.h"
  2. #include <cstdio>
  3. template <typename Scalar, typename Index>
  4. IGL_INLINE bool igl::readWRL(
  5. const std::string wrl_file_name,
  6. std::vector<std::vector<Scalar > > & V,
  7. std::vector<std::vector<Index > > & F)
  8. {
  9. using namespace std;
  10. FILE * wrl_file = fopen(wrl_file_name.c_str(),"r");
  11. if(NULL==wrl_file)
  12. {
  13. printf("IOError: %s could not be opened...",wrl_file_name.c_str());
  14. return false;
  15. }
  16. V.clear();
  17. F.clear();
  18. char line[1000];
  19. // Read lines until seeing "point ["
  20. // treat other lines in file as "comments"
  21. bool still_comments = true;
  22. string needle("point [");
  23. string haystack;
  24. while(still_comments)
  25. {
  26. fgets(line,1000,wrl_file);
  27. haystack = string(line);
  28. still_comments = string::npos == haystack.find(needle);
  29. }
  30. // read points in sets of 3
  31. int floats_read = 3;
  32. double x,y,z;
  33. while(floats_read == 3)
  34. {
  35. floats_read = fscanf(wrl_file," %lf %lf %lf,",&x,&y,&z);
  36. if(floats_read == 3)
  37. {
  38. vector<Scalar > point;
  39. point.resize(3);
  40. point[0] = x;
  41. point[1] = y;
  42. point[2] = z;
  43. V.push_back(point);
  44. //printf("(%g, %g, %g)\n",x,y,z);
  45. }else if(floats_read != 0)
  46. {
  47. printf("ERROR: unrecognized format...\n");
  48. return false;
  49. }
  50. }
  51. // Read lines until seeing "coordIndex ["
  52. // treat other lines in file as "comments"
  53. still_comments = true;
  54. needle = string("coordIndex [");
  55. while(still_comments)
  56. {
  57. fgets(line,1000,wrl_file);
  58. haystack = string(line);
  59. still_comments = string::npos == haystack.find(needle);
  60. }
  61. // read F
  62. int ints_read = 1;
  63. while(ints_read > 0)
  64. {
  65. // read new face indices (until hit -1)
  66. vector<Index > face;
  67. while(true)
  68. {
  69. // indices are 0-indexed
  70. int i;
  71. ints_read = fscanf(wrl_file," %d,",&i);
  72. if(ints_read > 0)
  73. {
  74. if(i>=0)
  75. {
  76. face.push_back(i);
  77. }else
  78. {
  79. F.push_back(face);
  80. break;
  81. }
  82. }else
  83. {
  84. break;
  85. }
  86. }
  87. }
  88. fclose(wrl_file);
  89. return true;
  90. }
  91. #ifndef IGL_HEADER_ONLY
  92. // Explicit template instanciation
  93. template bool igl::readWRL<double, int>(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::vector<std::vector<double, std::allocator<double> >, std::allocator<std::vector<double, std::allocator<double> > > >&, std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >&);
  94. #endif