readOBJ_mex.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include "mex.h"
  2. #define IGL_HEADER_ONLY
  3. #include <Eigen/Core>
  4. #include <igl/readOBJ.h>
  5. using namespace std;
  6. using namespace Eigen;
  7. extern void _main();
  8. Eigen::MatrixXd readMatrix(const mxArray* mat)
  9. {
  10. double* ptr = mxGetPr(mat);
  11. int m = mxGetM(mat);
  12. int n = mxGetN(mat);
  13. Eigen::MatrixXd V;
  14. V.resize(m,n);
  15. for(int j=0;j<n;j++)
  16. for(int i=0;i<m;++i)
  17. V(i,j) = *(ptr++);
  18. return V;
  19. }
  20. mxArray* writeMatrix(const MatrixXd& mat)
  21. {
  22. mxArray* ret = 0;
  23. if (mat.size() == 0)
  24. {
  25. ret = mxCreateNumericMatrix(0, 0, mxDOUBLE_CLASS, mxREAL);
  26. }
  27. else
  28. {
  29. int M = mat.rows();
  30. int N = mat.cols();
  31. ret = mxCreateNumericMatrix(M, N, mxDOUBLE_CLASS, mxREAL);
  32. double* pointer = mxGetPr(ret);
  33. /* Copy data into the mxArray */
  34. int count = 0;
  35. for ( int j = 0; j < N; ++j )
  36. for (int i = 0; i < M; ++i)
  37. pointer[count++] = mat(i,j);
  38. }
  39. return ret;
  40. }
  41. void mexFunction(
  42. int nlhs,
  43. mxArray *plhs[],
  44. int nrhs,
  45. const mxArray *prhs[]
  46. )
  47. {
  48. /* Check for proper number of arguments */
  49. if (nrhs != 1) {
  50. mexErrMsgIdAndTxt("MATLAB:mexcpp:nargin",
  51. "readOBJ requires 1 input arguments, the path of the file to open");
  52. }
  53. else if (nlhs != 2) {
  54. mexErrMsgIdAndTxt("MATLAB:mexcpp:nargout",
  55. "readOBJ generates two output argument, V and F.");
  56. }
  57. // Read the file path
  58. char* file_path = mxArrayToString(prhs[0]);
  59. MatrixXd V;
  60. MatrixXi F;
  61. // Read the mesh
  62. igl::readOBJ(file_path,V,F);
  63. // Matlab is indexing matrices from 1
  64. F = F.array() + 1;
  65. // Return the matrices to matlab, after converting them to double
  66. plhs[0] = writeMatrix(V);
  67. plhs[1] = writeMatrix(F.cast<double>());
  68. return;
  69. }