File: triangulate_faces.h

package info (click to toggle)
cgal 6.1.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 144,952 kB
  • sloc: cpp: 811,597; ansic: 208,576; sh: 493; python: 411; makefile: 286; javascript: 174
file content (731 lines) | stat: -rw-r--r-- 29,359 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
// Copyright (c) 2010-2011  GeometryFactory Sarl (France).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
//
// $URL: https://github.com/CGAL/cgal/blob/v6.1.1/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/triangulate_faces.h $
// $Id: include/CGAL/Polygon_mesh_processing/triangulate_faces.h 08b27d3db14 $
// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial
//
//
// Author(s)     : Laurent Rineau

#ifndef CGAL_POLYGON_MESH_PROCESSING_TRIANGULATE_FACES_H
#define CGAL_POLYGON_MESH_PROCESSING_TRIANGULATE_FACES_H

#include <CGAL/license/Polygon_mesh_processing/meshing_hole_filling.h>

#include <CGAL/Polygon_mesh_processing/triangulate_hole.h>

#include <CGAL/array.h>
#include <CGAL/boost/graph/helpers.h>
#include <CGAL/boost/graph/Euler_operations.h>
#include <CGAL/boost/graph/named_params_helper.h>
#include <CGAL/Named_function_parameters.h>

#include <boost/range/value_type.hpp>

#include <algorithm>
#include <iterator>
#include <map>
#include <queue>
#include <utility>
#include <vector>

namespace CGAL {
namespace Polygon_mesh_processing {
namespace Triangulate_faces {

/** \ingroup PMP_meshing_grp
*   %Default new face visitor model of `PMPTriangulateFaceVisitor`.
*   All its functions have an empty body. This class can be used as a
*   base class if only some of the functions of the concept require to be
*   overridden.
*/
template<class PolygonMesh>
struct Default_visitor
  : public Hole_filling::Default_visitor
{
  typedef boost::graph_traits<PolygonMesh> GT;
  typedef typename GT::face_descriptor face_descriptor;

  void before_subface_creations(face_descriptor /*f_old*/) {}
  void after_subface_creations() {}
  void after_subface_created(face_descriptor /*f_new*/) {}
};

} // namespace Triangulate_faces

namespace internal {

template <typename PolygonMesh>
class Triangulate_polygon_mesh_modifier
{
  using vertex_descriptor = typename boost::graph_traits<PolygonMesh>::vertex_descriptor;
  using halfedge_descriptor = typename boost::graph_traits<PolygonMesh>::halfedge_descriptor;
  using face_descriptor = typename boost::graph_traits<PolygonMesh>::face_descriptor;

private:
  template <typename VPM,
            typename Visitor,
            typename NamedParameters>
  bool triangulate_face_with_hole_filling(face_descriptor f,
                                          PolygonMesh& pmesh,
                                          const VPM vpm,
                                          Visitor visitor,
                                          const NamedParameters& np)
  {
    namespace PMP = CGAL::Polygon_mesh_processing;

    using Point = typename boost::property_traits<VPM>::value_type;

    // gather halfedges around the face
    std::vector<Point> hole_points;
    std::vector<vertex_descriptor> border_vertices;
    CGAL_assertion(CGAL::halfedges_around_face(halfedge(f, pmesh), pmesh).size() > 0);
    for(halfedge_descriptor h : CGAL::halfedges_around_face(halfedge(f, pmesh), pmesh))
    {
      vertex_descriptor v = source(h, pmesh);
      hole_points.push_back(get(vpm, v));
      border_vertices.push_back(v);
    }

    // use hole filling
    typedef CGAL::Triple<int, int, int> Face_indices;
    std::vector<Face_indices> patch;
    PMP::triangulate_hole_polyline(hole_points, std::back_inserter(patch),
                                   np.use_2d_constrained_delaunay_triangulation(true));

    if(patch.empty())
      return false;

    // triangulate the hole
    std::map<std::pair<int, int>, halfedge_descriptor > halfedge_map;
    int i = 0;
    for(halfedge_descriptor h : CGAL::halfedges_around_face(halfedge(f, pmesh), pmesh))
    {
      int j = std::size_t(i+1) == hole_points.size() ? 0 : i+1;
      halfedge_map[std::make_pair(i, j)] = h;
      ++i;
    }

    visitor.before_subface_creations(f);

    bool first = true;
    std::vector<halfedge_descriptor> hedges;
    hedges.reserve(4);
    for(const Face_indices& triangle : patch)
    {
      if(first)
        first = false;
      else
      {
        f = add_face(pmesh);
        visitor.after_subface_created(f);
      }

      std::array<int, 4> indices = make_array(triangle.first,
                                              triangle.second,
                                              triangle.third,
                                              triangle.first);
      for (int i=0; i<3; ++i)
      {
        typename std::map< std::pair<int, int> , halfedge_descriptor >::iterator insert_res =
          halfedge_map.emplace(std::make_pair(indices[i], indices[i+1]),
                               boost::graph_traits<PolygonMesh>::null_halfedge()).first;
        if(insert_res->second == boost::graph_traits<PolygonMesh>::null_halfedge())
        {
          halfedge_descriptor nh = halfedge(add_edge(pmesh), pmesh);
          insert_res->second = nh;
          halfedge_map[std::make_pair(indices[i+1], indices[i])] = opposite(nh, pmesh);
        }
        hedges.push_back(insert_res->second);
      }

      hedges.push_back(hedges.front());
      for(int i=0; i<3;++i)
      {
        set_next(hedges[i], hedges[i+1], pmesh);
        set_face(hedges[i], f, pmesh);
        set_target(hedges[i], border_vertices[indices[i+1]], pmesh);
      }

      set_halfedge(f, hedges[0], pmesh);
      hedges.clear();
    }

    visitor.after_subface_creations();

    return true;
  }

public:
  template <typename NamedParameters>
  bool operator()(face_descriptor f,
                  PolygonMesh& pmesh,
                  const NamedParameters& np)
  {
    using Traits = typename GetGeomTraits<PolygonMesh, NamedParameters>::type;
    using VPM = typename GetVertexPointMap<PolygonMesh, NamedParameters>::type;

    using FT = typename Traits::FT;
    using Point_ref = typename boost::property_traits<VPM>::reference;

    using Visitor = typename internal_np::Lookup_named_param_def<
                                            internal_np::visitor_t,
                                            NamedParameters,
                                            Triangulate_faces::Default_visitor<PolygonMesh> // default
                                          >::type;

    using parameters::choose_parameter;
    using parameters::get_parameter;

    CGAL_precondition(is_valid_face_descriptor(f, pmesh));

    Traits traits = choose_parameter<Traits>(get_parameter(np, internal_np::geom_traits));
    VPM vpm = choose_parameter(get_parameter(np, internal_np::vertex_point),
                               get_property_map(vertex_point, pmesh));
    Visitor visitor = choose_parameter<Visitor>(get_parameter(np, internal_np::visitor),
                                                Triangulate_faces::Default_visitor<PolygonMesh>());

    typename Traits::Construct_cross_product_vector_3 cross_product =
      traits.construct_cross_product_vector_3_object();

    typename boost::graph_traits<PolygonMesh>::degree_size_type  original_size = degree(f, pmesh);
    if(original_size <= 3)
      return true;

    if(original_size == 4)
    {
      std::array<halfedge_descriptor,4> verts;
      verts[0] = halfedge(f, pmesh);
      verts[1] = next(verts[0], pmesh);
      verts[2] = next(verts[1], pmesh);
      verts[3] = next(verts[2], pmesh);
      Point_ref p0 = get(vpm, target(verts[0], pmesh));
      Point_ref p1 = get(vpm, target(verts[1], pmesh));
      Point_ref p2 = get(vpm, target(verts[2], pmesh));
      Point_ref p3 = get(vpm, target(verts[3], pmesh));

      /* Chooses the diagonal that will split the quad in two triangles that maximize
       * the scalar product of the un-normalized normals of the two triangles.
       * The lengths of the un-normalized normals (computed using cross-products of two vectors)
       *  are proportional to the area of the triangles.
       * Maximize the scalar product of the two normals will avoid skinny triangles,
       * and will also taken into account the cosine of the angle between the two normals.
       * In particular, if the two triangles are oriented in different directions,
       * the scalar product will be negative.
       */
      visitor.before_subface_creations(f);

      typename Traits::Vector_3 p0p1=p1-p0;
      typename Traits::Vector_3 p1p2=p2-p1;
      typename Traits::Vector_3 p2p3=p3-p2;
      typename Traits::Vector_3 p0p3=p3-p0;

      const FT delta1 = cross_product(p1p2, p2p3) * cross_product(-p0p3, p0p1);
      const FT delta2 = cross_product(p0p1, -p1p2) * cross_product(p2p3, p0p3);

      halfedge_descriptor res = boost::graph_traits<PolygonMesh>::null_halfedge();

      if (delta1!=delta2)
        res = (delta2>delta1)
            ?  CGAL::Euler::split_face(verts[0], verts[2], pmesh)
            :  CGAL::Euler::split_face(verts[1], verts[3], pmesh);
      else
      {
        halfedge_descriptor m =
          *(std::min_element)(verts.begin(), verts.end(),
                              [&pmesh,vpm](halfedge_descriptor v0, halfedge_descriptor v1)
                              {
                                return lexicographically_xyz_smaller(get(vpm, target(v0, pmesh)),
                                                                     get(vpm, target(v1, pmesh)));
                              });
        res = (m==verts[0] || m==verts[2])
            ? CGAL::Euler::split_face(verts[0], verts[2], pmesh)
            : CGAL::Euler::split_face(verts[1], verts[3], pmesh);
      }

      visitor.after_subface_created(face(res, pmesh));
      visitor.after_subface_created(face(opposite(res, pmesh), pmesh));

      visitor.after_subface_creations();

      return true;
    }

    return triangulate_face_with_hole_filling(f, pmesh, vpm, visitor, np);
  }
}; // class Triangulate_polygon_mesh_modifier

} // namespace internal

/**
* \ingroup PMP_meshing_grp
*
* triangulates a single face of a polygon mesh. This function depends on the package \ref PkgTriangulation2.
*
* @tparam PolygonMesh a model of `FaceListGraph` and `MutableFaceGraph`
* @tparam NamedParameters a sequence of \ref bgl_namedparameters "Named Parameters"
*
* @param f face to be triangulated
* @param pmesh the polygon mesh to which the face to be triangulated belongs
* @param np an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below
*
* \cgalNamedParamsBegin
*   \cgalParamNBegin{vertex_point_map}
*     \cgalParamDescription{a property map associating points to the vertices of `pmesh`}
*     \cgalParamType{a class model of `ReadWritePropertyMap` with `boost::graph_traits<PolygonMesh>::%vertex_descriptor`
*                    as key type and `%Point_3` as value type}
*     \cgalParamDefault{`boost::get(CGAL::vertex_point, pmesh)`}
*     \cgalParamExtra{If this parameter is omitted, an internal property map for `CGAL::vertex_point_t`
*                     must be available in `PolygonMesh`.}
*   \cgalParamNEnd
*
*   \cgalParamNBegin{geom_traits}
*     \cgalParamDescription{an instance of a geometric traits class}
*     \cgalParamType{a class model of `Kernel`}
*     \cgalParamDefault{a \cgal Kernel deduced from the point type, using `CGAL::Kernel_traits`}
*     \cgalParamExtra{The geometric traits class must be compatible with the vertex point type.}
*   \cgalParamNEnd
*
*   \cgalParamNBegin{visitor}
*     \cgalParamDescription{a visitor that enables to track how faces are triangulated into subfaces}
*     \cgalParamType{a class model of `PMPTriangulateFaceVisitor` and `PMPHolefillingVisitor`}
*     \cgalParamDefault{`Triangulate_faces::Default_visitor<PolygonMesh>`}
*     \cgalParamExtra{Note that the visitor will be copied, so
*                     it must not have any data member that does not have a reference-like type.}
*   \cgalParamNEnd
* \cgalNamedParamsEnd
*
* This function calls `CGAL::Polygon_mesh_processing::triangulate_hole_polyline()`.
* Refer to its documentation for its named parameters.
*
* @pre The face `f` is not degenerate.
*
* @return `true` if the face has been triangulated.
*
* @see `triangulate_faces()`
*/
template <typename PolygonMesh,
          typename NamedParameters = parameters::Default_named_parameters>
bool triangulate_face(typename boost::graph_traits<PolygonMesh>::face_descriptor f,
                      PolygonMesh& pmesh,
                      const NamedParameters& np = parameters::default_values())
{
  internal::Triangulate_polygon_mesh_modifier<PolygonMesh> modifier;
  return modifier(f, pmesh, np);
}

/**
* \ingroup PMP_meshing_grp
*
* triangulates given faces of a polygon mesh. This function depends on the package \ref PkgTriangulation2.
*
* @tparam FaceRange range of `boost::graph_traits<PolygonMesh>::%face_descriptor`, model of `Range`.
*         Its iterator type is `InputIterator`.
* @tparam PolygonMesh a model of `FaceListGraph` and `MutableFaceGraph`
* @tparam NamedParameters a sequence of \ref bgl_namedparameters "Named Parameters"
*
* @param face_range the range of faces to be triangulated
* @param pmesh the polygon mesh to be triangulated
* @param np an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below
*
* \cgalNamedParamsBegin
*   \cgalParamNBegin{vertex_point_map}
*     \cgalParamDescription{a property map associating points to the vertices of `pmesh`}
*     \cgalParamType{a class model of `ReadWritePropertyMap` with `boost::graph_traits<PolygonMesh>::%vertex_descriptor`
*                    as key type and `%Point_3` as value type}
*     \cgalParamDefault{`boost::get(CGAL::vertex_point, pmesh)`}
*     \cgalParamExtra{If this parameter is omitted, an internal property map for `CGAL::vertex_point_t`
*                     must be available in `PolygonMesh`.}
*   \cgalParamNEnd
*
*   \cgalParamNBegin{geom_traits}
*     \cgalParamDescription{an instance of a geometric traits class}
*     \cgalParamType{a class model of `Kernel`}
*     \cgalParamDefault{a \cgal Kernel deduced from the point type, using `CGAL::Kernel_traits`}
*     \cgalParamExtra{The geometric traits class must be compatible with the vertex point type.}
*   \cgalParamNEnd
*
*   \cgalParamNBegin{visitor}
*     \cgalParamDescription{a visitor that enables to track how faces are triangulated into subfaces}
*     \cgalParamType{a class model of `PMPTriangulateFaceVisitor` and `PMPHolefillingVisitor`}
*     \cgalParamDefault{`Triangulate_faces::Default_visitor<PolygonMesh>`}
*     \cgalParamExtra{Note that the visitor will be copied, so
*                     it must not have any data member that does not have a reference-like type.}
*   \cgalParamNEnd
* \cgalNamedParamsEnd
*
* This function calls `CGAL::Polygon_mesh_processing::triangulate_hole_polyline()` for each face.
* Refer to its documentation for its named parameters.
*
* @pre No face within `face_range` is degenerate.
*
* @return `true` if all the faces have been triangulated.
*
* @see `triangulate_face()`
* @see `triangulate_polygons()`
*/
template <typename FaceRange,
          typename PolygonMesh,
          typename NamedParameters = parameters::Default_named_parameters>
bool triangulate_faces(FaceRange face_range,
                       PolygonMesh& pmesh,
                       const NamedParameters& np = parameters::default_values())
{
  using face_descriptor = typename boost::graph_traits<PolygonMesh>::face_descriptor;

  bool result = true;

  // One needs to store the facets into a vector, because the list of
  // facets of the polyhedron will be modified during the loop, and
  // that invalidates the range [facets_begin(), facets_end()[.
  std::vector<face_descriptor> facets(std::begin(face_range), std::end(face_range));

  internal::Triangulate_polygon_mesh_modifier<PolygonMesh> modifier;
  for(face_descriptor f : facets)
  {
    if(!modifier(f, pmesh, np))
      result = false;
  }

  return result;
}

/**
* \ingroup PMP_meshing_grp
*
* triangulates all faces of a polygon mesh. This function depends on the package \ref PkgTriangulation2.
*
* @tparam PolygonMesh a model of `FaceListGraph` and `MutableFaceGraph`
* @tparam NamedParameters a sequence of \ref bgl_namedparameters "Named Parameters"
*
* @param pmesh the polygon mesh to be triangulated
* @param np an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below
*
* \cgalNamedParamsBegin
*   \cgalParamNBegin{vertex_point_map}
*     \cgalParamDescription{a property map associating points to the vertices of `pmesh`}
*     \cgalParamType{a class model of `ReadWritePropertyMap` with `boost::graph_traits<PolygonMesh>::%vertex_descriptor`
*                    as key type and `%Point_3` as value type}
*     \cgalParamDefault{`boost::get(CGAL::vertex_point, pmesh)`}
*     \cgalParamExtra{If this parameter is omitted, an internal property map for `CGAL::vertex_point_t`
*                     must be available in `PolygonMesh`.}
*   \cgalParamNEnd
*
*   \cgalParamNBegin{geom_traits}
*     \cgalParamDescription{an instance of a geometric traits class}
*     \cgalParamType{a class model of `Kernel`}
*     \cgalParamDefault{a \cgal Kernel deduced from the point type, using `CGAL::Kernel_traits`}
*     \cgalParamExtra{The geometric traits class must be compatible with the vertex point type.}
*   \cgalParamNEnd
*
*   \cgalParamNBegin{visitor}
*     \cgalParamDescription{a visitor that enables to track how faces are triangulated into subfaces}
*     \cgalParamType{a class model of `PMPTriangulateFaceVisitor` and `PMPHolefillingVisitor`}
*     \cgalParamDefault{`Triangulate_faces::Default_visitor<PolygonMesh>`}
*     \cgalParamExtra{Note that the visitor will be copied, so
*                     it must not have any data member that does not have a reference-like type.}
*   \cgalParamNEnd
* \cgalNamedParamsEnd
*
* This function calls `CGAL::Polygon_mesh_processing::triangulate_hole_polyline()` on all the faces of the polygon mesh.
* Refer to its documentation for its named parameters.
*
* @pre No face of `pmesh` is degenerate.
*
* @return `true` if all the faces have been triangulated.
*
* @see `triangulate_face()`
* @see `triangulate_polygons()`
*/
template <typename PolygonMesh, typename NamedParameters = parameters::Default_named_parameters>
bool triangulate_faces(PolygonMesh& pmesh,
                       const NamedParameters& np = parameters::default_values())
{
  return triangulate_faces(faces(pmesh), pmesh, np);
}

////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
// Polygon Soup

namespace Triangulate_polygons {

/** \ingroup PMP_meshing_grp
*   %Default new polygon visitor model of `PMPTriangulateFaceVisitor`.
*   All its functions have an empty body. This class can be used as a
*   base class if only some of the functions of the concept require to be
*   overridden.
*/
struct Default_visitor
  : public Hole_filling::Default_visitor
{
  template <typename Polygon>
  void before_subface_creations(const Polygon& /*f_old*/) {}

  template <typename Polygon>
  void after_subface_created(const Polygon& /*f_new*/) {}

  void after_subface_creations() {}
};

} // namespace Triangulate_polygons

namespace internal {

class Triangulate_polygon_soup_modifier
{
private:
  template<typename Polygon,
           typename PointRange,
           typename PolygonRange,
           typename PMap,
           typename Visitor,
           typename NamedParameters>
  bool triangulate_polygon_with_hole_filling(const Polygon& polygon,
                                             const PointRange& points,
                                             PolygonRange& triangulated_polygons, // output
                                             PMap pm,
                                             Visitor visitor,
                                             const NamedParameters& np)
  {
    namespace PMP = CGAL::Polygon_mesh_processing;

    using Point = typename boost::property_traits<PMap>::value_type;

    // gather halfedges around the face
    std::vector<Point> hole_points;
    std::vector<std::size_t> hole_points_indices;

    for(std::size_t i : polygon)
    {
      hole_points.push_back(get(pm, points[i]));
      hole_points_indices.push_back(i);
    }

    // use hole filling
    typedef CGAL::Triple<int, int, int> Face_indices;
    std::vector<Face_indices> patch;
    PMP::triangulate_hole_polyline(hole_points, std::back_inserter(patch), np);

    if(patch.empty())
      return false;

    visitor.before_subface_creations(polygon);

    for(const Face_indices& triangle : patch)
    {
      triangulated_polygons.push_back({hole_points_indices[triangle.first],
                                       hole_points_indices[triangle.second],
                                       hole_points_indices[triangle.third]});
      visitor.after_subface_created(triangulated_polygons.back());
    }

    visitor.after_subface_creations();
    return true;
  }

public:
  template <typename Polygon,
            typename PointRange,
            typename PolygonRange,
            typename NamedParameters>
  bool operator()(const Polygon& polygon,
                  const PointRange& points,
                  PolygonRange& triangulated_polygons,
                  const NamedParameters& np)
  {
    // PointMap
    using PMap = typename GetPointMap<PointRange, NamedParameters>::const_type;
    using Point_ref = typename boost::property_traits<PMap>::reference;

    // Kernel
    using Point = typename boost::property_traits<PMap>::value_type;
    using Def_Kernel = typename CGAL::Kernel_traits<Point>::Kernel;
    using Traits = typename internal_np::Lookup_named_param_def<
                              internal_np::geom_traits_t,
                              NamedParameters,
                              Def_Kernel>::type;
    using FT = typename Traits::FT;
    using PID = typename std::iterator_traits<typename Polygon::const_iterator>::value_type;

    // Visitor
    using Visitor = typename internal_np::Lookup_named_param_def<
                                            internal_np::visitor_t,
                                            NamedParameters,
                                            Triangulate_polygons::Default_visitor // default
                                          >::type;

    using parameters::choose_parameter;
    using parameters::get_parameter;

    PMap pm = choose_parameter<PMap>(get_parameter(np, internal_np::point_map));
    Traits traits = choose_parameter<Traits>(get_parameter(np, internal_np::geom_traits));
    Visitor visitor = choose_parameter<Visitor>(get_parameter(np, internal_np::visitor),
                                                Triangulate_polygons::Default_visitor());

    typename Traits::Construct_cross_product_vector_3 cross_product =
      traits.construct_cross_product_vector_3_object();

    const std::size_t original_size = polygon.size();
    if(original_size == 4)
    {
      Point_ref p0 = get(pm, points[polygon[0]]);
      Point_ref p1 = get(pm, points[polygon[1]]);
      Point_ref p2 = get(pm, points[polygon[2]]);
      Point_ref p3 = get(pm, points[polygon[3]]);

      /* Chooses the diagonal that will split the quad in two triangles that maximize
       * the scalar product of the un-normalized normals of the two triangles.
       * The lengths of the un-normalized normals (computed using cross-products of two vectors)
       *  are proportional to the area of the triangles.
       * Maximize the scalar product of the two normals will avoid skinny triangles,
       * and will also taken into account the cosine of the angle between the two normals.
       * In particular, if the two triangles are oriented in different directions,
       * the scalar product will be negative.
       */
      visitor.before_subface_creations(polygon);


      typename Traits::Vector_3 p0p1=p1-p0;
      typename Traits::Vector_3 p1p2=p2-p1;
      typename Traits::Vector_3 p2p3=p3-p2;
      typename Traits::Vector_3 p0p3=p3-p0;

      const FT delta1 = cross_product(p1p2, p2p3) * cross_product(-p0p3, p0p1);
      const FT delta2 = cross_product(p0p1, -p1p2) * cross_product(p2p3, p0p3);
      if (delta1!=delta2)
      {
        if(delta2 > delta1)
        {
          triangulated_polygons.push_back({polygon[0], polygon[1], polygon[2]});
          triangulated_polygons.push_back({polygon[0], polygon[2], polygon[3]});
        }
        else
        {
          triangulated_polygons.push_back({polygon[0], polygon[1], polygon[3]});
          triangulated_polygons.push_back({polygon[1], polygon[2], polygon[3]});
        }
      }
      else
      {
        PID mid =
          *(std::min_element)(polygon.begin(), polygon.end(),
                              [&points,pm](PID id1 , PID id2)
                              {
                                return lexicographically_xyz_smaller(get(pm, points[id1]),
                                                                     get(pm, points[id2]));
                              });
        if (mid==0|| mid==2)
        {
          triangulated_polygons.push_back({polygon[0], polygon[1], polygon[2]});
          triangulated_polygons.push_back({polygon[0], polygon[2], polygon[3]});
        }
        else
        {
          triangulated_polygons.push_back({polygon[0], polygon[1], polygon[3]});
          triangulated_polygons.push_back({polygon[1], polygon[2], polygon[3]});
        }
      }

      visitor.after_subface_created(triangulated_polygons[triangulated_polygons.size()-2]);
      visitor.after_subface_created(triangulated_polygons[triangulated_polygons.size()-1]);

      visitor.after_subface_creations();

      return true;
    }

    return triangulate_polygon_with_hole_filling(polygon, points, triangulated_polygons, pm, visitor, np);
  }
}; // class Triangulate_polygon_soup_modifier

} // namespace internal

/**
* \ingroup PMP_meshing_grp
*
* triangulates all polygons of a polygon soup. This function depends on the package \ref PkgTriangulation2.
*
* @tparam PointRange a model of `ConstRange`. The value type of its iterator is the point type.
* @tparam PolygonRange a model of the concepts `SequenceContainer` and `Swappable`,
*                      whose `value_type` is itself a model of the concept `SequenceContainer`
*                      whose `value_type` is `std::size_t`.
* @tparam NamedParameters a sequence of \ref bgl_namedparameters "Named Parameters"
*
* @param points the point geometry of the soup to be triangulated
* @param polygons the polygons to be triangulated
* @param np an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below
*
* \cgalNamedParamsBegin
*   \cgalParamNBegin{point_map}
*     \cgalParamDescription{a property map associating points to the elements of the point set `points`}
*     \cgalParamType{a model of `ReadablePropertyMap` whose key type is the value type
*                    of the iterator of `PointRange` and whose value type is `geom_traits::Point_3`}
*     \cgalParamDefault{`CGAL::Identity_property_map<geom_traits::Point_3>`}
*   \cgalParamNEnd
*
*   \cgalParamNBegin{geom_traits}
*     \cgalParamDescription{an instance of a geometric traits class}
*     \cgalParamType{a class model of `Kernel`}
*     \cgalParamDefault{a \cgal Kernel deduced from the point type, using `CGAL::Kernel_traits`}
*     \cgalParamExtra{The geometric traits class must be compatible with the vertex point type.}
*   \cgalParamNEnd
*
*   \cgalParamNBegin{visitor}
*     \cgalParamDescription{a visitor that enables to track how polygons are divided into triangles}
*     \cgalParamType{a class model of `PMPTriangulateFaceVisitor` and `PMPHolefillingVisitor`}
*     \cgalParamDefault{`Triangulate_polygons::Default_visitor`}
*     \cgalParamExtra{Note that the visitor will be copied, so
*                     it must not have any data member that does not have a reference-like type.}
*   \cgalParamNEnd
* \cgalNamedParamsEnd
*
* This function calls `CGAL::Polygon_mesh_processing::triangulate_hole_polyline()` for each polygon.
* Refer to its documentation for its named parameters.
*
* @pre No polygon within `polygons` is degenerate.
*
* @return `true` if all the polygons have been triangulated.
*
* @see `triangulate_faces()`
*/
template <typename PointRange,
          typename PolygonRange,
          typename NamedParameters = parameters::Default_named_parameters>
bool triangulate_polygons(const PointRange& points,
                          PolygonRange& polygons,
                          const NamedParameters& np = parameters::default_values())
{
  using Polygon = typename boost::range_value<PolygonRange>::type;

  PolygonRange triangulated_polygons;
  triangulated_polygons.reserve(polygons.size());

  bool success = true;

  internal::Triangulate_polygon_soup_modifier modifier;
  for(const Polygon& polygon : polygons)
  {
    if(polygon.size() <= 3)
    {
      triangulated_polygons.push_back(polygon);
      continue;
    }

    if(!modifier(polygon, points, triangulated_polygons, np))
      success = false;
  }

  std::swap(polygons, triangulated_polygons);

  return success;
}

} // namespace Polygon_mesh_processing
} // namespace CGAL

#endif // CGAL_POLYGON_MESH_PROCESSING_TRIANGULATE_FACES_H