namespace CGAL {
/*!
\mainpage User Manual
\anchor Chapter_PolygonMeshProcessing

\cgalAutoToc
\authors Sébastien Loriot, Jane Tournois, Ilker %O. Yaz

\image html neptun_head.jpg
\image latex neptun_head.jpg
<BR>

\section PMPIntroduction Introduction

This package implements a collection of methods and classes for polygon mesh processing,
ranging from basic operations on simplices, to complex geometry processing algorithms.
The implementation of this package mainly follows algorithms and references
given in Botsch et al.'s book on polygon mesh processing \cgalCite{botsch2010PMP}.

\subsection PMPDef Polygon Mesh
A \a polygon \a mesh is a consistent and orientable surface mesh, that can have
one or more boundaries.
The \a faces are simple polygons.
The \a edges are segments. Each edge connects two \a vertices,
and is shared by two faces (including the \a null \a face for boundary edges).
A polygon mesh can have any number of connected components, and also some self-intersections.
In this package, a polygon mesh is considered to have the topology of a 2-manifold.

\subsection PMPAPI API
This package follows the BGL API described in \ref chapterBGL.
It can thus be used either with `Polyhedron_3`, `Surface_mesh`, or
any class model of the concept `FaceGraph`. Each function or class of this package
details the requirements on the input polygon mesh.

BGL \ref namedparameters are used to deal with optional parameters.

\subsection PMPOutline Outline
The algorithms described in this manual are organized in sections.
Section 2 describes \ref PMPMeshing algorithms, including triangulation of non-triangulated
meshes, refinement, optimization by fairing, and isotropic remeshing of triangulated surface meshes.
Section 3 lists the available, \ref PMPHoleFilling algorithms, which can possibly be combined with refinement and fairing.
Section 4 gives a list of \ref PMPPredicates that can be evaluated on the processed polygon
mesh, including point location and self intersection tests.
Tools for checking or fixing the \ref PMPOrientation are then described.
Section 5 deals with \ref PMPRepairing of polygon meshes and polygon soups.
Section 6 offers algorithms for \ref PMPNormalComp at vertices and on faces of a polygon mesh.
Section 7 describes a class that provides an operator able to compute intersections
of the a polygon mesh with arbitrary planes, called \ref PMPSlicer.
Section 8 deals with methods to compute \ref PMPConnectedComponents
of a polygon mesh, and discard the smallest ones.

\todo Section 9 provides some extensive examples of how a polygon mesh can be treated using this package.

****************************************
\section PMPMeshing Meshing

A surface patch can be refined by inserting new vertices and flipping edges to get a triangulation.
Using a criterion presented in \cgalCite{liepa2003filling},
the density of triangles near the boundary of the patch is approximated by the refinement function.
The validity of the mesh is enforced by flipping edges.
An edge is flipped only if the opposite edge does not exist in the original mesh
and if no degenerate triangles are generated.

A region of the surface mesh (\e e.\e g. the refined region), can be faired
to obtain a tangentially continuous and smooth surface patch.
The region to be faired is defined as a range of vertices that are relocated.
The fairing step minimizes a linear bi-Laplacian system with boundary constraints,
described in \cgalCite{Botsch2008OnLinearVariational}.
The visual results of aforementioned steps are depicted by \cgalFigureRef{Mech_steps} (c and d).

\subsection MeshingAPI API

\subsubsection Meshing

Refinement and fairing functions can be applied to an arbitrary region on a triangle mesh, using :
- `CGAL::Polygon_mesh_processing::refine()` : given a set of facets on a mesh, refines the region.
- `CGAL::Polygon_mesh_processing::fair()` : given a set of vertices on a mesh, fairs the region.

Fairing needs a sparse linear solver and we recommend the use of \ref thirdpartyEigen 3.2 or later.
Note that fairing might fail if fixed vertices, which are used as boundary conditions, do
not suffice to solve the constructed linear system.

Many algorithms require as input meshes in which all the faces have the same degree,
or even are triangles. Hence, one may want to triangulate all polygon faces of a mesh.

This package provides the function `CGAL::Polygon_mesh_processing::triangulate_faces()`
that triangulates all faces of the input polygon mesh.
An approximated support plane is chosen for each face, orthogonal to the normal vector
computed by `CGAL::Polygon_mesh_processing::compute_face_normal()`.
Then, the triangulation of each face is the one obtained by building a
`CGAL::Constrained_Delaunay_triangulation_2` in this plane.
This choice is made because the constrained Delaunay triangulation
is the triangulation that, given the edges of the face to be triangulated,
maximizes the minimum angle of all the angles of the triangles in the triangulation.

\subsubsection Remeshing

The incremental triangle-based isotropic remeshing algorithm introduced by Botsch et al
 \cgalCite{botsch2004remeshing}, \cgalCite{botsch2010PMP} is implemented in this package.
This algorithm incrementally performs simple operations such as edge splits, edge collapses,
edge flips, and Laplacian smoothing. All the vertices of the remeshed patch are reprojected
to the original surface to keep a good approximation of the input.

A triangulated region of a polygon mesh can be remeshed using the function
`CGAL::Polygon_mesh_processing::isotropic_remeshing()`, as illustrated
by \cgalFigureRef{iso_remeshing}. The algorithm has only two parameters :
the target edge length for the remeshed surface patch, and
the number of iterations of the abovementioned sequence of operations. The bigger
this number, the smoother and closer to target edge length the mesh will be.

An additional option has been added to \e protect (\e i.\e e. not modify) some given polylines.
In some cases, those polylines are too long, and reaching the desired target edge length while protecting them is not
possible and leads to an infinite loop of edge splits in the incident faces. To avoid that pitfall, the
function `CGAL::Polygon_mesh_processing::split_long_edges()` should be called on the list of
constrained edges before remeshing.

\cgalFigureBegin{iso_remeshing, iso_remeshing.png}
Isotropic remeshing. (a) Triangulated input surface mesh.
(b) Surface uniformly and entirely remeshed.
(c) Selection of a range of faces to be remeshed.
(d) Surface mesh with the selection uniformly remeshed.
\cgalFigureEnd


\subsection MeshingExamples Meshing Examples

\subsubsection MeshingExample_1 Refine and Fair a Region on a Triangle Mesh

The following example calls the functions `CGAL::Polygon_mesh_processing::refine()`
and `CGAL::Polygon_mesh_processing::fair()` for some selected regions on the input triangle mesh.

\cgalExample{Polygon_mesh_processing/refine_fair_example.cpp}

\subsubsection MeshingExample_2 Triangulate a Polygon Mesh

Triangulating a polygon mesh can be achieved through the function
`CGAL::Polygon_mesh_processing::triangulate_faces()`
as shown in the following example.

\cgalExample{Polygon_mesh_processing/triangulate_faces_example.cpp}


\subsubsection RemeshingExample_1 Isotropic Remeshing of a Region on a Polygon Mesh

The following example shows a complete example of how the isotropic remeshing function can be used.
First, the border of the polygon mesh is collected.
Since the boundary edges will be considered as constrained and protected in this example, the function `split_long_edges()` is called first on these edges.

Once this is done, remeshing is run on all the surface, with protection of constraints activated, for 3 iterations.

\cgalExample{Polygon_mesh_processing/isotropic_remeshing_example.cpp}


********************************************
\section PMPHoleFilling Hole Filling

This package provides an algorithm for filling one closed hole that is either in a triangulated surface mesh
or defined by a sequence of points that describe a polyline.
The main steps of the algorithm are described in \cgalCite{liepa2003filling} and can be summarized as follows.

First, the largest patch triangulating the boundary of the hole is generated without introducing any new vertex. 
The patch is selected so as to minimize a quality function evaluated for all possible triangular patches.
The quality function first minimizes the worst dihedral angle between patch triangles,
then the total surface area of the patch as a tiebreaker.
Following the suggestions in \cgalCite{zou2013algorithm}, the performance of the algorithm is significantly improved
by narrowing the search space to faces of a 3D Delaunay triangulation of the hole boundary vertices,
from all possible patches, while searching for the best patch with respect to the
aforementioned quality criteria.

For some complicated input hole boundary, the generated patch may have self-intersections.
After hole filling, the generated patch can be refined and faired using the meshing functions
`CGAL::Polygon_mesh_processing::refine()` and `CGAL::Polygon_mesh_processing::fair()`
described in Section \ref PMPMeshing.

\cgalFigureBegin{Mech_steps, mech_hole_horz.jpg}
Results of the main steps of the algorithm.
From left to right: (a) the hole,
(b) the hole after its triangulation,
(c) after triangulation and refinement,
(d) after triangulation, refinement and fairing.
\cgalFigureEnd


\subsection HoleFillingAPI API

This package provides four functions for hole filling:
	- `triangulate_hole_polyline()` : given a sequence of points defining the hole, triangulates the hole.
	- `triangulate_hole()` : given a border halfedge on the boundary of the hole on a mesh, triangulates the hole.
	- `triangulate_and_refine_hole()` : in addition to `triangulate_hole()` the generated patch is refined.
	- `triangulate_refine_and_fair_hole()` : in addition to `triangulate_and_refine_hole()` the generated patch is also faired.

\subsection HFExamples Examples

\subsubsection HFExample_1 Triangulate a Polyline

The following example triangulates a hole described by an input polyline.

\cgalExample{Polygon_mesh_processing/triangulate_polyline_example.cpp}


\subsubsection HFExample_2 Hole Filling From the Border of the Hole

If the input polygon mesh has a hole or more than one hole, it is possible
to iteratively fill them by detecting border edges (i.e. with only
one incident non-null face) after each hole filling step.

Holes are filled one after the other, and the process stops when there is no border edge left.

This process is illustrated by the example below, where holes are
iteratively filled, refined and faired to get a faired mesh with no hole.


\cgalExample{Polygon_mesh_processing/hole_filling_example.cpp}

 \cgalFigureBegin{Triangulated_fork, fork.jpg}
 Holes in the fork model are filled with triangle patches.
 \cgalFigureEnd


***************************************
\section PMPPredicates Predicates

This packages provides several predicates to be evaluated with respect to a triangle mesh.

\subsection PMPSelIntersections Self Intersections

Self intersections can be detected from a triangle mesh, by calling the predicate
`CGAL::Polygon_mesh_processing::does_self_intersect()`.
Additionally, the function `CGAL::Polygon_mesh_processing::self_intersections()`
records all pairs of intersecting triangles.

\cgalFigureBegin{SelfIntersections, selfintersections.jpg}
Detecting self-intersections on a triangle mesh.
The intersecting triangles are displayed in dark grey on the right image.
\cgalFigureEnd

\subsubsection SIExample Self Intersections Example
\cgalExample{Polygon_mesh_processing/self_intersections_example.cpp}


\subsection PMPInsideTest Side of Triangle Mesh

The class `CGAL::Side_of_triangle_mesh` provides a functor that tests whether a query point is 
inside, outside, or on the boundary of the domain bounded by a given closed triangle mesh.

A point is said to be on the bounded side of the domain bounded by the input triangle mesh
if an odd number of surfaces is crossed when walking from the point to infinity.
The input triangle mesh is expected to contain no self-intersections
and to be free from self-inclusions.

The algorithm can handle the case of a triangle mesh with several connected components,
and returns correct results.
In case of self-inclusions, the ray intersections parity test is performed,
and the execution will not fail.
However, the user should be aware that the predicate
alternately considers sub-volumes to be on the bounded and unbounded sides of the
input triangle mesh.

\subsubsection InsideExample Inside Test Example
\cgalExample{Polygon_mesh_processing/point_inside_example.cpp}


****************************************
\section PMPOrientation Orientation

This package provides functions dealing with the orientation of faces in a closed polygon mesh.

The function `CGAL::Polygon_mesh_processing::is_outward_oriented()` checks whether
an oriented polygon mesh is oriented such that the normals to all faces are oriented towards the
outside of the domain bounded by the input polygon mesh.

The function
`CGAL::Polygon_mesh_processing::reverse_face_orientations()` reverses the orientation
of halfedges around faces.
As a consequence, the normal computed for each face (see Section
\ref PMPNormalComp) is also reversed.

The \ref PolygonSoupExample puts these functions at work on a polygon soup.


****************************************
\section PMPRepairing Combinatorial Repairing 
*******************
\subsection Stitching

It happens that a polygon mesh has several edges and vertices that are duplicated.
For those edges and vertices, the connectivity of the mesh is incomplete, if not considered incorrect.

Stitching the borders of such a polygon mesh consists in two main steps.
First, border edges that are similar but duplicated are detected and paired.
Then, they are "stitched" together so that the edges and vertices duplicates are removed
from the mesh, and each of these remaining edges is incident to exactly two faces.

The function \link PMP_repairing_grp `CGAL::Polygon_mesh_processing::stitch_borders()` \endlink
 performs such repairing operation. The input mesh should be manifold.
Otherwise, stitching is not guaranteed to succeed.

\subsubsection StitchingExample Stitching Example

The following example applies the stitching operation to a simple quad mesh
with duplicated border edges.

\cgalExample{Polygon_mesh_processing/stitch_borders_example.cpp}

*******************
<!---
\subsection DegenerateFaces Removing Degenerate Faces

Some degenerate faces may be part of a given triangle mesh.
A face is considered \e degenerate if two of its vertices
share the same location,
or in general if its three vertices are collinear.
The function
`CGAL::Polygon_mesh_processing::remove_degenerate_faces()`
removes those faces and fixes the connectivity of the newly cleaned up mesh.
It is also possible to remove isolated vertices from any polygon mesh, using the function
`CGAL::Polygon_mesh_processing::remove_isolated_vertices()`.

\subsubsection RemoveDegenerateExample Example

In the following example, the degenerate faces of a triangle mesh
are removed, the connectivity is fixed, and the number of removed faces
is output.

\cgalExample{Polygon_mesh_processing/remove_degeneracies_example.cpp}
--->

*******************
\subsection PolygonSoups Polygon Soups

When the faces of a polygon mesh are given but the connectivity is unknown,
we must deal with of a \e polygon \e soup.

Before running any of the algorithms on the so-called 
polygon soup, one should ensure that the polygons are consistently oriented.
To do so, this package provides the function
`CGAL::Polygon_mesh_processing::orient_polygon_soup()`,
described in \cgalCite{gueziec2001cutting}.

To deal with polygon soups that cannot be converted to a
combinatorial manifold surface, some points are duplicated.
Because a polygon soup does not have any connectivity (each point
has as many occurences as the number of polygons it belongs to),
duplicating one point (or a pair of points)
amounts to duplicate the polygon to which it belongs.

The duplicated points are either an endpoint of an edge incident to more
than two polygons, an endpoint of an edge between
two polygons with incompatible orientations (during the re-orientation process),
or more generally a point \a p at which the intersection
of an infinitesimally small ball centered at \a p
with the polygons incident to it is not a topological disk.

Once the polygon soup is consistently oriented,
with possibly duplicated (or more) points,
the connectivity can be recovered and made consistent
to build a valid polygon mesh.
The function `CGAL::Polygon_mesh_processing::polygon_soup_to_polygon_mesh()`
performs this mesh construction step.


\subsubsection PolygonSoupExample Polygon Soup Example

This example shows how to generate a mesh from a polygon soup.
The first step is to get a soup of consistently oriented faces, before
rebuilding the connectivity.
In this example, some orientation tests are performed on the output
polygon mesh to illustrate
Section \ref PMPOrientation.

\cgalExample{Polygon_mesh_processing/polygon_soup_example.cpp}



****************************************
\section PMPNormalComp Computing Normals

This package provides methods to compute normals on the polygon mesh.
The normal can either be computed for each single face,
or estimated for each vertex, as the average of its incident face normals.
These computations are performed with :
- `CGAL::Polygon_mesh_processing::compute_face_normal()`
- `CGAL::Polygon_mesh_processing::compute_vertex_normal()`

We further provide functions to compute all the normals to faces,
or to vertices, or to both :
- `CGAL::Polygon_mesh_processing::compute_face_normals()`
- `CGAL::Polygon_mesh_processing::compute_vertex_normals()`
- `CGAL::Polygon_mesh_processing::compute_normals()`.

Property maps are used to record the computed normals.


\subsection NormalsExample Normals Computation Example

The following example illustrates how to
compute the normals to faces and vertices
and store them in property maps.

\cgalExample{Polygon_mesh_processing/compute_normals_example.cpp}


****************************************
\section PMPSlicer Slicer

The `CGAL::Polygon_mesh_slicer` is an operator that intersects a triangle surface
mesh with a plane. It records the intersection as a set of polylines since the intersection
can be made of more than one connected component. The degenerate case
where the intersection is a single point is handled.

\cgalFigureRef{SlicerFig} shows
the polylines returned by the slicing operation for a triangle mesh
and a set of parallel planes.

\cgalFigureBegin{SlicerFig, slicer.jpg}
Slicing a mesh. A triangle mesh (left) and the polylines
computed by the mesh slicer by intersecting
a set of parallel planes (right).
\cgalFigureEnd

\subsection SlicerExample Slicer Example

The example below illustrates how to use the mesh slicer for a given
triangle mesh and a plane. Two constructors are used in the example
for pedagogical purposes.

\cgalExample{Polygon_mesh_processing/mesh_slicer_example.cpp}

****************************************
\section PMPConnectedComponents Connected Components

This package provides functions to enumerate and store
the connected components of a polygon mesh.
The connected components can be either closed and geometrically separated,
or separated by border or user-specified \e constraint edges.

First, the function `CGAL::Polygon_mesh_processing::connected_component()`
collects all the faces that belong to the same connected component as
the face that is given as a parameter.

Then, `CGAL::Polygon_mesh_processing::connected_components()`
collects all the connected components, and fills a property map
with the indices of the different connected components.

The functions `CGAL::Polygon_mesh_processing::keep_connected_components()`
and `CGAL::Polygon_mesh_processing::remove_connected_components()`
enable the user to keep and remove only a selection of connected components,
provided either as a range of faces that belong to the desired connected components
or as a range of connected component ids (one or more per connected component).

Finally, `CGAL::Polygon_mesh_processing::keep_largest_connected_components()`
enables the user to keep only the largest connected components. This feature can
for example be useful for noisy data were small connected components
should be discarded in favour of major connected components.


\subsection CCExample Connected Components Example

The following example shows how to record the connected
components of a polygon mesh.
In particular, we provide an example for the optional parameter \c EdgeConstraintMap,
a property map that returns information about an edge being a \e constraint or not.
A \e constraint provides a mean to demarcate the border of a connected component, and prevents
the propagation of a connected component index to cross it.

\cgalExample{Polygon_mesh_processing/connected_components_example.cpp}


****************************************
\section PMPAll Requirements Summary

The table below recapitulates the basic requirements of each function of this package.
For each requirement, the table answers a question :
- should the input mesh be a pure triangle mesh?
- should the input mesh be self-intersection free?
- should the input mesh be closed (with no boundary)?
<center>
Function or Class                     | Pure Triangle  | Self-Intersection Free | Closed
:------------------------------------ | :------------: | :--------------------: | :-------:
`fair()`                              |     yes        |        no              |   no
`refine()`                            |     yes        |        no              |   no
`triangulate_faces()`                 |     no         |        no              |   no
`isotropic_remeshing()`               |     no         |        no              |   no
`split_long_edges()`                  |     no         |        no              |   no
`triangulate_hole()`                  |     no         |        no              |   no
`triangulate_and_refine_hole()`       |     no         |        no              |   no
`triangulate_refine_and_fair_hole()`  |     no         |        no              |   no
`triangulate_hole_polyline()`         |     no         |        no              |   no
`does_self_intersect()`               |     yes        |        no              |   no
`self_intersections()`                |     yes        |        no              |   no
`Side_of_triangle_mesh`               |     yes        |        yes             |   yes
`is_outward_oriented()`               |     no         |        no              |   yes
`reverse_face_orientations()`         |     no         |        no              |   no
`stitch_borders()`                    |     no         |        no              |   no
`polygon_soup_to_polygon_mesh()`      |     no         |        no              |   no
`orient_polygon_soup()`               |     no         |        no              |   no
`remove_isolated_vertices()`          |     no         |        no              |   no
`compute_face_normal()`               |     no         |        no              |   no
`compute_face_normals()`              |     no         |        no              |   no
`compute_vertex_normal()`             |     no         |        no              |   no
`compute_vertex_normals()`            |     no         |        no              |   no
`compute_normals()`                   |     no         |        no              |   no
`Polygon_mesh_slicer`                 |     yes        |        yes             |   no
`connected_component()`               |     no         |        no              |   no
`connected_components()`              |     no         |        no              |   no
`keep_largest_connected_components()` |     no         |        no              |   no
`keep_connected_components()`         |     no         |        no              |   no
`remove_connected_components()`       |     no         |        no              |   no
</center>
<!---
`remove_degenerate_faces()`           |     yes        |        no              |   no
--->
****************************************
\section PMPHistory Implementation History

A first version of this package was started by Ilker %O. Yaz and Sébastien Loriot.
Jane Tournois worked on the finalization of the API, code, and documentation.

*/
} /* namespace CGAL */
