add vcglib

This commit is contained in:
yuanlin zhong committed 2025-11-03 17:46:44 +08:00
1 parent 6f6c0c8eb7
commit af8100f851
1537 files changed
+634197

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
cmake_minimum_required(VERSION 3.13)
project (metro)
if (VCG_HEADER_ONLY)
set(SOURCES
metro.cpp
${VCG_INCLUDE_DIRS}/wrap/ply/plylib.cpp)
endif()
add_executable(metro
${SOURCES})
target_link_libraries(
metro
PUBLIC
vcglib
)
+37
View File
@@ -0,0 +1,37 @@
VCGLib http://vcg.sf.net o o
Visual and Computer Graphics Library o o
_ O _
Copyright(C) 2005-2006 \/)\/
Visual Computing Lab http://vcg.isti.cnr.it /\/|
ISTI - Italian National Research Council |
\
Metro 4.07 2007/05/11
All rights reserved.
2007/05/11 Release 4.07
Added support for obj files.
Now the Distance comparison can be done exploiting also a (slow) octree.
Removed bug on the display of the area of the mesh.
2005/10/03 Release 4.06
Changed the core for distance computation.
Current version uses the lib flexible search structures.
Now the comparison can be done exploiting a static uniform grid,
a hashed grid or a hierarchy of AA box.
2005/04/04 Release 4.05
Added saving of Error Histogram
2005/01/26 Release 4.04
Gcc compiling issues
Moved to the library core the code for computing min distance froma a point to a mesh using a uniform grid.
Slightly faster.
2005/01/03 Release 4.03
Better ply compatibility, and improved error reporting
2004/11/29 Release 4.02
removed bug in printing Hausdorf distance,
removed bug in command line parsing,
upgraded import mesh library to support off format
+318
View File
@@ -0,0 +1,318 @@
/****************************************************************************
* VCGLib o o *
* Visual and Computer Graphics Library o o *
* _ O _ *
* Copyright(C) 2004-2016 \/)\/ *
* Visual Computing Lab /\/| *
* ISTI - Italian National Research Council | *
* \ *
* All rights reserved. *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt) *
* for more details. *
* *
****************************************************************************/
// standard libraries
#include <time.h>
#include <vcg/math/histogram.h>
#include <vcg/complex/complex.h>
#include <wrap/io_trimesh/import.h>
#include <wrap/io_trimesh/export.h>
#include <vcg/simplex/face/component_ep.h>
#include <vcg/complex/algorithms/update/component_ep.h>
#include <vcg/complex/algorithms/update/bounding.h>
#include "sampling.h"
using namespace std;
// project definitions.
// error messages
#define MSG_ERR_MESH_LOAD "error loading the input meshes.\n"
#define MSG_ERR_INVALID_OPTION "unable to parse option '%s'\n"
#define MSG_ERR_FILE_OPEN "unable to open the output file.'n"
#define MSG_ERR_UNKNOWN_FORMAT "unknown file format '%s'.\n"
// global constants
#define NO_SAMPLES_PER_FACE 10
#define N_SAMPLES_EDGE_TO_FACE_RATIO 0.1
#define BBOX_FACTOR 0.1
#define INFLATE_PERCENTAGE 0.02
#define MIN_SIZE 125 /* 125 = 5^3 */
#define N_HIST_BINS 256
#define PRINT_EVERY_N_ELEMENTS 1000
class CFace;
class CVertex;
struct UsedTypes:public vcg::UsedTypes< vcg::Use<CFace>::AsFaceType, vcg::Use<CVertex>::AsVertexType>{};
class CVertex : public vcg::Vertex<UsedTypes,vcg::vertex::Coord3d,vcg::vertex::Qualityf,vcg::vertex::Normal3d,vcg::vertex::Color4b,vcg::vertex::BitFlags> {};
class CFace : public vcg::Face< UsedTypes,vcg::face::VertexRef, vcg::face::Normal3d, vcg::face::EdgePlane,vcg::face::Color4b,vcg::face::Mark,vcg::face::BitFlags> {};
class CMesh : public vcg::tri::TriMesh< std::vector<CVertex>, std::vector<CFace> > {};
// -----------------------------------------------------------------------------------------------
using namespace vcg;
////////////////// Command line Flags and parameters
bool NumberOfSamples = false;
bool SamplesPerAreaUnit = false;
bool CleaningFlag=false;
// -----------------------------------------------------------------------------------------------
void Usage()
{
printf("\nUsage: "\
"metro file1 file2 [opt]\n"\
"Where opt can be:\n"\
" -v disable vertex sampling\n"\
" -e disable edge sampling\n"\
" -f disable face sampling\n"\
" -u ignore unreferred vertices\n"\
" -sx set the face sampling mode\n"\
" where x can be:\n"\
" -s0 montecarlo sampling\n"\
" -s1 subdivision sampling\n"\
" -s2 similar triangles sampling (Default)\n"\
" -n# set the required number of samples (overrides -A)\n"\
" -a# set the required number of samples per area unit (overrides -N)\n"\
" -c save a mesh with error as per-vertex colour and quality\n"\
" -C # # Set the min/max values used for color mapping\n"\
" -L Remove duplicated and unreferenced vertices before processing\n"\
" -h write files with histograms of error distribution\n"\
" -G Use a static Uniform Grid as Search Structure (default)\n"\
" -O Use an octree as a Search Structure\n"\
" -A Use an AxisAligned Bounding Box Tree as Search Structure\n"\
" -H Use an Hashed Uniform Grid as Search Structure\n"\
"\n"
"Default options are to sample vertexes, edge and faces by taking \n"
"a number of samples that is approx. 10x the face number.\n"
);
exit(-1);
}
// simple aux function that compute the name for the file containing the stored computations
std::string SaveFileName(const std::string &filename)
{
int pos=filename.find_last_of('.',filename.length());
std::string fileout=filename.substr(0,pos)+"_metro.ply";
return fileout;
}
// Open Mesh
void OpenMesh(const char *filename, CMesh &m)
{
int err = tri::io::Importer<CMesh>::Open(m,filename);
if(err) {
printf("Error in reading %s: '%s'\n",filename,tri::io::Importer<CMesh>::ErrorMsg(err));
if(tri::io::Importer<CMesh>::ErrorCritical(err)) exit(-1);
}
printf("read mesh `%s'\n", filename);
if(CleaningFlag){
int dup = tri::Clean<CMesh>::RemoveDuplicateVertex(m);
int unref = tri::Clean<CMesh>::RemoveUnreferencedVertex(m);
printf("Removed %i duplicate and %i unreferenced vertices from mesh %s\n",dup,unref,filename);
}
}
int main(int argc, char**argv)
{
CMesh S1, S2;
float ColorMin=0, ColorMax=0;
double dist1_max, dist2_max;
unsigned long n_samples_target, elapsed_time;
double n_samples_per_area_unit;
int flags;
// print program info
printf("-------------------------------\n"
" Metro V.4.07 \n"
" http://vcg.isti.cnr.it\n"
" release date: " __DATE__ "\n"
"-------------------------------\n\n");
if(argc <= 2) Usage();
// default parameters
flags = SamplingFlags::VERTEX_SAMPLING |
SamplingFlags::EDGE_SAMPLING |
SamplingFlags::FACE_SAMPLING |
SamplingFlags::SIMILAR_SAMPLING;
// parse command line.
for(int i=3; i < argc;)
{
if(argv[i][0]=='-')
switch(argv[i][1])
{
case 'h' : flags |= SamplingFlags::HIST; break;
case 'v' : flags &= ~SamplingFlags::VERTEX_SAMPLING; break;
case 'e' : flags &= ~SamplingFlags::EDGE_SAMPLING; break;
case 'f' : flags &= ~SamplingFlags::FACE_SAMPLING; break;
case 'u' : flags |= SamplingFlags::INCLUDE_UNREFERENCED_VERTICES; break;
case 's' :
switch(argv[i][2])
{
case '0': flags = (flags | SamplingFlags::MONTECARLO_SAMPLING ) & (~ SamplingFlags::NO_SAMPLING );break;
case '1': flags = (flags | SamplingFlags::SUBDIVISION_SAMPLING ) & (~ SamplingFlags::NO_SAMPLING );break;
case '2': flags = (flags | SamplingFlags::SIMILAR_SAMPLING ) & (~ SamplingFlags::NO_SAMPLING );break;
default : printf(MSG_ERR_INVALID_OPTION, argv[i]);
exit(0);
}
break;
case 'n': NumberOfSamples = true; n_samples_target = (unsigned long) atoi(&(argv[i][2])); break;
case 'a': SamplesPerAreaUnit = true; n_samples_per_area_unit = (unsigned long) atoi(&(argv[i][2])); break;
case 'c': flags |= SamplingFlags::SAVE_ERROR; break;
case 'L': CleaningFlag=true; break;
case 'C': ColorMin=float(atof(argv[i+1])); ColorMax=float(atof(argv[i+2])); i+=2; break;
case 'A': flags |= SamplingFlags::USE_AABB_TREE; printf("Using AABB Tree as search structure\n"); break;
case 'G': flags |= SamplingFlags::USE_STATIC_GRID; printf("Using static uniform grid as search structure\n"); break;
case 'H': flags |= SamplingFlags::USE_HASH_GRID; printf("Using hashed uniform grid as search structure\n"); break;
case 'O': flags |= SamplingFlags::USE_OCTREE; printf("Using octree as search structure\n"); break;
default : printf(MSG_ERR_INVALID_OPTION, argv[i]);
exit(0);
}
i++;
}
if(!(flags & SamplingFlags::USE_HASH_GRID) && !(flags & SamplingFlags::USE_AABB_TREE) && !(flags & SamplingFlags::USE_OCTREE))
flags |= SamplingFlags::USE_STATIC_GRID;
// load input meshes.
OpenMesh(argv[1],S1);
OpenMesh(argv[2],S2);
string S1NewName=SaveFileName(argv[1]);
string S2NewName=SaveFileName(argv[2]);
if(!NumberOfSamples && !SamplesPerAreaUnit)
{
NumberOfSamples = true;
n_samples_target = 10 * max(S1.fn,S2.fn);// take 10 samples per face
}
// compute face information
tri::UpdateComponentEP<CMesh>::Set(S1);
tri::UpdateComponentEP<CMesh>::Set(S2);
// set bounding boxes for S1 and S2
tri::UpdateBounding<CMesh>::Box(S1);
tri::UpdateBounding<CMesh>::Box(S2);
// set Bounding Box.
Box3<CMesh::ScalarType> bbox, tmp_bbox_M1=S1.bbox, tmp_bbox_M2=S2.bbox;
bbox.Add(S1.bbox);
bbox.Add(S2.bbox);
bbox.Offset(bbox.Diag()*0.02);
S1.bbox = bbox;
S2.bbox = bbox;
// initialize time info.
int t0=clock();
Sampling<CMesh> ForwardSampling(S1,S2);
Sampling<CMesh> BackwardSampling(S2,S1);
// print mesh info.
printf("Mesh info:\n");
printf(" M1: '%s'\n\tvertices %7i\n\tfaces %7i\n\tarea %12.4f\n", argv[1], S1.vn, S1.fn, ForwardSampling.GetArea());
printf("\tbbox (%7.4f %7.4f %7.4f)-(%7.4f %7.4f %7.4f)\n", tmp_bbox_M1.min[0], tmp_bbox_M1.min[1], tmp_bbox_M1.min[2], tmp_bbox_M1.max[0], tmp_bbox_M1.max[1], tmp_bbox_M1.max[2]);
printf("\tbbox diagonal %f\n", (float)tmp_bbox_M1.Diag());
printf(" M2: '%s'\n\tvertices %7i\n\tfaces %7i\n\tarea %12.4f\n", argv[2], S2.vn, S2.fn, BackwardSampling.GetArea());
printf("\tbbox (%7.4f %7.4f %7.4f)-(%7.4f %7.4f %7.4f)\n", tmp_bbox_M2.min[0], tmp_bbox_M2.min[1], tmp_bbox_M2.min[2], tmp_bbox_M2.max[0], tmp_bbox_M2.max[1], tmp_bbox_M2.max[2]);
printf("\tbbox diagonal %f\n", (float)tmp_bbox_M2.Diag());
// Forward distance.
printf("\nForward distance (M1 -> M2):\n");
ForwardSampling.SetFlags(flags);
if(NumberOfSamples)
{
ForwardSampling.SetSamplesTarget(n_samples_target);
n_samples_per_area_unit = ForwardSampling.GetNSamplesPerAreaUnit();
}
else
{
ForwardSampling.SetSamplesPerAreaUnit(n_samples_per_area_unit);
n_samples_target = ForwardSampling.GetNSamplesTarget();
}
printf("target # samples : %lu\ntarget # samples/area : %f\n", n_samples_target, n_samples_per_area_unit);
ForwardSampling.Hausdorff();
dist1_max = ForwardSampling.GetDistMax();
printf("\ndistances:\n max : %f (%f wrt bounding box diagonal)\n", (float)dist1_max, (float)dist1_max/bbox.Diag());
printf(" mean : %f\n", ForwardSampling.GetDistMean());
printf(" RMS : %f\n", ForwardSampling.GetDistRMS());
printf("# vertex samples %9lu\n", ForwardSampling.GetNVertexSamples());
printf("# edge samples %9lu\n", ForwardSampling.GetNEdgeSamples());
printf("# area samples %9lu\n", ForwardSampling.GetNAreaSamples());
printf("# total samples %9lu\n", ForwardSampling.GetNSamples());
printf("# samples per area unit: %f\n\n", ForwardSampling.GetNSamplesPerAreaUnit());
// Backward distance.
printf("\nBackward distance (M2 -> M1):\n");
BackwardSampling.SetFlags(flags);
if(NumberOfSamples)
{
BackwardSampling.SetSamplesTarget(n_samples_target);
n_samples_per_area_unit = BackwardSampling.GetNSamplesPerAreaUnit();
}
else
{
BackwardSampling.SetSamplesPerAreaUnit(n_samples_per_area_unit);
n_samples_target = BackwardSampling.GetNSamplesTarget();
}
printf("target # samples : %lu\ntarget # samples/area : %f\n", n_samples_target, n_samples_per_area_unit);
BackwardSampling.Hausdorff();
dist2_max = BackwardSampling.GetDistMax();
printf("\ndistances:\n max : %f (%f wrt bounding box diagonal)\n", (float)dist2_max, (float)dist2_max/bbox.Diag());
printf(" mean : %f\n", BackwardSampling.GetDistMean());
printf(" RMS : %f\n", BackwardSampling.GetDistRMS());
printf("# vertex samples %9lu\n", BackwardSampling.GetNVertexSamples());
printf("# edge samples %9lu\n", BackwardSampling.GetNEdgeSamples());
printf("# area samples %9lu\n", BackwardSampling.GetNAreaSamples());
printf("# total samples %9lu\n", BackwardSampling.GetNSamples());
printf("# samples per area unit: %f\n\n", BackwardSampling.GetNSamplesPerAreaUnit());
// compute time info.
elapsed_time = clock() - t0;
int n_total_sample=ForwardSampling.GetNSamples()+BackwardSampling.GetNSamples();
double mesh_dist_max = max(dist1_max , dist2_max);
printf("\nHausdorff distance: %f (%f wrt bounding box diagonal)\n",(float)mesh_dist_max,(float)mesh_dist_max/bbox.Diag());
printf(" Computation time : %d ms\n",(int)(1000.0*elapsed_time/CLOCKS_PER_SEC));
printf(" # samples/second : %f\n\n", (float)n_total_sample/((float)elapsed_time/CLOCKS_PER_SEC));
// save error files.
if(flags & SamplingFlags::SAVE_ERROR)
{
int saveMask = vcg::tri::io::Mask::IOM_VERTCOLOR | vcg::tri::io::Mask::IOM_VERTQUALITY /* | vcg::ply::PLYMask::PM_VERTQUALITY*/ ;
//p.mask|=vcg::ply::PLYMask::PM_VERTCOLOR|vcg::ply::PLYMask::PM_VERTQUALITY;
if(ColorMax!=0 || ColorMin != 0){
vcg::tri::UpdateColor<CMesh>::PerVertexQualityRamp(S1,ColorMin,ColorMax);
vcg::tri::UpdateColor<CMesh>::PerVertexQualityRamp(S2,ColorMin,ColorMax);
}
tri::io::ExporterPLY<CMesh>::Save( S1,S1NewName.c_str(),saveMask);
tri::io::ExporterPLY<CMesh>::Save( S2,S2NewName.c_str(),saveMask);
}
// save error files.
if(flags & SamplingFlags::HIST)
{
ForwardSampling.GetHist().FileWrite("forward_result.csv");
BackwardSampling.GetHist().FileWrite("backward_result.csv");
}
return 0;
}
// -----------------------------------------------------------------------------------------------
+10
View File
@@ -0,0 +1,10 @@
TARGET = metro
DEPENDPATH += ../..
INCLUDEPATH += . ../.. ../../eigenlib
CONFIG += console stl c++11 debug_and_release
TEMPLATE = app
SOURCES += metro.cpp ../../wrap/ply/plylib.cpp
# Mac specific Config required to avoid to make application bundles
CONFIG -= app_bundle
+96
View File
@@ -0,0 +1,96 @@
VCGLib http://www.vcglib.net o o
Visual and Computer Graphics Library o o
_ O _
Copyright(C) 2005-2006 \/)\/
Visual Computing Lab http://vcg.isti.cnr.it /\/|
ISTI - Italian National Research Council |
\
Metro 4.07 2007/05/11
All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License (http://www.gnu.org/licenses/gpl.txt)
for more details.
--- Synopsis ---
Metro is a tool designed to evaluate the difference between two triangular meshes.
Metro adopts an approximated approach based on surface sampling and point-to-surface distance computation.
Please, when using this tool, cite the following reference:
P. Cignoni, C. Rocchini and R. Scopigno
"Metro: measuring error on simplified surfaces"
Computer Graphics Forum, Blackwell Publishers, vol. 17(2), June 1998, pp 167-174
For any question about this software please contact:
Paolo Cignoni ( paolo.cignoni@isti.cnr.it )
--- General Info ---
Metro is a tool designed to evaluate the difference between two triangular meshes.
Metro adopts an approximated approach based on surface sampling and point-to-surface distance computation.
Three different surface sampling methods are implemented:
* Montecarlo sampling (pick k random samples in the interior of each face)
* Subdivision sampling (recursively subdivide each face along the longest edge and choose the sample in the center of each cell)
* Similar Triangles sampling (subdivide each face F in k polygons similar to F and sample the face in correspondence with the vertices of these polygons, internal to F)
Note that the three methods described above are used to sample only the interior of each face.
A different scheme is used to sample vertices and edges: vertices are sampled in the straightforward manner,
while edges are sampled by uniformly interleaving samples along each edge.
Three different Spatial indexing structures can be used to find the closest point to a sample, a Statically Allocated Uniform Grid, a Hashed Uniform Grid and a Hierarchy of axis aligned bounding boxes.
--- Basic usage ---
Metro is a command-line tool which allows the user to select among different sampling schemes.
A list of the command-line parameters accepted by the tool is shown in the following.
Usage: Metro file1 file2 [opts]
where "file1" and "file2" are the input meshes in PLY, OFF or STL format, and opts can be:
-v disable vertex sampling
-e disable edge sampling
-f disable face sampling
-u ignore unreferred vertices
-sx set the face sampling mode
where x can be:
-s0 montecarlo sampling
-s1 subdivision sampling
-s2 similar triangles sampling (Default)
-n# set the required number of samples (overrides -A)
-a# set the required number of samples per area unit (overrides -N)
-c save a mesh with error as per-vertex colour and quality
-C # # Set the min/max values used for color mapping
-L Remove duplicated and unreferenced vertices before processing
-h write files with histograms of error distribution
-G Use a static Uniform Grid as Search Structure (default)
-A Use an Axis Aligned Bounding Box Tree as Search Structure
-H Use an Hashed Uniform Grid as Search Structure
-O Use an Octree as Search Structure
The -C option is useful in combination with -c option for creating a set of
meshes with a coherent coloring scheme.
It sets how the errors are mapped into color according to the following formula,
let e be the error and ColorRamp be a R->RGB function mapping 0..1 values
into a smooth RedYellowGreenCyanBlue ramp:
e=Clamp(e,min,max);
VertexColor = ColorRamp( (e-min)/(max-min) );
The Histogram files saved by the -h option contains two column of numbers
e_i and p_i; p_i denotes the fraction of the surface having an error
between e_i and e_{i+1}. The sum of the second column values should give 1.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
This directory contains four 3d models that can be used to test metro. The models represent the same toroidal knot at two different level of details.
- knot_orig.ply 12800 vertexes, 25600 triangles: the original high resolution mesh
- knot_subsampled.ply 800 vertexes, 1600 triangles: a low res model obtained by simple uniform subsampling
- knot_vcg_simplified.ply 800 vertexes, 1600 triangles: a low res model obtained by our library simplification code
- knot_max_simplified.stl 800 vertexes, 1600 triangles: a low res model obtained by using a commercial tool
+603
View File
@@ -0,0 +1,603 @@
/****************************************************************************
* VCGLib o o *
* Visual and Computer Graphics Library o o *
* _ O _ *
* Copyright(C) 2004-2016 \/)\/ *
* Visual Computing Lab /\/| *
* ISTI - Italian National Research Council | *
* \ *
* All rights reserved. *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt) *
* for more details. *
* *
****************************************************************************/
#ifndef __VCGLIB__SAMPLING
#define __VCGLIB__SAMPLING
#include <time.h>
#include <vcg/complex/algorithms/closest.h>
#include <vcg/space/box3.h>
#include <vcg/math/histogram.h>
#include <vcg/space/color4.h>
#include <vcg/simplex/face/distance.h>
#include <vcg/complex/algorithms/update/color.h>
#include <vcg/space/index/grid_static_ptr.h>
#include <vcg/space/index/aabb_binary_tree/aabb_binary_tree.h>
#include <vcg/space/index/octree.h>
#include <vcg/space/index/spatial_hashing.h>
namespace vcg
{
struct SamplingFlags{
enum{
HIST = 0x0001,
VERTEX_SAMPLING = 0x0002,
EDGE_SAMPLING = 0x0004,
FACE_SAMPLING = 0x0008,
MONTECARLO_SAMPLING = 0x0010,
SUBDIVISION_SAMPLING = 0x0020,
SIMILAR_SAMPLING = 0x0040,
NO_SAMPLING = 0x0070,
SAVE_ERROR = 0x0100,
INCLUDE_UNREFERENCED_VERTICES = 0x0200,
USE_STATIC_GRID = 0x0400,
USE_HASH_GRID = 0x0800,
USE_AABB_TREE = 0x1000,
USE_OCTREE = 0x2000
};
};
// -----------------------------------------------------------------------------------------------
template <class MetroMesh>
class Sampling
{
public:
private:
typedef typename MetroMesh::CoordType CoordType;
typedef typename MetroMesh::ScalarType ScalarType;
typedef typename MetroMesh::VertexType VertexType;
typedef typename MetroMesh::VertexPointer VertexPointer;
typedef typename MetroMesh::VertexIterator VertexIterator;
typedef typename MetroMesh::FaceIterator FaceIterator;
typedef typename MetroMesh::FaceType FaceType;
typedef typename MetroMesh::FaceContainer FaceContainer;
typedef GridStaticPtr <FaceType, typename MetroMesh::ScalarType > MetroMeshGrid;
typedef SpatialHashTable <FaceType, typename MetroMesh::ScalarType > MetroMeshHash;
typedef AABBBinaryTreeIndex <FaceType, typename MetroMesh::ScalarType, vcg::EmptyClass> MetroMeshAABB;
typedef Octree <FaceType, typename MetroMesh::ScalarType > MetroMeshOctree;
typedef Point3<typename MetroMesh::ScalarType> Point3x;
// data structures
MetroMesh &S1;
MetroMesh &S2;
MetroMeshGrid gS2;
MetroMeshHash hS2;
MetroMeshAABB tS2;
MetroMeshOctree oS2;
unsigned int n_samples_per_face ;
float n_samples_edge_to_face_ratio ;
float bbox_factor ;
float inflate_percentage ;
unsigned int min_size ;
int n_hist_bins ;
int print_every_n_elements ;
int referredBit ;
// parameters
double dist_upper_bound;
double n_samples_per_area_unit;
unsigned long n_samples_target;
int Flags;
// results
Histogram<double> hist;
unsigned long n_total_samples;
unsigned long n_total_area_samples;
unsigned long n_total_edge_samples;
unsigned long n_total_vertex_samples;
double max_dist;
double mean_dist;
double RMS_dist;
double volume;
double area_S1;
// globals
int n_samples;
// private methods
inline double ComputeMeshArea(MetroMesh & mesh);
float AddSample(const Point3x &p);
inline void AddRandomSample(FaceIterator &T);
inline void SampleEdge(const Point3x & v0, const Point3x & v1, int n_samples_per_edge);
void VertexSampling();
void EdgeSampling();
void FaceSubdiv(const Point3x & v0, const Point3x &v1, const Point3x & v2, int maxdepth);
void SimilarTriangles(const Point3x &v0, const Point3x &v1, const Point3x &v2, int n_samples_per_edge);
void MontecarloFaceSampling();
void SubdivFaceSampling();
void SimilarFaceSampling();
public :
// public methods
Sampling(MetroMesh &_s1, MetroMesh &_s2);
~Sampling();
void Hausdorff();
double GetArea() {return area_S1;}
double GetDistMax() {return max_dist;}
double GetDistMean() {return mean_dist;}
double GetDistRMS() {return RMS_dist;}
double GetDistVolume() {return volume;}
unsigned long GetNSamples() {return n_total_samples;}
unsigned long GetNAreaSamples() {return n_total_area_samples;}
unsigned long GetNEdgeSamples() {return n_total_edge_samples;}
unsigned long GetNVertexSamples() {return n_total_vertex_samples;}
double GetNSamplesPerAreaUnit() {return n_samples_per_area_unit;}
unsigned long GetNSamplesTarget() {return n_samples_target;}
Histogram<double> &GetHist() {return hist;}
void SetFlags(int flags) {Flags = flags;}
void ClearFlag(int flag) {Flags &= (flag ^ -1);}
void SetParam(double _n_samp) {n_samples_target = _n_samp;}
void SetSamplesTarget(unsigned long _n_samp);
void SetSamplesPerAreaUnit(double _n_samp);
};
// -----------------------------------------------------------------------------------------------
// constructor
template <class MetroMesh>
Sampling<MetroMesh>::Sampling(MetroMesh &_s1, MetroMesh &_s2):S1(_s1),S2(_s2)
{
Flags = 0;
area_S1 = ComputeMeshArea(_s1);
// set default numbers
n_samples_per_face = 10;
n_samples_edge_to_face_ratio = 0.1f;
bbox_factor = 0.1f;
inflate_percentage = 0.02f;
min_size = 125; /* 125 = 5^3 */
n_hist_bins = 256;
print_every_n_elements = S1.fn/100;
if(print_every_n_elements <= 1)
print_every_n_elements = 2;
referredBit = VertexType::NewBitFlag();
// store the unreferred vertices
FaceIterator fi; VertexIterator vi; int i;
for(fi = _s1.face.begin(); fi!= _s1.face.end(); ++fi)
for(i=0;i<3;++i) (*fi).V(i)->SetUserBit(referredBit);
}
template <class MetroMesh>
Sampling<MetroMesh>::~Sampling()
{
VertexType::DeleteBitFlag(referredBit);
}
// set sampling parameters
template <class MetroMesh>
void Sampling<MetroMesh>::SetSamplesTarget(unsigned long _n_samp)
{
n_samples_target = _n_samp;
n_samples_per_area_unit = n_samples_target / (double)area_S1;
}
template <class MetroMesh>
void Sampling<MetroMesh>::SetSamplesPerAreaUnit(double _n_samp)
{
n_samples_per_area_unit = _n_samp;
n_samples_target = (unsigned long)((double) n_samples_per_area_unit * area_S1);
}
// auxiliary functions
template <class MetroMesh>
inline double Sampling<MetroMesh>::ComputeMeshArea(MetroMesh & mesh)
{
FaceIterator face;
double area = 0.0;
for(face=mesh.face.begin(); face != mesh.face.end(); face++)
if(!(*face).IsD())
area += DoubleArea(*face);
return area/2.0;
}
template <class MetroMesh>
float Sampling<MetroMesh>::AddSample(const Point3x &p )
{
FaceType *f=0;
Point3x normf, bestq, ip;
ScalarType dist;
dist = dist_upper_bound;
// compute distance between p_i and the mesh S2
if(Flags & SamplingFlags::USE_AABB_TREE)
f=tri::GetClosestFaceEP<MetroMesh,MetroMeshAABB>(S2, tS2, p, dist_upper_bound, dist, normf, bestq, ip);
if(Flags & SamplingFlags::USE_HASH_GRID)
f=tri::GetClosestFaceEP<MetroMesh,MetroMeshHash>(S2, hS2, p, dist_upper_bound, dist, normf, bestq, ip);
if(Flags & SamplingFlags::USE_STATIC_GRID)
f=tri::GetClosestFaceEP<MetroMesh,MetroMeshGrid>(S2, gS2, p, dist_upper_bound, dist, normf, bestq, ip);
if (Flags & SamplingFlags::USE_OCTREE)
f=tri::GetClosestFaceEP<MetroMesh,MetroMeshOctree>(S2, oS2, p, dist_upper_bound, dist, normf, bestq, ip);
// update distance measures
if(dist == dist_upper_bound)
return -1.0;
if(dist > max_dist)
max_dist = dist; // L_inf
mean_dist += dist; // L_1
RMS_dist += dist*dist; // L_2
n_total_samples++;
if(Flags & SamplingFlags::HIST)
hist.Add((float)fabs(dist));
return (float)dist;
}
// -----------------------------------------------------------------------------------------------
// --- Vertex Sampling ---------------------------------------------------------------------------
template <class MetroMesh>
void Sampling<MetroMesh>::VertexSampling()
{
// Vertex sampling.
int cnt = 0;
float error;
printf("Vertex sampling\n");
VertexIterator vi;
typename std::vector<VertexPointer>::iterator vif;
for(vi=S1.vert.begin();vi!=S1.vert.end();++vi)
if( (*vi).IsUserBit(referredBit) || // it is referred
((Flags&SamplingFlags::INCLUDE_UNREFERENCED_VERTICES) != 0) ) //include also unreferred
{
error = AddSample((*vi).cP());
n_total_vertex_samples++;
// save vertex quality
if(Flags & SamplingFlags::SAVE_ERROR) (*vi).Q() = error;
// print progress information
if(!(++cnt % print_every_n_elements))
printf("Sampling vertices %d%%\r", (100 * cnt/S1.vn));
}
printf(" \r");
}
// -----------------------------------------------------------------------------------------------
// --- Edge Sampling -----------------------------------------------------------------------------
template <class MetroMesh>
inline void Sampling<MetroMesh>::SampleEdge(const Point3x & v0, const Point3x & v1, int n_samples_per_edge)
{
// uniform sampling of the segment v0v1.
Point3x e((v1-v0)/(double)(n_samples_per_edge+1));
int i;
for(i=1; i <= n_samples_per_edge; i++)
{
AddSample(v0 + e*i);
n_total_edge_samples++;
}
}
template <class MetroMesh>
void Sampling<MetroMesh>::EdgeSampling()
{
// Edge sampling.
typedef std::pair<VertexPointer, VertexPointer> pvv;
std::vector< pvv > Edges;
printf("Edge sampling\n");
// compute edge list.
FaceIterator fi;
for(fi=S1.face.begin(); fi != S1.face.end(); fi++)
for(int i=0; i<3; ++i)
{
Edges.push_back(std::make_pair((*fi).V0(i),(*fi).V1(i)));
if(Edges.back().first > Edges.back().second)
std::swap(Edges.back().first, Edges.back().second);
}
sort(Edges.begin(), Edges.end());
typename std::vector< pvv>::iterator edgeend = unique(Edges.begin(), Edges.end());
Edges.resize(edgeend-Edges.begin());
// sample edges.
typename std::vector<pvv>::iterator ei;
double n_samples_per_length_unit;
double n_samples_decimal = 0.0;
int cnt=0;
if(Flags & SamplingFlags::FACE_SAMPLING)
n_samples_per_length_unit = sqrt((double)n_samples_per_area_unit);
else
n_samples_per_length_unit = n_samples_per_area_unit;
for(ei=Edges.begin(); ei!=Edges.end(); ++ei)
{
n_samples_decimal += Distance((*ei).first->cP(),(*ei).second->cP()) * n_samples_per_length_unit;
n_samples = (int) n_samples_decimal;
SampleEdge((*ei).first->cP(), (*ei).second->cP(), (int) n_samples);
n_samples_decimal -= (double) n_samples;
// print progress information
if(!(++cnt % print_every_n_elements))
printf("Sampling edge %lu%%\r", (100 * cnt/Edges.size()));
}
printf(" \r");
}
// -----------------------------------------------------------------------------------------------
// --- Face Sampling -----------------------------------------------------------------------------
// Montecarlo sampling.
template <class MetroMesh>
inline void Sampling<MetroMesh>::AddRandomSample(FaceIterator &T)
{
// random sampling over the input face.
double rnd_1, rnd_2;
// vertices of the face T.
Point3x p0(T->V(0)->cP());
Point3x p1(T->V(1)->cP());
Point3x p2(T->V(2)->cP());
// calculate two edges of T.
Point3x v1(p1 - p0);
Point3x v2(p2 - p0);
// choose two random numbers.
rnd_1 = (double)rand() / (double)RAND_MAX;
rnd_2 = (double)rand() / (double)RAND_MAX;
if(rnd_1 + rnd_2 > 1.0)
{
rnd_1 = 1.0 - rnd_1;
rnd_2 = 1.0 - rnd_2;
}
// add a random point on the face T.
AddSample (p0 + (v1 * rnd_1 + v2 * rnd_2));
n_total_area_samples++;
}
template <class MetroMesh>
void Sampling<MetroMesh>::MontecarloFaceSampling()
{
// Montecarlo sampling.
double n_samples_decimal = 0.0;
FaceIterator fi;
srand(clock());
// printf("Montecarlo face sampling\n");
for(fi=S1.face.begin(); fi != S1.face.end(); fi++)
if(!(*fi).IsD())
{
// compute # samples in the current face.
n_samples_decimal += 0.5*DoubleArea(*fi) * n_samples_per_area_unit;
n_samples = (int) n_samples_decimal;
// for every sample p_i in T...
for(int i=0; i < n_samples; i++)
AddRandomSample(fi);
n_samples_decimal -= (double) n_samples;
// print progress information
// if(!(++cnt % print_every_n_elements))
// printf("Sampling face %d%%\r", (100 * cnt/S1.fn));
}
// printf(" \r");
}
// Subdivision sampling.
template <class MetroMesh>
void Sampling<MetroMesh>::FaceSubdiv(const Point3x & v0, const Point3x & v1, const Point3x & v2, int maxdepth)
{
// recursive face subdivision.
if(maxdepth == 0)
{
// ground case.
AddSample((v0+v1+v2)/3.0f);
n_total_area_samples++;
n_samples++;
return;
}
// compute the longest edge.
double maxd01 = SquaredDistance(v0,v1);
double maxd12 = SquaredDistance(v1,v2);
double maxd20 = SquaredDistance(v2,v0);
int res;
if(maxd01 > maxd12)
if(maxd01 > maxd20) res = 0;
else res = 2;
else
if(maxd12 > maxd20) res = 1;
else res = 2;
// break the input triangle along the median to the the longest edge.
Point3x pp;
switch(res)
{
case 0 : pp = (v0+v1)/2;
FaceSubdiv(v0,pp,v2,maxdepth-1);
FaceSubdiv(pp,v1,v2,maxdepth-1);
break;
case 1 : pp = (v1+v2)/2;
FaceSubdiv(v0,v1,pp,maxdepth-1);
FaceSubdiv(v0,pp,v2,maxdepth-1);
break;
case 2 : pp = (v2+v0)/2;
FaceSubdiv(v0,v1,pp,maxdepth-1);
FaceSubdiv(pp,v1,v2,maxdepth-1);
break;
}
}
template <class MetroMesh>
void Sampling<MetroMesh>::SubdivFaceSampling()
{
// Subdivision sampling.
int cnt = 0, maxdepth;
double n_samples_decimal = 0.0;
typename MetroMesh::FaceIterator fi;
printf("Subdivision face sampling\n");
for(fi=S1.face.begin(); fi != S1.face.end(); fi++)
{
// compute # samples in the current face.
n_samples_decimal += 0.5*DoubleArea(*fi) * n_samples_per_area_unit;
n_samples = (int) n_samples_decimal;
if(n_samples)
{
// face sampling.
maxdepth = ((int)(log((double)n_samples)/log(2.0)));
n_samples = 0;
FaceSubdiv((*fi).V(0)->cP(), (*fi).V(1)->cP(), (*fi).V(2)->cP(), maxdepth);
}
n_samples_decimal -= (double) n_samples;
// print progress information
if(!(++cnt % print_every_n_elements))
printf("Sampling face %d%%\r", (100 * cnt/S1.fn));
}
printf(" \r");
}
// Similar Triangles sampling.
template <class MetroMesh>
void Sampling<MetroMesh>::SimilarTriangles(const Point3x & v0, const Point3x & v1, const Point3x & v2, int n_samples_per_edge)
{
Point3x V1((v1-v0)/(double)(n_samples_per_edge-1));
Point3x V2((v2-v0)/(double)(n_samples_per_edge-1));
int i, j;
// face sampling.
for(i=1; i < n_samples_per_edge-1; i++)
for(j=1; j < n_samples_per_edge-1-i; j++)
{
AddSample( v0 + (V1*(double)i + V2*(double)j) );
n_total_area_samples++;
n_samples++;
}
}
template <class MetroMesh>
void Sampling<MetroMesh>::SimilarFaceSampling()
{
// Similar Triangles sampling.
int cnt = 0, n_samples_per_edge;
double n_samples_decimal = 0.0;
FaceIterator fi;
printf("Similar Triangles face sampling\n");
for(fi=S1.face.begin(); fi != S1.face.end(); fi++)
{
// compute # samples in the current face.
n_samples_decimal += 0.5*DoubleArea(*fi) * n_samples_per_area_unit;
n_samples = (int) n_samples_decimal;
if(n_samples)
{
// face sampling.
n_samples_per_edge = (int)((sqrt(1.0+8.0*(double)n_samples) +5.0)/2.0);
n_samples = 0;
SimilarTriangles((*fi).V(0)->cP(), (*fi).V(1)->cP(), (*fi).V(2)->cP(), n_samples_per_edge);
}
n_samples_decimal -= (double) n_samples;
// print progress information
if(!(++cnt % print_every_n_elements))
printf("Sampling face %d%%\r", (100 * cnt/S1.fn));
}
printf(" \r");
}
// -----------------------------------------------------------------------------------------------
// --- Distance ----------------------------------------------------------------------------------
template <class MetroMesh>
void Sampling<MetroMesh>::Hausdorff()
{
Box3< ScalarType> bbox;
// set grid meshes.
if(Flags & SamplingFlags::USE_HASH_GRID) hS2.Set(S2.face.begin(),S2.face.end());
if(Flags & SamplingFlags::USE_AABB_TREE) tS2.Set(S2.face.begin(),S2.face.end());
if(Flags & SamplingFlags::USE_STATIC_GRID) gS2.Set(S2.face.begin(),S2.face.end());
if(Flags & SamplingFlags::USE_OCTREE) oS2.Set(S2.face.begin(),S2.face.end());
// set bounding box
bbox = S2.bbox;
dist_upper_bound = /*bbox_factor * */bbox.Diag();
if(Flags & SamplingFlags::HIST)
hist.SetRange(0.0, dist_upper_bound/100.0, n_hist_bins);
// initialize sampling statistics.
n_total_area_samples = n_total_edge_samples = n_total_vertex_samples = n_total_samples = n_samples = 0;
max_dist = -HUGE_VAL;
mean_dist = RMS_dist = 0;
// Vertex sampling.
if(Flags & SamplingFlags::VERTEX_SAMPLING)
VertexSampling();
// Edge sampling.
if(n_samples_target > n_total_samples)
{
n_samples_target -= (int) n_total_samples;
n_samples_per_area_unit = n_samples_target / area_S1;
if(Flags & SamplingFlags::EDGE_SAMPLING)
{
EdgeSampling();
if(n_samples_target > n_total_samples) n_samples_target -= (int) n_total_samples;
else n_samples_target=0;
}
// Face sampling.
if((Flags & SamplingFlags::FACE_SAMPLING) && (n_samples_target > 0))
{
n_samples_per_area_unit = n_samples_target / area_S1;
if(Flags & SamplingFlags::MONTECARLO_SAMPLING) MontecarloFaceSampling();
if(Flags & SamplingFlags::SUBDIVISION_SAMPLING) SubdivFaceSampling();
if(Flags & SamplingFlags::SIMILAR_SAMPLING) SimilarFaceSampling();
}
}
// compute vertex colour
if(Flags & SamplingFlags::SAVE_ERROR)
vcg::tri::UpdateColor<MetroMesh>::PerVertexQualityRamp(S1);
// compute statistics
n_samples_per_area_unit = (double) n_total_samples / area_S1;
volume = mean_dist / n_samples_per_area_unit / 2.0;
mean_dist /= n_total_samples;
RMS_dist = sqrt(RMS_dist / n_total_samples);
}
}
#endif