matlab编译并使用sdf_values

近期在编译gptoolbox时发现,我们可以在matlab调用libigl或者cgal里头的很多函数。近期刚好需要在matlab里头使用cgal当中的sdf_values函数,目前网上并没有这方面的工作。因而,写一篇博文记录下。

由于目前还没有一个sdf_values函数的cpp及m文件。因而,首先我们要对cpp及m文件之间的关系进行解析。刚好gptoolbox里头有一个decimate_cgal函数可供学习。

decimate_cgal函数学习

下面对decimate_cgal.m文件及decimate_cgal.cpp文件进行解析。

decimate_cgal.m文件解析

% DECIMATE_CGAL Decimate a mesh (V,F) using CGAL's Polyhedron edge_collapse
% routine. (V,F) must already be a manifold mesh
%
% [W,G] = decimate_cgal(V,F,ratio)
%
% Inputs:
%   V  #V by 3 list of input mesh vertex positions
%   F  #F by 3 list of triangles indices into V
%   ratio  scalar between 0 and 1 exclusively specifying ratio of output faces
%   to input faces: ratio ~= #G / #F
% Outputs:
%   W  #W by 3 list of output mesh vertex positions
%   G  #G by 3 list of triangles indices into W

输入为:

  • V:#V by 3
  • F: #F by 3
  • ratio:浮点数
    输出为:
  • W:#W by 3
  • G: #G by 3

我们接下去要分析下,V,F,ratio及W,G在CPP当中是如何对应的。

decimate_cgal.cpp文件解析

原始代码

// 必须的头文件
#include <mex.h>
#include <igl/C_STR.h>
#include <igl/matlab/mexErrMsgTxt.h>
#undef assert
#define assert( isOK ) ( (isOK) ? (void)0 : (void) mexErrMsgTxt(C_STR(__FILE__<<":"<<__LINE__<<": failed assertion `"<<#isOK<<"'"<<std::endl) ) )
#include <igl/matlab/MexStream.h>
#include <igl/matlab/parse_rhs.h>
#include <igl/matlab/prepare_lhs.h>
#include <igl/matlab/validate_arg.h>

//
#include <igl/copyleft/cgal/mesh_to_polyhedron.h>
#include <igl/copyleft/cgal/polyhedron_to_mesh.h>

//
#include <CGAL/Polyhedron_3.h> // Surface mesh
#include <CGAL/Simple_cartesian.h>
#include <CGAL/IO/Polyhedron_iostream.h>
#include <CGAL/Surface_mesh_simplification/edge_collapse.h>
#include <CGAL/Surface_mesh_simplification/Edge_collapse_visitor_base.h>
#include <CGAL/Polyhedron_items_with_id_3.h>
#include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Count_ratio_stop_predicate.h>
#include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Edge_length_cost.h>
#include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Midpoint_placement.h>

#include <iostream>

typedef CGAL::Simple_cartesian<double> Kernel;
typedef Kernel::Point_3 Point ;
//
// Setup an enriched polyhedron type which stores an id() field in the items
//
typedef CGAL::Polyhedron_3<Kernel,CGAL::Polyhedron_items_with_id_3> Surface_mesh; 
typedef Surface_mesh::Halfedge_handle Halfedge_handle ;
typedef Surface_mesh::Vertex_handle   Vertex_handle ;
namespace SMS = CGAL::Surface_mesh_simplification ;
typedef SMS::Edge_profile<Surface_mesh> Profile ;
// The following is a Visitor that keeps track of the simplification process.
// In this example the progress is printed real-time and a few statistics are
// recorded (and printed in the end).
//
struct Stats
{
  Stats() 
    : collected(0)
    , processed(0)
    , collapsed(0)
    , non_collapsable(0)
    , cost_uncomputable(0) 
    , placement_uncomputable(0) 
  {} 
  
  std::size_t collected ;
  std::size_t processed ;
  std::size_t collapsed ;
  std::size_t non_collapsable ;
  std::size_t cost_uncomputable  ;
  std::size_t placement_uncomputable ; 
} ;
struct My_visitor : SMS::Edge_collapse_visitor_base<Surface_mesh>
{
  My_visitor( Stats* s) : stats(s){} 
  // Called during the collecting phase for each edge collected.
  void OnCollected( Profile const&, boost::optional<double> const& )
  {
    ++ stats->collected ;
    //std::cerr << "\rEdges collected: " << stats->collected << std::flush ;
  }                
  
  // Called during the processing phase for each edge selected.
  // If cost is absent the edge won't be collapsed.
  void OnSelected(Profile const&          
                 ,boost::optional<double> cost
                 ,std::size_t             initial
                 ,std::size_t             current
                 )
  {
    ++ stats->processed ;
    if ( !cost )
      ++ stats->cost_uncomputable ;
      
    //if ( current == initial )
    //  std::cerr << "\n" << std::flush ;
    //std::cerr << "\r" << current << std::flush ;
  }                
  
  // Called during the processing phase for each edge being collapsed.
  // If placement is absent the edge is left uncollapsed.
  void OnCollapsing(Profile const&          
                   ,boost::optional<Point>  placement
                   )
  {
    if ( !placement )
      ++ stats->placement_uncomputable ;
  }                
  
  // Called for each edge which failed the so called link-condition,
  // that is, which cannot be collapsed because doing so would
  // turn the surface mesh into a non-manifold.
  void OnNonCollapsable( Profile const& )
  {
    ++ stats->non_collapsable;
  }                
  
  // Called AFTER each edge has been collapsed
  void OnCollapsed( Profile const&, Vertex_handle )
  {
    ++ stats->collapsed;
  }                
  
  Stats* stats ;
} ;

void mexFunction(
         int          nlhs,			// 输出参数数量
         mxArray      *plhs[],      // 输出参数数据,矩阵形式
         int          nrhs,         // 输入参数数量
         const mxArray *prhs[]      // 输入参数数据,矩阵形式
         )
{
  // 命名空间
  using namespace igl;
  using namespace igl::matlab;
  using namespace igl::copyleft::cgal;
  using namespace Eigen;
  // 顶点格式为double
  MatrixXd V,W;
  // 面片格式为int
  MatrixXi F,G;
  // 是否自适应?
  bool adaptive = false;
	
  // 输出流
  igl::matlab::MexStream mout;        
  std::streambuf *outbuf = std::cout.rdbuf(&mout);
  
  // 输入参数格式检查
  mexErrMsgTxt(nrhs>=3,"nrhs should be >= 3");
  parse_rhs_double(prhs,V);
  parse_rhs_index(prhs+1,F);
  mexErrMsgTxt(V.cols()==3,"V must be #V by 3");
  mexErrMsgTxt(F.cols()==3,"F must be #F by 3");
  mexErrMsgTxt( mxIsDouble(prhs[2]) && mxGetM(prhs[2])==1 && mxGetN(prhs[2])==1,"fraction to decimate should be scalar");
  double ratio = * mxGetPr(prhs[2]);
  mexErrMsgTxt((ratio>0 && ratio<1),"Ratio should be in (0,1)");
  
  // 扩展的动态参数
  {
    int i = 3;
    while(i<nrhs)
    {
      mexErrMsgTxt(mxIsChar(prhs[i]),"Parameter names should be strings");
      // Cast to char
      const char * name = mxArrayToString(prhs[i]);
      if(strcmp("Adaptive",name) == 0)
      {
        validate_arg_logical(i,nrhs,prhs,name);
        validate_arg_scalar(i,nrhs,prhs,name);
        adaptive = (bool)*mxGetLogicals(prhs[++i]);
      }else
      {
        mexErrMsgTxt(false,"Unknown parameter");
      }
      i++;
    }
  }

  // 将V,F转换为cgal polyhedron
  Surface_mesh surface_mesh; 
  if(!mesh_to_polyhedron(V,F,surface_mesh))
  {
    mexErrMsgTxt("Failed to convert (V,F) to cgal polyhedron");
  }

  // The items in this polyhedron have an "id()" field 
  // which the default index maps used in the algorithm
  // need to get the index of a vertex/edge.
  // However, the Polyhedron_3 class doesn't assign any value to
  // this id(), so we must do it here:
  int index = 0 ;
  
  for( Surface_mesh::Halfedge_iterator eb = surface_mesh.halfedges_begin()
     , ee = surface_mesh.halfedges_end()
     ; eb != ee
     ; ++ eb
     ) 
    eb->id() = index++;
  index = 0 ;
  for( Surface_mesh::Vertex_iterator vb = surface_mesh.vertices_begin()
     , ve = surface_mesh.vertices_end()
     ; vb != ve
     ; ++ vb
     ) 
    vb->id() = index++;
    
  // In this example, the simplification stops when the number of undirected edges
  // drops below 10% of the initial count
  SMS::Count_ratio_stop_predicate<Surface_mesh> stop(ratio);
 
  Stats stats ;
  My_visitor vis(&stats) ;
  // The index maps are not explicitelty passed as in the previous
  // example because the surface mesh items have a proper id() field.
  // On the other hand, we pass here explicit cost and placement
  // function which differ from the default policies, ommited in
  // the previous example.
  if(adaptive)
  {
    int r = SMS::edge_collapse
             (surface_mesh
             ,stop
             ,CGAL::parameters::visitor      (vis)
             );
  }else
  {
    int r = SMS::edge_collapse
             (surface_mesh
             ,stop
             ,CGAL::parameters::visitor      (vis)
             .get_cost     (SMS::Edge_length_cost  <Surface_mesh>())
             .get_placement(SMS::Midpoint_placement<Surface_mesh>())
             );
  }

  // 处理函数
  polyhedron_to_mesh(surface_mesh,W,G);
  
  // 
  switch(nlhs)
  {
    case 2:
      prepare_lhs_index(G,plhs+1);
    case 1:
      prepare_lhs_double(W,plhs+0);
    default:break;
  }

  // Restore the std stream buffer Important!
  std::cout.rdbuf(outbuf);
  return;
}
代码解析

这里的关键部分在于输入、输出及函数、处理过程。

  1. 头文件
#include <mex.h>
#include <igl/C_STR.h>
#include <igl/matlab/mexErrMsgTxt.h>
#undef assert
#define assert( isOK ) ( (isOK) ? (void)0 : (void) mexErrMsgTxt(C_STR(__FILE__<<":"<<__LINE__<<": failed assertion `"<<#isOK<<"'"<<std::endl) ) )
#include <igl/matlab/MexStream.h>
#include <igl/matlab/parse_rhs.h>
#include <igl/matlab/prepare_lhs.h>
#include <igl/matlab/validate_arg.h>

//
#include <igl/copyleft/cgal/mesh_to_polyhedron.h>
#include <igl/copyleft/cgal/polyhedron_to_mesh.h>

//
#include <CGAL/Polyhedron_3.h> // Surface mesh
#include <iostream>

这部分通常要保留!
2. 输入解析

 // 命名空间
  using namespace igl;
  using namespace igl::matlab;
  using namespace igl::copyleft::cgal;
  using namespace Eigen;
  // 顶点格式为double
  MatrixXd V,W;
  // 面片格式为int
  MatrixXi F,G;
  // 是否自适应?
  bool adaptive = false;
	
  // 输出流
  igl::matlab::MexStream mout;        
  std::streambuf *outbuf = std::cout.rdbuf(&mout);
  
  // 输入参数格式检查
  mexErrMsgTxt(nrhs>=3,"nrhs should be >= 3");
  parse_rhs_double(prhs,V);
  parse_rhs_index(prhs+1,F);
  mexErrMsgTxt(V.cols()==3,"V must be #V by 3");
  mexErrMsgTxt(F.cols()==3,"F must be #F by 3");
  mexErrMsgTxt( mxIsDouble(prhs[2]) && mxGetM(prhs[2])==1 && mxGetN(prhs[2])==1,"fraction to decimate should be scalar");
  double ratio = * mxGetPr(prhs[2]);
  mexErrMsgTxt((ratio>0 && ratio<1),"Ratio should be in (0,1)");
  1. 函数调用
  polyhedron_to_mesh(surface_mesh,W,G);
  1. 输出处理
  switch(nlhs)
  {
    case 2:
      prepare_lhs_index(G,plhs+1);
    case 1:
      prepare_lhs_double(W,plhs+0);
    default:break;
  }

  // Restore the std stream buffer Important!
  std::cout.rdbuf(outbuf);
  return;

sdf_values模块设计

sdf_values.m文件编写

% [faces,sdf] = sdf_values(V,F,cone_angle, number_of_rays, postprocess )
%
% Inputs:
%   V  #V by 3 list of input mesh vertex positions
%   F  #F by 3 list of triangles indices into V
%   cone_angle scalar between 0 and 2*pi 
%   number_of_rays: int between 0 and inf
%   postprocess: bool
% Outputs:
%   faces #F by 1 list of output mesh face id
%   sdf   #F by 1 list of sdf values for each triangles

sdf_values.cpp文件编写

#include <mex.h>
#include <igl/C_STR.h>
#include <igl/matlab/mexErrMsgTxt.h>
#undef assert
#define assert( isOK ) ( (isOK) ? (void)0 : (void) mexErrMsgTxt(C_STR(__FILE__<<":"<<__LINE__<<": failed assertion `"<<#isOK<<"'"<<std::endl) ) )
#include <igl/matlab/MexStream.h>

#include <igl/per_vertex_normals.h>
#include <igl/parallel_for.h>
#include <igl/signed_distance.h>
#include <igl/per_edge_normals.h>
#include <igl/matlab/validate_arg.h>
#include <igl/per_face_normals.h>
#include <igl/WindingNumberAABB.h>
#include <igl/matlab/prepare_lhs.h>
#include <igl/matlab/parse_rhs.h>
#include <igl/C_STR.h>
#include <igl/matlab/MexStream.h>
#include <igl/matlab/parse_rhs.h>
#include <igl/matlab/prepare_lhs.h>
#include <igl/matlab/validate_arg.h>
#include <igl/copyleft/cgal/mesh_to_polyhedron.h>
#include <igl/copyleft/cgal/polyhedron_to_mesh.h>


#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/mesh_segmentation.h>
#include <CGAL/property_map.h>
#include <CGAL/Simple_cartesian.h>
#include <CGAL/Polyhedron_3.h>
#include <CGAL/IO/Polyhedron_iostream.h>
#include <CGAL/Polyhedron_items_with_id_3.h>

#include <Eigen/Core>
#include <iostream>

typedef CGAL::Simple_cartesian<double> Kernel;
typedef Kernel::Point_3 Point;
typedef CGAL::Polyhedron_3<Kernel> Polyhedron;
typedef CGAL::Polyhedron_3<Kernel, CGAL::Polyhedron_items_with_id_3> Surface_mesh;

typedef boost::graph_traits<Surface_mesh>::face_descriptor face_descriptor;


void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  using namespace std;	
  using namespace igl;
  using namespace igl::matlab;
  using namespace igl::copyleft::cgal;
  using namespace Eigen;
  MatrixXd V;
  MatrixXi F;
  

  igl::matlab::MexStream mout;
  std::streambuf *outbuf = std::cout.rdbuf(&mout);

  mexErrMsgTxt(nrhs==5,"nrhs should be == 5");
  parse_rhs_double(prhs,V);
  parse_rhs_index(prhs+1,F);
  mexErrMsgTxt(V.cols()==3,"V must be #V by 3");
  mexErrMsgTxt(F.cols()==3,"F must be #F by 3");
  
  mexErrMsgTxt(mxIsDouble(prhs[2]) && mxGetM(prhs[2])==1 && mxGetN(prhs[2])==1,"cone_angle  should be scalar");
  double cone_angle = * mxGetPr(prhs[2]);
  mexErrMsgTxt((cone_angle>0 && cone_angle<6.28),"cone_angle should be in (0,pi)");
  
  mexErrMsgTxt(mxIsDouble(prhs[3]) && mxGetM(prhs[3])==1 && mxGetN(prhs[3])==1,"number_of_rays  should be scalar");
  std::size_t number_of_rays = * mxGetPr(prhs[3]);
  mexErrMsgTxt((number_of_rays>0 && number_of_rays<100),"number_of_rays should be in (0,100)");  

  mexErrMsgTxt(mxIsDouble(prhs[4]) && mxGetM(prhs[4])==1 && mxGetN(prhs[4])==1,"postprocess should be scalar");
  bool postprocess = * mxGetPr(prhs[4]);


  Surface_mesh mesh; 
  if(!mesh_to_polyhedron(V,F,mesh))
  {
    mexErrMsgTxt("Failed to convert (V,F) to cgal polyhedron");
  }

  // process
  typedef std::map<face_descriptor, double> Face_double_map;
  Face_double_map internal_map;
  boost::associative_property_map<Face_double_map> sdf_property_map(internal_map);

  // compute SDF values
  CGAL::sdf_values(mesh, sdf_property_map, cone_angle, number_of_rays, postprocess);
	
  plhs[0] = mxCreateDoubleMatrix(F.rows(), 1, mxREAL);
  double* face = mxGetPr(plhs[0]);

  plhs[1] = mxCreateDoubleMatrix(F.rows(), 1, mxREAL);
  double* sdf = mxGetPr(plhs[1]);


  long i = 0;
  for(face_descriptor f : faces(mesh))
  {
	  face[i] = i+1;
	  sdf[i] = sdf_property_map[f];
	  i++;
  }
	
  // Restore the std stream buffer Important!
  std::cout.rdbuf(outbuf);
}

编译运行

通过cmake进行编译并生成sdf_values.mexw64.
在matlab客户端输入:

[~,fsdf] = sdf_values(V1',F1',2*pi/3, 8, 1 );

显示结果为:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值