diff --git a/AABB_tree/include/CGAL/AABB_traits_3.h b/AABB_tree/include/CGAL/AABB_traits_3.h index 2db15ada3a4c..30b59bc8919d 100644 --- a/AABB_tree/include/CGAL/AABB_traits_3.h +++ b/AABB_tree/include/CGAL/AABB_traits_3.h @@ -761,7 +761,7 @@ class AABB_traits_3 } /// Comparison functions - static bool less_x(const Primitive& pr1, const Primitive& pr2,const AABB_traits_3& traits) + static bool less_x(const Primitive& pr1, const Primitive& pr2,const AABB_traits_3& traits) { return GeomTraits().less_x_3_object()( internal::Primitive_helper::get_reference_point(pr1,traits), internal::Primitive_helper::get_reference_point(pr2,traits) ); diff --git a/AABB_tree/include/CGAL/AABB_tree.h b/AABB_tree/include/CGAL/AABB_tree.h index c9881698a9a6..c84132776756 100644 --- a/AABB_tree/include/CGAL/AABB_tree.h +++ b/AABB_tree/include/CGAL/AABB_tree.h @@ -691,11 +691,12 @@ namespace CGAL { return std::addressof(m_nodes[0]); } - private: + /// @private const Primitive& singleton_data() const { CGAL_assertion(size() == 1); return *m_primitives.begin(); } + private: // search KD-tree mutable std::unique_ptr m_p_search_tree; diff --git a/AABB_tree/include/CGAL/AABB_tree/internal/AABB_traversal_traits.h b/AABB_tree/include/CGAL/AABB_tree/internal/AABB_traversal_traits.h index f00bc1340090..c0c67a0a3956 100644 --- a/AABB_tree/include/CGAL/AABB_tree/internal/AABB_traversal_traits.h +++ b/AABB_tree/include/CGAL/AABB_tree/internal/AABB_traversal_traits.h @@ -184,12 +184,10 @@ class Listing_primitive_traits }; /** - * It is more efficient to apply the inverse transformation to the query and then use the original traits, - * but except if the constructions are exact, the result may differ from applying the original transformation to the tree. - * @class Listing_primitive_traits_with_transformation + * @class Listing_bbox_primitive_traits */ -template -class Listing_primitive_traits_with_transformation +template +class Listing_bbox_primitive_traits { typedef typename AABBTraits::FT FT; typedef typename AABBTraits::Point Point; @@ -201,20 +199,15 @@ class Listing_primitive_traits_with_transformation typedef ::CGAL::AABB_node Node; public: - Listing_primitive_traits_with_transformation(OutputIterator out_it, const AABBTraits& traits) - : m_out_it(out_it), m_traits(traits), m_transfo(CGAL::IDENTITY), m_has_rotation(false) - {} - - Listing_primitive_traits_with_transformation(OutputIterator out_it, const AABBTraits& traits, const AffTransformation& transfo) - : m_out_it(out_it), m_traits(traits), m_transfo(transfo), m_has_rotation(transfo.has_rotation()) - {} + Listing_bbox_primitive_traits(OutputIterator out_it, const AABBTraits& traits) + : m_out_it(out_it), m_traits(traits) {} constexpr bool go_further() const { return true; } void intersection(const Query& query, const Primitive& primitive) { - auto datum_transformed = internal::Primitive_helper::get_datum(primitive, m_traits).transform(m_transfo); - if( CGAL::do_intersect(query, datum_transformed) ) + if( m_traits.do_intersect_object()(query.bbox(), + internal::Primitive_helper::get_datum(primitive, m_traits).bbox()) ) { *m_out_it++ = primitive.id(); } @@ -222,29 +215,21 @@ class Listing_primitive_traits_with_transformation bool do_intersect(const Query& query, const Node& node) const { - return m_traits.do_intersect_object()(query, compute_transformed_bbox(m_transfo, node.bbox(), m_has_rotation)); - } - - const AffTransformation& transformation() const { return m_transfo; } - void set_transformation(const AffTransformation& transfo) - { - m_transfo = transfo; - m_has_rotation = m_transfo.has_rotation(); + return m_traits.do_intersect_object()(query.bbox(), node.bbox()); } private: OutputIterator m_out_it; const AABBTraits& m_traits; - AffTransformation m_transfo; - bool m_has_rotation; }; /** - * @class Listing_distinct_primitive_traits - * used by `all_pairs_of_intersecting_primitives()` to avoid reporting `(i, i)` and twice `(i, j)`. + * It is more efficient to apply the inverse transformation to the query and then use the original traits, + * but except if the constructions are exact, the result may differ from applying the original transformation to the tree. + * @class Listing_primitive_traits_with_transformation */ -template -class Listing_distinct_primitive_traits +template +class Listing_primitive_traits_with_transformation { typedef typename AABBTraits::FT FT; typedef typename AABBTraits::Point Point; @@ -256,30 +241,44 @@ class Listing_distinct_primitive_traits typedef ::CGAL::AABB_node Node; public: - Listing_distinct_primitive_traits(OutputIterator out_it, const AABBTraits& traits) - : m_out_it(out_it), m_traits(traits) {} + Listing_primitive_traits_with_transformation(OutputIterator out_it, const AABBTraits& traits) + : m_out_it(out_it), m_traits(traits), m_transfo(CGAL::IDENTITY), m_has_rotation(false) + {} + + Listing_primitive_traits_with_transformation(OutputIterator out_it, const AABBTraits& traits, const AffTransformation& transfo) + : m_out_it(out_it), m_traits(traits), m_transfo(transfo), m_has_rotation(transfo.has_rotation()) + {} constexpr bool go_further() const { return true; } - void intersection(const Primitive& query, const Primitive& primitive) + void intersection(const Query& query, const Primitive& primitive) { - if( query.id()::get_datum(query, m_traits), primitive) ) + auto datum_transformed = internal::Primitive_helper::get_datum(primitive, m_traits).transform(m_transfo); + if( CGAL::do_intersect(query, datum_transformed) ) { *m_out_it++ = primitive.id(); } } - bool do_intersect(const Primitive& query, const Node& node) const + bool do_intersect(const Query& query, const Node& node) const { - return m_traits.do_intersect_object()(internal::Primitive_helper::get_datum(query, m_traits), node.bbox()); + return m_traits.do_intersect_object()(query, compute_transformed_bbox(m_transfo, node.bbox(), m_has_rotation)); + } + + const AffTransformation& transformation() const { return m_transfo; } + void set_transformation(const AffTransformation& transfo) + { + m_transfo = transfo; + m_has_rotation = m_transfo.has_rotation(); } private: OutputIterator m_out_it; const AABBTraits& m_traits; + AffTransformation m_transfo; + bool m_has_rotation; }; - /** * @class First_primitive_traits */ diff --git a/AABB_tree/include/CGAL/AABB_tree/internal/AABB_two_trees_traversal.h b/AABB_tree/include/CGAL/AABB_tree/internal/AABB_two_trees_traversal.h index b024e15fa766..61244dcb0123 100644 --- a/AABB_tree/include/CGAL/AABB_tree/internal/AABB_two_trees_traversal.h +++ b/AABB_tree/include/CGAL/AABB_tree/internal/AABB_two_trees_traversal.h @@ -18,24 +18,30 @@ #include #include +#if CGAL_LINKED_WITH_TBB +#include +#endif + namespace CGAL { namespace internal { namespace AABB_tree { +struct Two_trees_traversal_parallel_cutoff +{ + static constexpr std::size_t value = 3000; +}; + template void two_trees_traversal(const ::CGAL::AABB_node& node_A, - const ::CGAL::AABB_node& node_B, - const std::size_t nb_primitives_A, - const std::size_t nb_primitives_B, - TwoTreeTraversalTraits& traversal_traits) + const ::CGAL::AABB_node& node_B, + const std::size_t nb_primitives_A, + const std::size_t nb_primitives_B, + TwoTreeTraversalTraits& traversal_traits) { -#if CGAL_LINKED_WITH_TBB - const std::size_t cutoff_parallel_call = 100000; -#endif auto recursive_call = [](const auto &node_A, const auto &node_B, const std::size_t nb_primitives_A, const std::size_t nb_primitives_B, auto &traversal_traits){ if(traversal_traits.prefer_A_for_next_step(node_A, node_B, nb_primitives_A, nb_primitives_B)) two_trees_traversal< in_order, ConcurrencyTag>(node_A, node_B, nb_primitives_A, nb_primitives_B, traversal_traits); @@ -84,7 +90,10 @@ void two_trees_traversal(const ::CGAL::AABB_node& node_A, #if CGAL_LINKED_WITH_TBB if constexpr(ConcurrencyTag::is_parallel) { - if(do_intersect_left && do_intersect_right && nb_primitives_A > cutoff_parallel_call && nb_primitives_B > cutoff_parallel_call) + if(do_intersect_left && + do_intersect_right && + nb_primitives_A > Two_trees_traversal_parallel_cutoff::value && + nb_primitives_B > Two_trees_traversal_parallel_cutoff::value) { oneapi::tbb::task_group tg; tg.run([&]{ @@ -117,11 +126,91 @@ template void two_trees_traversal(const Tree_A& tree_A, - const Tree_B& tree_B, - TwoTreeTraversalTraits &traits) + const Tree_B& tree_B, + TwoTreeTraversalTraits &traits) { CGAL_precondition(tree_A.size() != 0 && tree_B.size() != 0); - two_trees_traversal(*tree_A.root_node(), *tree_B.root_node(), tree_A.size(), tree_B.size(), traits); + if(tree_A.size() == 1){ + if(tree_B.size() == 1) + traits.intersection(tree_A.singleton_data(), tree_B.singleton_data()); + else + traits.intersection(tree_A.singleton_data(), *tree_B.root_node(), tree_B.size()); + } + else if(tree_B.size() == 1) + traits.intersection(*tree_A.root_node(), tree_A.size(), tree_B.singleton_data()); + else + two_trees_traversal(*tree_A.root_node(), *tree_B.root_node(), tree_A.size(), tree_B.size(), traits); +} + +// An optimization to traverse a tree with itself +template +void one_tree_traversal(const ::CGAL::AABB_node& node, + const std::size_t nb_primitives, + TwoTreeTraversalTraits& traversal_traits) +{ + switch(nb_primitives) + { + case 2: + { + traversal_traits.intersection(node.left_data(), node.right_data()); + break; + } + case 3: + { + traversal_traits.intersection(node.left_data(), node.right_child(), 2); + one_tree_traversal(node.right_child(), 2, traversal_traits); + break; + } + default: + { +#if CGAL_LINKED_WITH_TBB + if constexpr(ConcurrencyTag::is_parallel) + { + if(nb_primitives > Two_trees_traversal_parallel_cutoff::value) + { + oneapi::tbb::task_group tg; + if(traversal_traits.do_intersect(node.left_child(), node.right_child())){ + tg.run([&]{ + two_trees_traversal(node.left_child(), node.right_child(), nb_primitives/2, nb_primitives - nb_primitives/2, traversal_traits);} + ); + } + tg.run([&]{ + one_tree_traversal(node.left_child(), nb_primitives/2, traversal_traits);} + ); + one_tree_traversal(node.right_child(), nb_primitives - nb_primitives/2, traversal_traits); + tg.wait(); + } + else + { + if(traversal_traits.do_intersect(node.left_child(), node.right_child())) + two_trees_traversal(node.left_child(), node.right_child(), nb_primitives/2, nb_primitives - nb_primitives/2, traversal_traits); + one_tree_traversal(node.left_child(), nb_primitives/2, traversal_traits); + one_tree_traversal(node.right_child(), nb_primitives - nb_primitives/2, traversal_traits); + } + } + else +#endif + { + if(traversal_traits.do_intersect(node.left_child(), node.right_child())) + two_trees_traversal(node.left_child(), node.right_child(), nb_primitives/2, nb_primitives - nb_primitives/2, traversal_traits); + one_tree_traversal(node.left_child(), nb_primitives/2, traversal_traits); + one_tree_traversal(node.right_child(), nb_primitives - nb_primitives/2, traversal_traits); + } + }} // switch end +} + +template +void one_tree_traversal(const Tree& tree, + TwoTreeTraversalTraits &traits) +{ + // Nothing to do if the tree is a singleton + if(tree.size() < 2) + return; + one_tree_traversal(*tree.root_node(), tree.size(), traits); } namespace experimental{ @@ -138,9 +227,6 @@ void two_trees_partial_traversal(const ::CGAL::AABB_node& node_A, const std::size_t cutoff, TwoTreeTraversalTraits& traversal_traits) { -#if CGAL_LINKED_WITH_TBB - const std::size_t cutoff_parallel_call = 100000; -#endif auto recursive_call = [&](const auto &node_A, const auto &node_B, const std::size_t nb_primitives_A, const std::size_t nb_primitives_B, auto &traversal_traits){ if(traversal_traits.prefer_A_for_next_step(node_A, node_B, nb_primitives_A, nb_primitives_B)) two_trees_partial_traversal< in_order, ConcurrencyTag>(node_A, node_B, nb_primitives_A, nb_primitives_B, cutoff, traversal_traits); @@ -171,7 +257,10 @@ void two_trees_partial_traversal(const ::CGAL::AABB_node& node_A, #if CGAL_LINKED_WITH_TBB if constexpr(ConcurrencyTag::is_parallel) { - if(do_intersect_left && do_intersect_right && nb_primitives_A > cutoff_parallel_call && nb_primitives_B > cutoff_parallel_call) + if(do_intersect_left && + do_intersect_right && + nb_primitives_A > Two_trees_traversal_parallel_cutoff::value && + nb_primitives_B > Two_trees_traversal_parallel_cutoff::value) { oneapi::tbb::task_group tg; tg.run([&]{ diff --git a/AABB_tree/include/CGAL/AABB_tree/internal/AABB_two_trees_traversal_traits.h b/AABB_tree/include/CGAL/AABB_tree/internal/AABB_two_trees_traversal_traits.h index 9751387c39e3..cf7551a8b492 100644 --- a/AABB_tree/include/CGAL/AABB_tree/internal/AABB_two_trees_traversal_traits.h +++ b/AABB_tree/include/CGAL/AABB_tree/internal/AABB_two_trees_traversal_traits.h @@ -25,25 +25,24 @@ namespace CGAL { namespace internal { namespace AABB_tree { -template +template class Wrap_output_iterator { - Value first; - OutputIterator out; + Value1 first; + OutputIterator& out; public: - Wrap_output_iterator(Value first_, OutputIterator out_): first(first_), out(out_){} + Wrap_output_iterator(Value1 first_, OutputIterator& out_): first(first_), out(out_){} - Wrap_output_iterator& operator=(Value second){ + Wrap_output_iterator& operator=(Value2 second){ if constexpr(in_order) - out = std::make_pair(first, second); + *out++ = std::make_pair(first, second); else - out = std::make_pair(second, first); + *out++ = std::make_pair(second, first); return *this; } Wrap_output_iterator& operator*(){ return *this; } - Wrap_output_iterator& operator++(){ ++out; return *this; } - Wrap_output_iterator operator++(int){ auto tmp = *this; ++out; return tmp; } - Wrap_output_iterator& operator+(int d){ out += d; return *this; } + Wrap_output_iterator& operator++(){ return *this; } + Wrap_output_iterator& operator++(int){ return *this;} }; template @@ -55,7 +54,7 @@ class Two_trees_listing_intersecting_primitives_traits typedef ::CGAL::AABB_node Node2; public: - Two_trees_listing_intersecting_primitives_traits(const AABBTraits1& traits1, const AABBTraits2& traits2, OutputIterator out_) + Two_trees_listing_intersecting_primitives_traits(const AABBTraits1& traits1, const AABBTraits2& traits2, OutputIterator& out_) : m_traits1(traits1), m_traits2(traits2), out(out_) {} @@ -69,9 +68,17 @@ class Two_trees_listing_intersecting_primitives_traits return node_a.bbox().squared_diagonal_length() > node_b.bbox().squared_diagonal_length(); } + void intersection(const Primitive1& primitive1, const Primitive2& primitive2) + { + using Wrap_iterator = Wrap_output_iterator; + Wrap_iterator wrap_out(primitive1.id(), out); + Listing_primitive_traits traits(wrap_out, m_traits2); + traits.intersection(internal::Primitive_helper::get_datum(primitive1, m_traits1), primitive2); + } + void intersection(const Primitive1& primitive1, const Node2& node2, std::size_t nb_primitives_2) { - using Wrap_iterator = Wrap_output_iterator; + using Wrap_iterator = Wrap_output_iterator; Wrap_iterator wrap_out(primitive1.id(), out); Listing_primitive_traits traits(wrap_out, m_traits2); node2.traversal( internal::Primitive_helper::get_datum(primitive1, m_traits1), traits, nb_primitives_2); @@ -79,7 +86,7 @@ class Two_trees_listing_intersecting_primitives_traits void intersection(const Node1& node1, std::size_t nb_primitives_1, const Primitive2& primitive2) { - using Wrap_iterator= Wrap_output_iterator; + using Wrap_iterator= Wrap_output_iterator; Wrap_iterator wrap_out(primitive2.id(), out); Listing_primitive_traits traits(wrap_out, m_traits1); node1.traversal( internal::Primitive_helper::get_datum(primitive2, m_traits2), traits, nb_primitives_1); @@ -93,7 +100,7 @@ class Two_trees_listing_intersecting_primitives_traits private: const AABBTraits1& m_traits1; const AABBTraits2& m_traits2; - OutputIterator out; + OutputIterator& out; }; template @@ -106,7 +113,7 @@ class Two_trees_listing_intersecting_primitives_traits_with_transformation public: Two_trees_listing_intersecting_primitives_traits_with_transformation(const AABBTraits1& traits1, const AABBTraits2& traits2, - OutputIterator out_, + OutputIterator& out_, const AffTransformation &tr1, const AffTransformation &tr2) : m_traits1(traits1), m_traits2(traits2), out(out_), @@ -130,12 +137,21 @@ class Two_trees_listing_intersecting_primitives_traits_with_transformation return node_a.bbox().squared_diagonal_length() > node_b.bbox().squared_diagonal_length(); } + void intersection(const Primitive1& primitive1, const Primitive2& primitive2) + { + using Wrap_iterator = Wrap_output_iterator; + Wrap_iterator wrap_out(primitive1.id(), out); + Listing_primitive_traits_with_transformation traits(wrap_out, m_traits2, m_tr2); + auto datum1 = (internal::Primitive_helper::get_datum(primitive1, m_traits1).transform(m_tr1)); + traits.intersection( datum1, primitive2); + } + void intersection(const Primitive1& primitive1, const Node2& node2, std::size_t nb_primitives_2) { // Use inverse transformation is faster but less numerically stable. if constexpr(Use_inverse_transformation::value) { - using Wrap_iterator = Wrap_output_iterator; + using Wrap_iterator = Wrap_output_iterator; Wrap_iterator wrap_out(primitive1.id(), out); Listing_primitive_traits traits(wrap_out, m_traits2); auto datum = (internal::Primitive_helper::get_datum(primitive1, m_traits1).transform(m_tr1)).transform(m_tr2_inverse); @@ -143,7 +159,7 @@ class Two_trees_listing_intersecting_primitives_traits_with_transformation } else { - using Wrap_iterator = Wrap_output_iterator; + using Wrap_iterator = Wrap_output_iterator; Wrap_iterator wrap_out(primitive1.id(), out); Listing_primitive_traits_with_transformation traits(wrap_out, m_traits2, m_tr2); auto datum = (internal::Primitive_helper::get_datum(primitive1, m_traits1).transform(m_tr1)); @@ -156,7 +172,7 @@ class Two_trees_listing_intersecting_primitives_traits_with_transformation // Use inverse transformation is faster but less numerically stable. if constexpr(Use_inverse_transformation::value) { - using Wrap_iterator = Wrap_output_iterator; + using Wrap_iterator = Wrap_output_iterator; Wrap_iterator wrap_out(primitive2.id(), out); Listing_primitive_traits traits(wrap_out, m_traits1); auto datum = (internal::Primitive_helper::get_datum(primitive2, m_traits2).transform(m_tr2)).transform(m_tr1_inverse); @@ -164,7 +180,7 @@ class Two_trees_listing_intersecting_primitives_traits_with_transformation } else { - using Wrap_iterator = Wrap_output_iterator; + using Wrap_iterator = Wrap_output_iterator; Wrap_iterator wrap_out(primitive2.id(), out); Listing_primitive_traits_with_transformation traits(wrap_out, m_traits1, m_tr1); auto datum = (internal::Primitive_helper::get_datum(primitive2, m_traits2).transform(m_tr2)); @@ -183,7 +199,7 @@ class Two_trees_listing_intersecting_primitives_traits_with_transformation private: const AABBTraits1& m_traits1; const AABBTraits2& m_traits2; - OutputIterator out; + OutputIterator& out; const AffTransformation& m_tr1; const AffTransformation& m_tr2; AffTransformation m_tr1_inverse; @@ -191,15 +207,17 @@ class Two_trees_listing_intersecting_primitives_traits_with_transformation bool m_tr1_has_rotation, m_tr2_has_rotation; }; -template -class Listing_self_intersecting_primitives_traits +template +class Two_trees_listing_primitives_with_overlapping_bbox_traits { - typedef typename AABBTraits::Primitive Primitive; - typedef ::CGAL::AABB_node Node; + typedef typename AABBTraits1::Primitive Primitive1; + typedef typename AABBTraits2::Primitive Primitive2; + typedef ::CGAL::AABB_node Node1; + typedef ::CGAL::AABB_node Node2; public: - Listing_self_intersecting_primitives_traits(const AABBTraits& traits, OutputIterator out_) - : m_traits(traits), out(out_) + Two_trees_listing_primitives_with_overlapping_bbox_traits(const AABBTraits1& traits1, const AABBTraits2& traits2, OutputIterator out_) + : m_traits1(traits1), m_traits2(traits2), out(out_) {} bool go_further() const { @@ -212,29 +230,38 @@ class Listing_self_intersecting_primitives_traits return node_a.bbox().squared_diagonal_length() > node_b.bbox().squared_diagonal_length(); } - void intersection(const Primitive& primitive1, const Node& node2, std::size_t nb_primitives_2) + void intersection(const Primitive1& primitive1, const Primitive2& primitive2) { - using Wrap_iterator = Wrap_output_iterator; + using Wrap_iterator = Wrap_output_iterator; Wrap_iterator wrap_out(primitive1.id(), out); - Listing_distinct_primitive_traits traits(wrap_out, m_traits); - node2.traversal( primitive1, traits, nb_primitives_2); + Listing_bbox_primitive_traits traits(wrap_out, m_traits2); + traits.intersection(internal::Primitive_helper::get_datum(primitive1, m_traits1), primitive2); } - void intersection(const Node& node1, std::size_t nb_primitives_1, const Primitive& primitive2) + void intersection(const Primitive1& primitive1, const Node2& node2, std::size_t nb_primitives_2) { - using Wrap_iterator= Wrap_output_iterator; + using Wrap_iterator = Wrap_output_iterator; + Wrap_iterator wrap_out(primitive1.id(), out); + Listing_bbox_primitive_traits traits(wrap_out, m_traits2); + node2.traversal( internal::Primitive_helper::get_datum(primitive1, m_traits1), traits, nb_primitives_2); + } + + void intersection(const Node1& node1, std::size_t nb_primitives_1, const Primitive2& primitive2) + { + using Wrap_iterator= Wrap_output_iterator; Wrap_iterator wrap_out(primitive2.id(), out); - Listing_distinct_primitive_traits traits(wrap_out, m_traits); - node1.traversal( primitive2, traits, nb_primitives_1); + Listing_bbox_primitive_traits traits(wrap_out, m_traits1); + node1.traversal( internal::Primitive_helper::get_datum(primitive2, m_traits2), traits, nb_primitives_1); } - bool do_intersect(const Node& node1, const Node& node2) const + bool do_intersect(const Node1& node1, const Node2& node2) const { return do_overlap(node1.bbox(), node2.bbox()); } private: - const AABBTraits& m_traits; + const AABBTraits1& m_traits1; + const AABBTraits2& m_traits2; OutputIterator out; }; @@ -261,6 +288,14 @@ class Two_trees_do_intersect_traits return node_a.bbox().squared_diagonal_length() > node_b.bbox().squared_diagonal_length(); } + void intersection(const Primitive1& primitive1, const Primitive2& primitive2) + { + Do_intersect_traits traits(m_traits2); + traits.intersection(internal::Primitive_helper::get_datum(primitive1, m_traits1), primitive2); + if(traits.is_intersection_found()) + m_is_found = true; + } + void intersection(const Primitive1& primitive1, const Node2& node2, std::size_t nb_primitives_2) { Do_intersect_traits traits(m_traits2); @@ -322,6 +357,26 @@ class Two_trees_do_intersect_traits_with_transformation return node_a.bbox().squared_diagonal_length() > node_b.bbox().squared_diagonal_length(); } + void intersection(const Primitive1& primitive1, const Primitive2& primitive2) + { + if constexpr(Use_inverse_transformation::value) + { + Do_intersect_traits traits(m_traits2); + auto datum = (internal::Primitive_helper::get_datum(primitive1, m_traits1).transform(m_tr1)).transform(m_tr2_inverse); + traits.intersection(datum, primitive2); + if(traits.is_intersection_found()) + m_is_found = true; + } + else + { + Do_intersect_traits_with_transformation traits(m_traits2, m_tr2); + auto datum = (internal::Primitive_helper::get_datum(primitive1, m_traits1).transform(m_tr1)); + traits.intersection(datum, primitive2); + if(traits.is_intersection_found()) + m_is_found = true; + } + } + void intersection(const Primitive1& primitive1, const Node2& node2, std::size_t nb_primitives_2) { // It is more efficient to apply the inverse transformation to the query and then use the original traits, diff --git a/AABB_tree/include/CGAL/AABB_trees/intersection.h b/AABB_tree/include/CGAL/AABB_trees/intersection.h index b4e9592dc52f..e49a225e0e78 100644 --- a/AABB_tree/include/CGAL/AABB_trees/intersection.h +++ b/AABB_tree/include/CGAL/AABB_trees/intersection.h @@ -150,11 +150,11 @@ namespace AABB_trees { typename OutputIterator, typename NamedParameters1 = parameters::Default_named_parameters, typename NamedParameters2 = parameters::Default_named_parameters> - void all_pairs_of_intersecting_primitives(const AABBTree1 &tree1, - const AABBTree2 &tree2, - OutputIterator out, - const NamedParameters1& np1 = parameters::default_values(), - const NamedParameters2& np2 = parameters::default_values()) + OutputIterator all_pairs_of_intersecting_primitives(const AABBTree1 &tree1, + const AABBTree2 &tree2, + OutputIterator out, + const NamedParameters1& np1 = parameters::default_values(), + const NamedParameters2& np2 = parameters::default_values()) { using parameters::get_parameter; using parameters::choose_parameter; @@ -167,7 +167,7 @@ namespace AABB_trees { // Early exit if one of the trees is empty if(tree1.empty() || tree2.empty()) - return; + return out; if constexpr(is_default_parameter::value && is_default_parameter::value) @@ -190,6 +190,8 @@ namespace AABB_trees { traversal_traits(tree1.traits(), tree2.traits(), out, tr1, tr2); CGAL::internal::AABB_tree::two_trees_traversal(tree1, tree2, traversal_traits); } + + return out; } /// \ingroup PkgAABBTreeRef @@ -204,12 +206,89 @@ namespace AABB_trees { template< typename Concurrency_tag = Sequential_tag, typename AABBTree, typename OutputIterator> - void all_pairs_of_intersecting_primitives(const AABBTree &tree, - OutputIterator out) + OutputIterator all_pairs_of_intersecting_primitives(const AABBTree &tree, + OutputIterator out) + { + if(tree.size() <= 1) + return out; + CGAL::internal::AABB_tree::Two_trees_listing_intersecting_primitives_traits traversal_traits(tree.traits(), tree.traits(), out); + CGAL::internal::AABB_tree::one_tree_traversal(tree, traversal_traits); + return out; + } + +// not officially documented for now +#ifndef DOXYGEN_RUNNING + /// \ingroup PkgAABBTreeRef + /// + /// \brief computes all pairs of primitives with overlapping bbox from two AABB trees. + /// + /// Both trees are traversed and all pairs of primitives that intersect are collected. + /// Each output element is a pair `(id1, id2)` where: + /// - `id1` is the ID of a primitive from `tree1` + /// - `id2` is the ID of a primitive from `tree2` + /// + /// \tparam AABBTree1 Type of the first AABB tree. + /// \tparam AABBTree2 Type of the second AABB tree. + /// \tparam OutputIterator Output iterator storing std::pair. + /// \tparam NamedParameters1 a sequence of \ref bgl_namedparameters "Named Parameters" + /// \tparam NamedParameters2 a sequence of \ref bgl_namedparameters "Named Parameters" + /// + /// \cgalNamedParamsBegin + /// \cgalParamNBegin{concurrency_tag} + /// \cgalParamDescription{a tag indicating if the task should be done using one or several threads.} + /// \cgalParamType{Either `CGAL::Sequential_tag`, or `CGAL::Parallel_tag`, or `CGAL::Parallel_if_available_tag`} + /// \cgalParamDefault{`CGAL::Sequential_tag`} + /// \cgalParamExtra{`np1` only} + /// \cgalParamNEnd + /// \cgalNamedParamsEnd + /// + /// \see do_intersect() + template< typename AABBTree1, + typename AABBTree2, + typename OutputIterator, + typename NamedParameters1 = parameters::Default_named_parameters, + typename NamedParameters2 = parameters::Default_named_parameters> + void all_pairs_of_primitives_with_overlapping_bbox(const AABBTree1 &tree1, + const AABBTree2 &tree2, + OutputIterator out, + const NamedParameters1& /*np1*/ = parameters::default_values(), + const NamedParameters2& /*np2*/ = parameters::default_values()) + { + using Concurrency_tag = typename internal_np::Lookup_named_param_def < + internal_np::concurrency_tag_t, + NamedParameters1, + Sequential_tag + > ::type; + + // Early exit if one of the trees is empty + if(tree1.empty() || tree2.empty()) + return; + + CGAL::internal::AABB_tree::Two_trees_listing_primitives_with_overlapping_bbox_traits traversal_traits(tree1.traits(), tree2.traits(), out); + CGAL::internal::AABB_tree::two_trees_traversal(tree1, tree2, traversal_traits); + } + + /// \ingroup PkgAABBTreeRef + /// + /// \brief computes all pairs of primitives from a single AABB tree that are intersecting. + /// + /// \note Two primitives do intersect if their datum do intersect according to the traits of the tree. Thus, with all documented traits in CGAL, two triangles sharing + /// a vertex are considered to intersect, and similarly for other primitives types and types of intersection. + /// + /// Intersections of a primitive with itself are not reported, and each intersecting + /// pair of distinct primitives is reported only once. + template< typename Concurrency_tag = Sequential_tag, // TODO: shouldn't it be a named parameter? + typename AABBTree, + typename OutputIterator> + void all_pairs_of_primitives_with_overlapping_bbox(const AABBTree &tree, + OutputIterator out) { - CGAL::internal::AABB_tree::Listing_self_intersecting_primitives_traits traversal_traits(tree.traits(), out); - CGAL::internal::AABB_tree::two_trees_traversal(tree, tree, traversal_traits); + if(tree.size() <= 1) + return; + CGAL::internal::AABB_tree::Two_trees_listing_primitives_with_overlapping_bbox_traits traversal_traits(tree.traits(), tree.traits(), out); + CGAL::internal::AABB_tree::one_tree_traversal(tree, traversal_traits); } +#endif }} // end namespace CGAL::AABB_trees diff --git a/AABB_tree/test/AABB_tree/aabb_vs_box_intersection_d_test.cpp b/AABB_tree/test/AABB_tree/aabb_vs_box_intersection_d_test.cpp new file mode 100644 index 000000000000..614565641a41 --- /dev/null +++ b/AABB_tree/test/AABB_tree/aabb_vs_box_intersection_d_test.cpp @@ -0,0 +1,153 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +using Box = CGAL::Box_intersection_d::Box_with_info_d; +using BoxRange = std::vector; +using K = CGAL::Simple_cartesian; + +template +struct Iterator_to_bbox_property_map{ + typedef Iterator key_type; + typedef CGAL::Bbox_3 value_type; + typedef value_type reference; + typedef boost::readable_property_map_tag category; + typedef Iterator_to_bbox_property_map Self; + + inline friend reference + get(Self, key_type it) + { + return it->bbox(); + } +}; + +template +struct Point_in_bbox_3_iterator_property_map{ + typedef Iterator key_type; + typedef typename GeomTraits::Point_3 value_type; + typedef value_type reference; + typedef boost::readable_property_map_tag category; + typedef Point_in_bbox_3_iterator_property_map Self; + + inline friend reference + get(Self, key_type it) + { + return typename GeomTraits::Point_3( it->bbox().xmin(), it->bbox().ymin(), it->bbox().zmin() ); + } +}; + +template < class GeomTraits, class Iterator> +struct AABB_box_primitive_3 : public CGAL::AABB_primitive< Iterator, + Iterator_to_bbox_property_map, + Point_in_bbox_3_iterator_property_map, + CGAL::Tag_false, CGAL::Tag_false > +{ + typedef CGAL::AABB_primitive< Iterator, + Iterator_to_bbox_property_map, + Point_in_bbox_3_iterator_property_map, + CGAL::Tag_false, CGAL::Tag_false > Base; + AABB_box_primitive_3(Iterator it) : Base(it){} +}; +using Primitive = AABB_box_primitive_3; +using AABB_traits = CGAL::AABB_traits_3; +using Tree = CGAL::AABB_tree; + +void test(BoxRange& r1, BoxRange& r2) +{ + int aabb_count = 0, + box_intersection_count = 0; + + Tree tree1(r1.begin(), r1.end()); + Tree tree2(r2.begin(), r2.end()); + + CGAL::AABB_trees::all_pairs_of_intersecting_primitives(tree1, tree2, boost::make_function_output_iterator( [&](auto&&) { ++aabb_count; }) ); + CGAL::box_intersection_d(r1.begin(), r1.end(), r2.begin(), r2.end(), [&](auto&, auto&){ ++box_intersection_count; }); + + assert(aabb_count == box_intersection_count); +} + +void random_test(std::size_t n = 1000) +{ + CGAL::Random r; + + BoxRange boxes1, boxes2; + boxes1.reserve(n); + boxes2.reserve(n); + + auto generate_boxes = [&](BoxRange& boxes) + { + for(std::size_t i = 0; i < n; ++i){ + const double x1 = r.get_double(0,10), + y1 = r.get_double(0,10), + z1 = r.get_double(0,10); + const double x2 = r.get_double(0,10), + y2 = r.get_double(0,10), + z2 = r.get_double(0,10); + boxes.emplace_back(CGAL::Bbox_3((std::min)(x1,x2), (std::min)(y1,y2), (std::min)(z1,z2), + (std::max)(x1,x2), (std::max)(y1,y2), (std::max)(z1,z2)), i); + } + }; + auto generate_unit_boxes = [&](BoxRange& boxes) + { + for(std::size_t i = 0; i < n; ++i){ + const double x = r.get_double(0,9), + y = r.get_double(0,9), + z = r.get_double(0,9); + boxes.emplace_back(CGAL::Bbox_3(x, y, z, x+1, y+1, z+1), i); + } + }; + generate_boxes(boxes1); + generate_boxes(boxes2); + test(boxes1, boxes2); + boxes1.clear(); boxes2.clear(); + generate_unit_boxes(boxes1); + generate_unit_boxes(boxes2); + test(boxes1, boxes2); +} + +template +void test_from_data(Path filename1, Path filename2) +{ + using Mesh = CGAL::Surface_mesh; + + Mesh mesh1, mesh2; + if(!CGAL::IO::read_polygon_mesh(filename1, mesh1) || !CGAL::IO::read_polygon_mesh(filename2, mesh2)){ + std::cout << "Files not found." << std::endl; + return; + } + + auto make_boxes = [](const Mesh& mesh){ + BoxRange boxes; + std::size_t i = 0; + for(auto f: mesh.faces()) + boxes.emplace_back(CGAL::Polygon_mesh_processing::face_bbox(f, mesh), i++); + return boxes; + }; + + BoxRange boxes1 = make_boxes(mesh1); + BoxRange boxes2 = make_boxes(mesh2); + test(boxes1, boxes2); +} + +int main() +{ + test_from_data(CGAL::data_file_path("meshes/diplodocus.off"), CGAL::data_file_path("meshes/bunny00.off")); + test_from_data(CGAL::data_file_path("meshes/bear.off"), CGAL::data_file_path("meshes/man.off")); + test_from_data(CGAL::data_file_path("meshes/sphere.off"), CGAL::data_file_path("meshes/elephant.off")); + test_from_data(CGAL::data_file_path("meshes/cow.off"), CGAL::data_file_path("meshes/cross.off")); + random_test(); + return 0; +} diff --git a/Alpha_wrap_3/package_info/Alpha_wrap_3/dependencies b/Alpha_wrap_3/package_info/Alpha_wrap_3/dependencies index d220894d4fd4..e44bd7a703d1 100644 --- a/Alpha_wrap_3/package_info/Alpha_wrap_3/dependencies +++ b/Alpha_wrap_3/package_info/Alpha_wrap_3/dependencies @@ -3,7 +3,6 @@ Algebraic_foundations Alpha_wrap_3 Arithmetic_kernel BGL -Box_intersection_d CGAL_Core Cartesian_kernel Circulator diff --git a/Cartesian_kernel/include/CGAL/Cartesian/function_objects.h b/Cartesian_kernel/include/CGAL/Cartesian/function_objects.h index d541b2754625..14f795d2e837 100644 --- a/Cartesian_kernel/include/CGAL/Cartesian/function_objects.h +++ b/Cartesian_kernel/include/CGAL/Cartesian/function_objects.h @@ -1887,6 +1887,12 @@ namespace CartesianKernelFunctors { typedef typename K::Circle_2 Circle_2; public: + const Bbox_2& + operator()(const Bbox_2& b) const + { + return b; + } + Bbox_2 operator()(const Point_2& p) const { @@ -1959,6 +1965,12 @@ namespace CartesianKernelFunctors { typedef typename K::Circle_3 Circle_3; public: + const Bbox_3& + operator()(const Bbox_3& b) const + { + return b; + } + Bbox_3 operator()(const Point_3& p) const { diff --git a/Constrained_triangulation_3/package_info/Constrained_triangulation_3/dependencies b/Constrained_triangulation_3/package_info/Constrained_triangulation_3/dependencies index 854e686ee58b..8bfb0c669839 100644 --- a/Constrained_triangulation_3/package_info/Constrained_triangulation_3/dependencies +++ b/Constrained_triangulation_3/package_info/Constrained_triangulation_3/dependencies @@ -1,8 +1,8 @@ +AABB_tree Algebraic_foundations Arithmetic_kernel BGL Basic_viewer -Box_intersection_d CGAL_Core Cartesian_kernel Circulator @@ -32,6 +32,7 @@ Random_numbers SMDS_3 STL_Extension Solver_interface +Spatial_searching Spatial_sorting Stream_support Surface_mesh diff --git a/Homogeneous_kernel/include/CGAL/Homogeneous/function_objects.h b/Homogeneous_kernel/include/CGAL/Homogeneous/function_objects.h index a0629653fc62..90683d416ec2 100644 --- a/Homogeneous_kernel/include/CGAL/Homogeneous/function_objects.h +++ b/Homogeneous_kernel/include/CGAL/Homogeneous/function_objects.h @@ -1889,6 +1889,12 @@ namespace HomogeneousKernelFunctors { typedef typename K::Circle_2 Circle_2; public: + const Bbox_2& + operator()(const Bbox_2& b) const + { + return b; + } + Bbox_2 operator()( const Point_2& p) const { @@ -1953,6 +1959,12 @@ namespace HomogeneousKernelFunctors { typedef typename K::Sphere_3 Sphere_3; public: + const Bbox_3& + operator()(const Bbox_3& b) const + { + return b; + } + Bbox_3 operator()(const Point_3& p) const { diff --git a/Installation/CHANGES.md b/Installation/CHANGES.md index 18a0144868ad..b386c5884396 100644 --- a/Installation/CHANGES.md +++ b/Installation/CHANGES.md @@ -60,6 +60,11 @@ Release date: December 2026 - **Breaking change** Removed the member function `vertices_in_conflict()` of the Delaunay and the regular triangulation which were deprecated since CGAL-3.8 - Removed the concept `WeightedPoint` +### [Polygon Mesh Processing](https://doc.cgal.org/6.3/Manual/packages.html#PkgPolygonMeshProcessing) +- `CGAL::Polygon_mesh_processing::do_intersect()` and `CGAL::Polygon_mesh_processing::self_intersections()` functions now have a named parameter `concurrency_tag`, + specifying whether the task should be performed using a single or multiple threads. +- The running times of the functions above have been improved. + ### [Polygon Mesh Processing - Mesh Repair](https://doc.cgal.org/6.3/Manual/packages.html#PkgPMPMeshRepair) - **Breaking change**: Removed the function `CGAL::Polygon_mesh_processing::smooth_mesh()` which was deprecated since CGAL-5.5. - **Breaking change**: Removed the overload of the functions `CGAL::Polygon_mesh_processing::triangulate_hole()`, `CGAL::Polygon_mesh_processing::triangulate_and_refine_hole()`, and `CGAL::Polygon_mesh_processing::triangulate_refine_and_fair_hole()` having output iterators for vertices and faces as parameter, which were deprecated since CGAL-6.0. @@ -74,6 +79,8 @@ Release date: December 2026 - The corefinement based operations (including Boolean operations) has been optimized to better handle cases when some identical faces are shared between the input meshes. This leads to a significant speed up in those cases. +- `corefine()` and its variants now have a named parameter `concurrency_tag`, specifying whether the task should be performed using a single or multiple threads. +- The running times of `corefine()`, `autorefine()` and their variants have been improved. - Added new multithreading compatible functions operating directly on triangle soups, enabling the handling of non-manifold input and output volumes: `CGAL::Polygon_mesh_processing::compute_union_of_triangle_soups()`, `CGAL::Polygon_mesh_processing::compute_intersection_of_triangle_soups()`, and `CGAL::Polygon_mesh_processing::compute_difference_of_triangle_soups()`. diff --git a/Installation/include/CGAL/Surface_mesh/Surface_mesh_fwd.h b/Installation/include/CGAL/Surface_mesh/Surface_mesh_fwd.h index 844abe803bf8..012de41f6d8d 100644 --- a/Installation/include/CGAL/Surface_mesh/Surface_mesh_fwd.h +++ b/Installation/include/CGAL/Surface_mesh/Surface_mesh_fwd.h @@ -13,13 +13,26 @@ /// \file Surface_mesh_fwd.h /// Forward declarations of the Surface_mesh package. +#include +#include + #ifndef DOXYGEN_RUNNING + namespace CGAL { +BOOST_MPL_HAS_XXX_TRAIT_DEF(Point) // fwdS for the public interface template class Surface_mesh; +template +struct Is_base_of_surface_mesh : std::false_type {}; + +template +struct Is_base_of_surface_mesh::value>>: std::is_base_of< CGAL::Surface_mesh, T> +{}; + + } // CGAL #endif diff --git a/Kernel_23/doc/Kernel_23/Concepts/FunctionObjectConcepts.h b/Kernel_23/doc/Kernel_23/Concepts/FunctionObjectConcepts.h index f53c9d00200e..8bce32d70e19 100644 --- a/Kernel_23/doc/Kernel_23/Concepts/FunctionObjectConcepts.h +++ b/Kernel_23/doc/Kernel_23/Concepts/FunctionObjectConcepts.h @@ -3811,6 +3811,12 @@ class ConstructBbox_2 { /// A model of this concept must provide: /// @{ + /*! + returns `b`. + */ + CGAL::Bbox_2 operator()(const Kernel::Bbox_2 + &b); + /*! returns a bounding box of `p`. */ @@ -3859,6 +3865,12 @@ class ConstructBbox_3 { /// A model of this concept must provide: /// @{ + /*! + returns `b`. + */ + CGAL::Bbox_3 operator()(const Kernel::Bbox_3 + &b); + /*! returns a bounding box of `c`. */ diff --git a/Kernel_23/include/CGAL/Bbox_2.h b/Kernel_23/include/CGAL/Bbox_2.h index 563d88d9e497..26a820cc89f9 100644 --- a/Kernel_23/include/CGAL/Bbox_2.h +++ b/Kernel_23/include/CGAL/Bbox_2.h @@ -71,6 +71,8 @@ class Bbox_2 inline Bbox_2 operator+(const Bbox_2 &b) const; inline Bbox_2& operator+=(const Bbox_2 &b); + inline const Bbox_2& bbox() const; + inline int largest_span_index() const; inline void dilate(int dist); @@ -152,6 +154,12 @@ Bbox_2::max BOOST_PREVENT_MACRO_SUBSTITUTION (int i) const return ymax(); } +inline +const Bbox_2& +Bbox_2::bbox() const{ + return *this; +} + inline Bbox_2 Bbox_2::operator+(const Bbox_2 &b) const diff --git a/Kernel_23/include/CGAL/Bbox_3.h b/Kernel_23/include/CGAL/Bbox_3.h index fea9ff8cfc9a..41d99b64661e 100644 --- a/Kernel_23/include/CGAL/Bbox_3.h +++ b/Kernel_23/include/CGAL/Bbox_3.h @@ -79,6 +79,8 @@ class Bbox_3 Bbox_3 operator+(const Bbox_3& b) const; Bbox_3& operator+=(const Bbox_3& b); + inline const Bbox_3& bbox() const; + inline void dilate(int dist); inline void scale(double factor); inline void pad(double offset); @@ -150,6 +152,12 @@ Bbox_3::operator!=(const Bbox_3 &b) const return ! (b == *this); } +inline +const Bbox_3& +Bbox_3::bbox() const{ + return *this; +} + inline int Bbox_3::dimension() const diff --git a/Lab/demo/Lab/Plugins/PMP/Surface_intersection_plugin.cpp b/Lab/demo/Lab/Plugins/PMP/Surface_intersection_plugin.cpp index c8a57ea630de..4521b84a4262 100644 --- a/Lab/demo/Lab/Plugins/PMP/Surface_intersection_plugin.cpp +++ b/Lab/demo/Lab/Plugins/PMP/Surface_intersection_plugin.cpp @@ -208,7 +208,7 @@ void CGAL_Lab_intersection_plugin::intersectionPolylines() } std::vector poly_intersections; - PMP::internal::compute_polylines_polylines_intersection(polyA, polyB,std::back_inserter(poly_intersections) , Kernel()); + PMP::intersections(polyA, polyB, std::back_inserter(poly_intersections)); for(const Poly_intersection& inter : poly_intersections) { @@ -309,11 +309,10 @@ void CGAL_Lab_intersection_plugin::intersectionSurfacePolyline() polylines.push_back(pol); } std::vector poly_intersections; - PMP::internal::compute_face_polylines_intersection(faces(*itemA->face_graph()), - polylines, - *itemA->face_graph(), - std::back_inserter(poly_intersections), - CGAL::parameters::default_values()); + PMP::intersections(*itemA->face_graph(), + polylines, + std::back_inserter(poly_intersections), + CGAL::parameters::default_values()); for(const Poly_intersection& inter : poly_intersections) { diff --git a/PMP_Boolean_operations/benchmark/CMakeLists.txt b/PMP_Boolean_operations/benchmark/CMakeLists.txt index 1cd65d7416b7..6397f3061152 100644 --- a/PMP_Boolean_operations/benchmark/CMakeLists.txt +++ b/PMP_Boolean_operations/benchmark/CMakeLists.txt @@ -6,6 +6,8 @@ project(PMP_Boolean_operations_Benchmarks) # CGAL and its components find_package(CGAL REQUIRED) +find_package(Eigen3 QUIET) +include(CGAL_Eigen3_support) create_single_source_cgal_program("rotated_cubes_autorefinement.cpp") create_single_source_cgal_program("coplanar_cubes_autorefinement.cpp") @@ -14,8 +16,20 @@ create_single_source_cgal_program("Performance/performance_snap_polygon_soup.cpp create_single_source_cgal_program("Robustness/robustness_snap_polygon_soup.cpp") create_single_source_cgal_program("Quality/quality_snap_polygon_soup.cpp") -create_single_source_cgal_program("polygon_mesh_slicer.cpp") -target_link_libraries(polygon_mesh_slicer PRIVATE CGAL::Eigen3_support) +create_single_source_cgal_program("Performance/performance_autorefine.cpp") +create_single_source_cgal_program("Robustness/robustness_autorefine.cpp") +create_single_source_cgal_program("Quality/quality_autorefine.cpp") + +create_single_source_cgal_program("Performance/performance_boolop.cpp") +create_single_source_cgal_program("Robustness/robustness_boolop.cpp") +create_single_source_cgal_program("Quality/quality_boolop.cpp") + +if(TARGET CGAL::Eigen3_support) + create_single_source_cgal_program("polygon_mesh_slicer.cpp") + target_link_libraries(polygon_mesh_slicer PRIVATE CGAL::Eigen3_support) +else() + message(STATUS "NOTICE: Eigen3 not found. polygon_mesh_slicer will not be built.") +endif() find_package(TBB QUIET) include(CGAL_TBB_support) diff --git a/PMP_Boolean_operations/benchmark/Performance/performance_autorefine.cpp b/PMP_Boolean_operations/benchmark/Performance/performance_autorefine.cpp new file mode 100644 index 000000000000..b7afe903e75a --- /dev/null +++ b/PMP_Boolean_operations/benchmark/Performance/performance_autorefine.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +#include +#include + +#include + +using Kernel = CGAL::Exact_predicates_inexact_constructions_kernel; +using Point_3 = Kernel::Point_3; +using Surface_mesh = CGAL::Surface_mesh; +namespace PMP = CGAL::Polygon_mesh_processing; + +int main(int argc, char** argv) +{ + if(argc < 2) + { + std::cerr << "Usage: " << argv[0] << " \n"; + return 1; + } + + Surface_mesh mesh; + if(!CGAL::IO::read_polygon_mesh(argv[1], mesh) || mesh.is_empty()) + { + std::cerr << "Cannot read " << argv[1] << "\n"; + return 1; + } + + if(!CGAL::is_triangle_mesh(mesh)) + PMP::triangulate_faces(mesh); + + PMP::autorefine(mesh, + CGAL::parameters::concurrency_tag(CGAL::Parallel_if_available_tag())); + + return 0; +} diff --git a/PMP_Boolean_operations/benchmark/Performance/performance_boolop.cpp b/PMP_Boolean_operations/benchmark/Performance/performance_boolop.cpp new file mode 100644 index 000000000000..27fff1fd75eb --- /dev/null +++ b/PMP_Boolean_operations/benchmark/Performance/performance_boolop.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +#include +#include + +#include + +using Kernel = CGAL::Exact_predicates_inexact_constructions_kernel; +using Point_3 = Kernel::Point_3; +using Vector_3 = Kernel::Vector_3; +using Mesh = CGAL::Surface_mesh; +namespace PMP = CGAL::Polygon_mesh_processing; + +int main(int argc, char** argv) +{ + if(argc < 2) + { + std::cerr << "Usage: " << argv[0] << " \n"; + return 1; + } + + Mesh tm1; + if(!CGAL::IO::read_polygon_mesh(argv[1], tm1) || tm1.is_empty()) + { + std::cerr << "Cannot read " << argv[1] << "\n"; + return 1; + } + + Mesh tm2 = tm1; + const CGAL::Bbox_3 bb = PMP::bbox(tm1); + const Vector_3 translation((bb.xmax()-bb.xmin()) * 0.2, + (bb.ymax()-bb.ymin()) * 0.2, + (bb.zmax()-bb.zmin()) * 0.2); + for(auto v : tm2.vertices()) + tm2.point(v) = tm2.point(v) + translation; + + Mesh out; + PMP::corefine_and_compute_union( + tm1, tm2, out, + CGAL::parameters::concurrency_tag(CGAL::Parallel_if_available_tag())); + return 0; +} diff --git a/PMP_Boolean_operations/benchmark/Performance/run_performance_autorefine.sh b/PMP_Boolean_operations/benchmark/Performance/run_performance_autorefine.sh new file mode 100755 index 000000000000..e073d571ad46 --- /dev/null +++ b/PMP_Boolean_operations/benchmark/Performance/run_performance_autorefine.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +set -e + +if [ "$#" -lt 2 ]; then + echo "Usage: $0 " + exit 1 +fi + +INPUT_FILE=$1 +TIMEOUT=$2 + +TMP_LOG=$(mktemp) +/usr/bin/time -f "TIME:%e\nMEM:%M" timeout "$TIMEOUT"s performance_autorefine "$INPUT_FILE" 2> "$TMP_LOG" + +SECONDS=$(grep "TIME" "$TMP_LOG" | cut -d':' -f2) +MEMORY=$(grep "MEM" "$TMP_LOG" | cut -d':' -f2) + +rm -f "$TMP_LOG" +echo "{\"seconds\": \"$SECONDS\", \"memory_peaks\": \"$MEMORY\"}" diff --git a/PMP_Boolean_operations/benchmark/Performance/run_performance_boolop.sh b/PMP_Boolean_operations/benchmark/Performance/run_performance_boolop.sh new file mode 100755 index 000000000000..6794fa944140 --- /dev/null +++ b/PMP_Boolean_operations/benchmark/Performance/run_performance_boolop.sh @@ -0,0 +1,14 @@ +#!/bin/bash +set -e +if [ "$#" -lt 2 ]; then + echo "Usage: $0 " + exit 1 +fi +INPUT_FILE=$1 +TIMEOUT=$2 +TMP_LOG=$(mktemp) +/usr/bin/time -f "TIME:%e\nMEM:%M" timeout "$TIMEOUT"s performance_boolop "$INPUT_FILE" 2> "$TMP_LOG" +SECONDS=$(grep "TIME" "$TMP_LOG" | cut -d':' -f2) +MEMORY=$(grep "MEM" "$TMP_LOG" | cut -d':' -f2) +rm -f "$TMP_LOG" +echo "{\"seconds\": \"$SECONDS\", \"memory_peaks\": \"$MEMORY\"}" diff --git a/PMP_Boolean_operations/benchmark/Performance/run_performance.sh b/PMP_Boolean_operations/benchmark/Performance/run_performance_snap.sh similarity index 54% rename from PMP_Boolean_operations/benchmark/Performance/run_performance.sh rename to PMP_Boolean_operations/benchmark/Performance/run_performance_snap.sh index aa6ea1a28ba0..417b7dc3741a 100755 --- a/PMP_Boolean_operations/benchmark/Performance/run_performance.sh +++ b/PMP_Boolean_operations/benchmark/Performance/run_performance_snap.sh @@ -13,16 +13,19 @@ GRID_SIZE=$3 ERASE_ALL_DUPLICATE=$4 # Use /usr/bin/time for memory usage (maximum resident set size in KB) -TMP_LOG=$(mktemp) +TMP_LOG_BOOLOP=$(mktemp) +TMP_LOG_AUTOREFINE=$(mktemp) +TMP_LOG_SNAP=$(mktemp) + # Run the benchmarked command -/usr/bin/time -f "TIME:%e\nMEM:%M" timeout "$TIMEOUT"s performance_snap_polygon_soup "$INPUT_FILE" "$GRID_SIZE" "$ERASE_ALL_DUPLICATE" 2> "$TMP_LOG" +/usr/bin/time -f "TIME:%e\nMEM:%M" timeout "$TIMEOUT"s performance_boolop "$INPUT_FILE" 2> "$TMP_LOG_BOOLOP" +/usr/bin/time -f "TIME:%e\nMEM:%M" timeout "$TIMEOUT"s performance_autorefine "$INPUT_FILE" 2> "$TMP_LOG_AUTOREFINE" +/usr/bin/time -f "TIME:%e\nMEM:%M" timeout "$TIMEOUT"s performance_snap_polygon_soup "$INPUT_FILE" "$GRID_SIZE" "$ERASE_ALL_DUPLICATE" 2> "$TMP_LOG_SNAP" # Parse time and memory -SECONDS=$(grep "TIME" "$TMP_LOG" | cut -d':' -f2) -MEMORY=$(grep "MEM" "$TMP_LOG" | cut -d':' -f2) - -rm -f "$TMP_LOG" +SECONDS=$(grep "TIME" "$TMP_LOG_BOOLOP" | cut -d':' -f2) +MEMORY=$(grep "MEM" "$TMP_LOG_BOOLOP" | cut -d':' -f2) # Output JSON echo "{\"seconds\": \"$SECONDS\", \"memory_peaks\": \"$MEMORY\"}" diff --git a/PMP_Boolean_operations/benchmark/Quality/quality_autorefine.cpp b/PMP_Boolean_operations/benchmark/Quality/quality_autorefine.cpp new file mode 100644 index 000000000000..cc567b93f943 --- /dev/null +++ b/PMP_Boolean_operations/benchmark/Quality/quality_autorefine.cpp @@ -0,0 +1,53 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +using Kernel = CGAL::Exact_predicates_inexact_constructions_kernel; +using Point_3 = Kernel::Point_3; +using Surface_mesh = CGAL::Surface_mesh; +namespace PMP = CGAL::Polygon_mesh_processing; + +int main(int argc, char** argv) +{ + if(argc < 2) + { + std::cerr << "Usage: " << argv[0] << " \n"; + return 1; + } + + Surface_mesh mesh; + if(!CGAL::IO::read_polygon_mesh(argv[1], mesh) || mesh.is_empty()) + { + std::cerr << "Cannot read " << argv[1] << "\n"; + return 1; + } + + if(!CGAL::is_triangle_mesh(mesh)) + PMP::triangulate_faces(mesh); + + PMP::autorefine(mesh, CGAL::parameters::concurrency_tag(CGAL::Parallel_if_available_tag())); + + const bool self_intersecting = + PMP::does_self_intersect(mesh); + + std::cout << "{\n" + << " \"Nb_output_vertices\": " << num_vertices(mesh) << ",\n" + << " \"Nb_output_edges\": " << num_edges(mesh) << ",\n" + << " \"Nb_output_faces\": " << num_faces(mesh) << ",\n" + << " \"Is_triangle_mesh\": \"" << (CGAL::is_triangle_mesh(mesh) ? "True" : "False") << "\",\n" + << " \"Is_valid\": \"" << (CGAL::is_valid_polygon_mesh(mesh) ? "True" : "False") << "\",\n" + << " \"Self_intersecting\": \"" << (self_intersecting ? "True" : "False") << "\",\n" + << " \"Closed\": \"" << (CGAL::is_closed(mesh) ? "True" : "False") << "\",\n" + << " \"Output_bound_a_volume\": \"" << (PMP::does_bound_a_volume(mesh) ? "True" : "False") << "\"\n" + << "}\n"; + + return 0; +} diff --git a/PMP_Boolean_operations/benchmark/Quality/quality_boolop.cpp b/PMP_Boolean_operations/benchmark/Quality/quality_boolop.cpp new file mode 100644 index 000000000000..7f35135886d4 --- /dev/null +++ b/PMP_Boolean_operations/benchmark/Quality/quality_boolop.cpp @@ -0,0 +1,59 @@ +#include +#include +#include +#include +#include + +#include +#include +#include + +using Kernel = CGAL::Exact_predicates_inexact_constructions_kernel; +using Point_3 = Kernel::Point_3; +using Vector_3 = Kernel::Vector_3; +using Mesh = CGAL::Surface_mesh; +namespace PMP = CGAL::Polygon_mesh_processing; + +int main(int argc, char** argv) +{ + if(argc < 2) + { + std::cerr << "Usage: " << argv[0] << " \n"; + return 1; + } + + Mesh tm1; + if(!CGAL::IO::read_polygon_mesh(argv[1], tm1) || tm1.is_empty()) + return 1; + + Mesh tm2 = tm1; + const CGAL::Bbox_3 bb = PMP::bbox(tm1); + const Vector_3 translation((bb.xmax()-bb.xmin()) * 0.2, + (bb.ymax()-bb.ymin()) * 0.2, + (bb.zmax()-bb.zmin()) * 0.2); + for(auto v : tm2.vertices()) + tm2.point(v) = tm2.point(v) + translation; + + Mesh outputs[4]; + std::array, 4> output = { + &outputs[0], &outputs[1], &outputs[2], &outputs[3] + }; + + const auto success = PMP::corefine_and_compute_boolean_operations( + tm1, tm2, output, + CGAL::parameters::concurrency_tag(CGAL::Parallel_if_available_tag())); + + std::cout << "{\n"; + const char* names[] = {"union", "intersection", "tm1_minus_tm2", "tm2_minus_tm1"}; + for(std::size_t i=0; i<4; ++i) + { + std::cout << " \"" << names[i] << "\": {\"success\": " + << (success[i] ? "true" : "false") + << ", \"vertices\": " << num_vertices(outputs[i]) + << ", \"faces\": " << num_faces(outputs[i]) << "}"; + if(i != 3) std::cout << ','; + std::cout << '\n'; + } + std::cout << "}\n"; + return 0; +} diff --git a/PMP_Boolean_operations/benchmark/Quality/run_quality_autorefine.sh b/PMP_Boolean_operations/benchmark/Quality/run_quality_autorefine.sh new file mode 100755 index 000000000000..bd6382863f59 --- /dev/null +++ b/PMP_Boolean_operations/benchmark/Quality/run_quality_autorefine.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +set -e + +if [ "$#" -lt 2 ]; then + echo "Usage: $0 " + exit 1 +fi + +INPUT_FILE=$1 +TIMEOUT=$2 + +TMP_LOG=$(mktemp) +timeout "$TIMEOUT"s quality_autorefine "$INPUT_FILE" > "$TMP_LOG" +cat "$TMP_LOG" +rm -f "$TMP_LOG" diff --git a/PMP_Boolean_operations/benchmark/Quality/run_quality_boolop.sh b/PMP_Boolean_operations/benchmark/Quality/run_quality_boolop.sh new file mode 100755 index 000000000000..163646e428bb --- /dev/null +++ b/PMP_Boolean_operations/benchmark/Quality/run_quality_boolop.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -e +if [ "$#" -lt 2 ]; then + echo "Usage: $0 " + exit 1 +fi +INPUT_FILE=$1 +TIMEOUT=$2 +TMP_LOG=$(mktemp) +timeout "$TIMEOUT"s quality_boolop "$INPUT_FILE" > "$TMP_LOG" +cat "$TMP_LOG" +rm -f "$TMP_LOG" diff --git a/PMP_Boolean_operations/benchmark/Quality/run_quality.sh b/PMP_Boolean_operations/benchmark/Quality/run_quality_snap.sh similarity index 100% rename from PMP_Boolean_operations/benchmark/Quality/run_quality.sh rename to PMP_Boolean_operations/benchmark/Quality/run_quality_snap.sh diff --git a/PMP_Boolean_operations/benchmark/Robustness/robustness_autorefine.cpp b/PMP_Boolean_operations/benchmark/Robustness/robustness_autorefine.cpp new file mode 100644 index 000000000000..8eca1dbb0a30 --- /dev/null +++ b/PMP_Boolean_operations/benchmark/Robustness/robustness_autorefine.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +#include +#include +#include + +#include + +using Kernel = CGAL::Exact_predicates_inexact_constructions_kernel; +using Point_3 = Kernel::Point_3; +using Surface_mesh = CGAL::Surface_mesh; +namespace PMP = CGAL::Polygon_mesh_processing; + +enum EXIT_CODES { VALID_OUTPUT=0, + INVALID_INPUT=1, + SELF_INTERSECTING_OUTPUT=3, + SIGSEGV=10, + SIGSABRT=11, + SIGFPE=12, + TIMEOUT=13 }; + +int main(int argc, char** argv) +{ + if(argc < 2) + return INVALID_INPUT; + + Surface_mesh mesh; + if(!CGAL::IO::read_polygon_mesh(argv[1], mesh) || mesh.is_empty()) + return INVALID_INPUT; + + if(!CGAL::is_triangle_mesh(mesh)) + PMP::triangulate_faces(mesh); + + PMP::autorefine(mesh, CGAL::parameters::concurrency_tag(CGAL::Parallel_if_available_tag())); + + if(PMP::does_self_intersect(mesh)) + return SELF_INTERSECTING_OUTPUT; + + return VALID_OUTPUT; +} diff --git a/PMP_Boolean_operations/benchmark/Robustness/robustness_boolop.cpp b/PMP_Boolean_operations/benchmark/Robustness/robustness_boolop.cpp new file mode 100644 index 000000000000..5d554da84a87 --- /dev/null +++ b/PMP_Boolean_operations/benchmark/Robustness/robustness_boolop.cpp @@ -0,0 +1,77 @@ +#include +#include +#include +#include +#include + +#include +#include +#include + +using Kernel = CGAL::Exact_predicates_inexact_constructions_kernel; +using Point_3 = Kernel::Point_3; +using Vector_3 = Kernel::Vector_3; +using Mesh = CGAL::Surface_mesh; +namespace PMP = CGAL::Polygon_mesh_processing; + +using Output_array = std::array, 4>; + +enum Output_type { OUTPLACE, INPLACE_TM1, INPLACE_TM2 }; + +bool run_case(const Mesh& input, const Vector_3& translation, + const std::size_t operation, const Output_type output_type) +{ + Mesh tm1 = input; + Mesh tm2 = input; + for(auto v : tm2.vertices()) + tm2.point(v) = tm2.point(v) + translation; + + Mesh out; + Output_array output = {std::nullopt, std::nullopt, std::nullopt, std::nullopt}; + + switch(output_type) + { + case OUTPLACE: output[operation] = &out; break; + case INPLACE_TM1: output[operation] = &tm1; break; + case INPLACE_TM2: output[operation] = &tm2; break; + } + + const auto success = PMP::corefine_and_compute_boolean_operations( + tm1, tm2, output, + CGAL::parameters::concurrency_tag(CGAL::Parallel_if_available_tag())); + + Mesh* result = output[operation].value(); + return success[operation] && result != nullptr && !result->is_empty(); +} + +int main(int argc, char** argv) +{ + if(argc < 2) + { + std::cerr << "Usage: " << argv[0] << " \n"; + return 1; + } + + Mesh input; + if(!CGAL::IO::read_polygon_mesh(argv[1], input) || input.is_empty()) + return 1; + + const CGAL::Bbox_3 bb = PMP::bbox(input); + const Vector_3 translation((bb.xmax()-bb.xmin()) * 0.2, + (bb.ymax()-bb.ymin()) * 0.2, + (bb.zmax()-bb.zmin()) * 0.2); + + const char* output_names[] = {"outplace", "inplace_tm1", "inplace_tm2"}; + for(std::size_t op=0; op<4; ++op) + { + for(int type=OUTPLACE; type<=INPLACE_TM2; ++type) + { + const bool ok = run_case(input, translation, op, static_cast(type)); + std::cout << "output_" << op << "." << output_names[type] + << ": " << (ok ? "OK" : "FAILED") << '\n'; + if(!ok) + return 1; + } + } + return 0; +} diff --git a/PMP_Boolean_operations/benchmark/Robustness/run_robustness_autorefine.sh b/PMP_Boolean_operations/benchmark/Robustness/run_robustness_autorefine.sh new file mode 100755 index 000000000000..92822c894a4e --- /dev/null +++ b/PMP_Boolean_operations/benchmark/Robustness/run_robustness_autorefine.sh @@ -0,0 +1,27 @@ +#!/bin/bash + +if [ "$#" -lt 2 ]; then + echo "Usage: $0 " + exit 1 +fi + +INPUT_FILE=$1 +TIMEOUT=$2 + +timeout --foreground "$TIMEOUT"s robustness_autorefine "$INPUT_FILE" +EXIT_CODE=$? + +declare -A TAGS +TAGS[0]="VALID_OUTPUT" +TAGS[1]="INPUT_IS_INVALID" +TAGS[3]="SELF_INTERSECTING_OUTPUT" +TAGS[139]="SIGSEGV" +TAGS[11]="SIGSEGV" +TAGS[6]="SIGABRT" +TAGS[8]="SIGFPE" +TAGS[132]="SIGILL" +TAGS[124]="TIMEOUT" + +TAG_NAME=${TAGS[$EXIT_CODE]:-UNKNOWN} +TAG_DESC=$([[ "$EXIT_CODE" -eq 0 ]] && echo "OK" || echo "Error") +echo "{\"TAG_NAME\": \"$TAG_NAME\", \"TAG\": \"$TAG_DESC\"}" diff --git a/PMP_Boolean_operations/benchmark/Robustness/run_robustness_boolop.sh b/PMP_Boolean_operations/benchmark/Robustness/run_robustness_boolop.sh new file mode 100755 index 000000000000..23a51c5a38c5 --- /dev/null +++ b/PMP_Boolean_operations/benchmark/Robustness/run_robustness_boolop.sh @@ -0,0 +1,10 @@ +#!/bin/bash +set -e +if [ "$#" -lt 2 ]; then + echo "Usage: $0 " + exit 1 +fi +INPUT_FILE=$1 +TIMEOUT=$2 +timeout --foreground "$TIMEOUT"s robustness_boolop "$INPUT_FILE" +echo '{"TAG_NAME": "VALID_OUTPUT", "TAG": "OK"}' diff --git a/PMP_Boolean_operations/benchmark/Robustness/run_robustness.sh b/PMP_Boolean_operations/benchmark/Robustness/run_robustness_snap.sh similarity index 100% rename from PMP_Boolean_operations/benchmark/Robustness/run_robustness.sh rename to PMP_Boolean_operations/benchmark/Robustness/run_robustness_snap.sh diff --git a/PMP_Boolean_operations/benchmark/benchmarking_snap_polygon_soup.sh b/PMP_Boolean_operations/benchmark/benchmarking_snap_polygon_soup.sh index da3f363566a4..5373a2bff176 100755 --- a/PMP_Boolean_operations/benchmark/benchmarking_snap_polygon_soup.sh +++ b/PMP_Boolean_operations/benchmark/benchmarking_snap_polygon_soup.sh @@ -22,13 +22,13 @@ process_file() { echo " \"$INPUT_ID\": {" echo " \"path\": \"$INPUT_PATH\"," - PERF_OUTPUT=$(bash "$PROJECT_DIR/Performance/run_performance.sh" "$INPUT_PATH" "$TIMEOUT" "$GRID_SIZE" "$ERASE_ALL_DUPLICATE" 2>> "$OUTPUT_DIR/Logs/$COMPONENT_NAME/Performance/$INPUT_ID.log") + PERF_OUTPUT=$(bash "$PROJECT_DIR/Performance/run_performance_snap.sh" "$INPUT_PATH" "$TIMEOUT" "$GRID_SIZE" "$ERASE_ALL_DUPLICATE" 2>> "$OUTPUT_DIR/Logs/$COMPONENT_NAME/Performance/$INPUT_ID.log") echo " \"Performance\": $PERF_OUTPUT," - QUALITY_OUTPUT=$(bash "$PROJECT_DIR/Quality/run_quality.sh" "$INPUT_PATH" "$TIMEOUT" "$GRID_SIZE" "$ERASE_ALL_DUPLICATE" 2>> "$OUTPUT_DIR/Logs/$COMPONENT_NAME/Quality/$INPUT_ID.log") + QUALITY_OUTPUT=$(bash "$PROJECT_DIR/Quality/run_quality_snap.sh" "$INPUT_PATH" "$TIMEOUT" "$GRID_SIZE" "$ERASE_ALL_DUPLICATE" 2>> "$OUTPUT_DIR/Logs/$COMPONENT_NAME/Quality/$INPUT_ID.log") echo " \"Quality\": $QUALITY_OUTPUT," - ROBUST_OUTPUT=$(bash "$PROJECT_DIR/Robustness/run_robustness.sh" "$INPUT_PATH" "$TIMEOUT" "$GRID_SIZE" "$ERASE_ALL_DUPLICATE" 2>> "$OUTPUT_DIR/Logs/$COMPONENT_NAME/Robustness/$INPUT_ID.log") + ROBUST_OUTPUT=$(bash "$PROJECT_DIR/Robustness/run_robustness_snap.sh" "$INPUT_PATH" "$TIMEOUT" "$GRID_SIZE" "$ERASE_ALL_DUPLICATE" 2>> "$OUTPUT_DIR/Logs/$COMPONENT_NAME/Robustness/$INPUT_ID.log") echo " \"Robustness\": $ROBUST_OUTPUT" echo " }" diff --git a/PMP_Boolean_operations/examples/PMP_Boolean_operations/CMakeLists.txt b/PMP_Boolean_operations/examples/PMP_Boolean_operations/CMakeLists.txt index 1f6e746c1f03..209d58424a31 100644 --- a/PMP_Boolean_operations/examples/PMP_Boolean_operations/CMakeLists.txt +++ b/PMP_Boolean_operations/examples/PMP_Boolean_operations/CMakeLists.txt @@ -52,6 +52,7 @@ if(TARGET CGAL::TBB_support) target_link_libraries(soup_autorefinement PRIVATE CGAL::TBB_support) target_link_libraries(soup_union PRIVATE CGAL::TBB_support) target_link_libraries(snap_polygon_soup PRIVATE CGAL::TBB_support) + target_link_libraries(corefinement_mesh_union_progress PRIVATE CGAL::TBB_support) create_single_source_cgal_program("corefinement_parallel_union_meshes.cpp") target_link_libraries(corefinement_parallel_union_meshes PRIVATE CGAL::TBB_support) diff --git a/PMP_Boolean_operations/examples/PMP_Boolean_operations/corefinement_mesh_union_progress.cpp b/PMP_Boolean_operations/examples/PMP_Boolean_operations/corefinement_mesh_union_progress.cpp index 52ff83c547fe..41f0cb10168a 100644 --- a/PMP_Boolean_operations/examples/PMP_Boolean_operations/corefinement_mesh_union_progress.cpp +++ b/PMP_Boolean_operations/examples/PMP_Boolean_operations/corefinement_mesh_union_progress.cpp @@ -3,6 +3,7 @@ #include #include +#include #include @@ -97,7 +98,7 @@ struct Visitor_rep{ std::size_t bound_intersection = 0; std::size_t tintersection = 0; std::size_t count_intersection = 0; - CGAL::Timer t; + CGAL::Real_timer t; }; @@ -196,12 +197,12 @@ int main(int argc, char* argv[]) return 1; } - CGAL::Timer t; + CGAL::Real_timer t; t.start(); Mesh out; Visitor visitor; - bool valid_union = PMP::corefine_and_compute_union (mesh1,mesh2, out, CGAL::parameters::visitor(visitor)); + bool valid_union = PMP::corefine_and_compute_union (mesh1,mesh2, out, CGAL::parameters::visitor(visitor).concurrency_tag(CGAL::Parallel_if_available_tag())); std::cout << "Global timer = " << t.time() << " sec." << std::endl; diff --git a/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/autorefinement.h b/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/autorefinement.h index 2dc4c283e1c1..72ee90f24fdf 100644 --- a/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/autorefinement.h +++ b/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/autorefinement.h @@ -28,6 +28,8 @@ #include #endif +#include + // output #include #include @@ -1836,7 +1838,7 @@ bool autorefine_triangle_soup(PointRange& soup_points, * * \cgalNamedParamsBegin * \cgalParamNBegin{concurrency_tag} - * \cgalParamDescription{a tag indicating if the task should be done using one or several threads.} + * \cgalParamDescription{a tag specifying whether the task should be performed using a single or multiple threads.} * \cgalParamType{Either `CGAL::Sequential_tag`, or `CGAL::Parallel_tag`, or `CGAL::Parallel_if_available_tag`} * \cgalParamDefault{`CGAL::Sequential_tag`} * \cgalParamNEnd diff --git a/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/clip.h b/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/clip.h index fedabcb09ecb..89aa237abe66 100644 --- a/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/clip.h +++ b/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/clip.h @@ -820,6 +820,13 @@ struct Visitor_wrapper_for_triangulate_face * * * \cgalNamedParamsBegin + * \cgalParamNBegin{concurrency_tag} + * \cgalParamDescription{a tag specifying whether the task should be performed using a single or multiple threads.} + * \cgalParamType{Either `CGAL::Sequential_tag`, or `CGAL::Parallel_tag`, or `CGAL::Parallel_if_available_tag`} + * \cgalParamDefault{`CGAL::Sequential_tag`} + * \cgalParamExtra{`np_tm` only} + * \cgalParamNEnd + * * \cgalParamNBegin{vertex_point_map} * \cgalParamDescription{a property map associating points to the vertices of `tm` (resp. `clipper`)} * \cgalParamType{a class model of `ReadWritePropertyMap` with `boost::graph_traits::%vertex_descriptor` @@ -938,7 +945,7 @@ clip(TriangleMesh& tm, * \cgalNamedParamsBegin * * \cgalParamNBegin{concurrency_tag} - * \cgalParamDescription{a tag indicating if the task should be performed using one or several threads.} + * \cgalParamDescription{a tag specifying whether the task should be performed using a single or multiple threads.} * \cgalParamType{Either `CGAL::Sequential_tag`, or `CGAL::Parallel_tag`, or `CGAL::Parallel_if_available_tag`} * \cgalParamDefault{`CGAL::Sequential_tag`} * \cgalParamNEnd @@ -1191,6 +1198,12 @@ bool clip(PolygonMesh& pm, * @param np an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below * * \cgalNamedParamsBegin + * \cgalParamNBegin{concurrency_tag} + * \cgalParamDescription{a tag specifying whether the task should be performed using a single or multiple threads.} + * \cgalParamType{Either `CGAL::Sequential_tag`, or `CGAL::Parallel_tag`, or `CGAL::Parallel_if_available_tag`} + * \cgalParamDefault{`CGAL::Sequential_tag`} + * \cgalParamNEnd + * * \cgalParamNBegin{vertex_point_map} * \cgalParamDescription{a property map associating points to the vertices of `tm`} * \cgalParamType{a class model of `ReadWritePropertyMap` with `boost::graph_traits::%vertex_descriptor` @@ -1303,6 +1316,13 @@ bool clip(TriangleMesh& tm, * @param np_s an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below * * \cgalNamedParamsBegin + * \cgalParamNBegin{concurrency_tag} + * \cgalParamDescription{a tag specifying whether the task should be performed using a single or multiple threads.} + * \cgalParamType{Either `CGAL::Sequential_tag`, or `CGAL::Parallel_tag`, or `CGAL::Parallel_if_available_tag`} + * \cgalParamDefault{`CGAL::Sequential_tag`} + * \cgalParamExtra{`np_tm` only} + * \cgalParamNEnd + * * \cgalParamNBegin{vertex_point_map} * \cgalParamDescription{a property map associating points to the vertices of `tm` (`splitter`)} * \cgalParamType{a class model of `ReadWritePropertyMap` with `boost::graph_traits::%vertex_descriptor` @@ -1354,6 +1374,12 @@ void split(TriangleMesh& tm, using parameters::get_parameter; using parameters::choose_parameter; + typedef typename internal_np::Lookup_named_param_def < + internal_np::concurrency_tag_t, + NamedParameters1, + Sequential_tag + > ::type Concurrency_tag; + typedef typename GetVertexPointMap::type VPM1; typedef typename GetVertexPointMap::type VPM2; @@ -1380,7 +1406,7 @@ void split(TriangleMesh& tm, const bool do_not_modify_splitter = choose_parameter(get_parameter(np_s, internal_np::do_not_modify), false); PMP::corefine(tm, splitter, - CGAL::parameters::vertex_point_map(vpm_tm).edge_is_marked_map(ecm).visitor(uv), + CGAL::parameters::vertex_point_map(vpm_tm).edge_is_marked_map(ecm).visitor(uv).concurrency_tag(Concurrency_tag()), CGAL::parameters::vertex_point_map(vpm_s).do_not_modify(do_not_modify_splitter)); //split mesh along marked edges @@ -1538,6 +1564,12 @@ void split(PolygonMesh& pm, * @param np an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below * * \cgalNamedParamsBegin + * \cgalParamNBegin{concurrency_tag} + * \cgalParamDescription{a tag specifying whether the task should be performed using a single or multiple threads.} + * \cgalParamType{Either `CGAL::Sequential_tag`, or `CGAL::Parallel_tag`, or `CGAL::Parallel_if_available_tag`} + * \cgalParamDefault{`CGAL::Sequential_tag`} + * \cgalParamNEnd + * * \cgalParamNBegin{vertex_point_map} * \cgalParamDescription{a property map associating points to the vertices of `tm`} * \cgalParamType{a class model of `ReadWritePropertyMap` with `boost::graph_traits::%vertex_descriptor` diff --git a/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/corefinement.h b/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/corefinement.h index 0d65c8aaac54..75b4d8f9dec3 100644 --- a/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/corefinement.h +++ b/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/corefinement.h @@ -180,6 +180,13 @@ enum Boolean_operation_type {UNION = 0, INTERSECTION=1, * @param np2 an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below * * \cgalNamedParamsBegin + * \cgalParamNBegin{concurrency_tag} + * \cgalParamDescription{a tag specifying whether the task should be performed using a single or multiple threads.} + * \cgalParamType{Either `CGAL::Sequential_tag`, or `CGAL::Parallel_tag`, or `CGAL::Parallel_if_available_tag`} + * \cgalParamDefault{`CGAL::Sequential_tag`} + * \cgalParamExtra{`np1` only} + * \cgalParamNEnd + * * \cgalParamNBegin{vertex_point_map} * \cgalParamDescription{a property map associating points to the vertices of `tm1` (`tm2`)} * \cgalParamType{a class model of `ReadablePropertyMap` with `boost::graph_traits::%vertex_descriptor` @@ -294,6 +301,12 @@ corefine_and_compute_boolean_operations( using parameters::choose_parameter; using parameters::get_parameter; + using ConcurrencyTag = typename internal_np::Lookup_named_param_def < + internal_np::concurrency_tag_t, + NPIn1, + Sequential_tag + > ::type; + const bool throw_on_self_intersection = choose_parameter(get_parameter(np1, internal_np::throw_on_self_intersection), false); @@ -477,7 +490,7 @@ corefine_and_compute_boolean_operations( ob.setup_for_clipping_a_surface(use_compact_clipper); } - Corefinement::Intersection_of_triangle_meshes + Corefinement::Intersection_of_triangle_meshes functor(tm1, tm2, vpm1, vpm2, Algo_visitor(uv,ob,em_in)); functor(CGAL::Emptyset_iterator(), throw_on_self_intersection, true); @@ -518,6 +531,13 @@ corefine_and_compute_boolean_operations( * @param np2 an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below * * \cgalNamedParamsBegin + * \cgalParamNBegin{concurrency_tag} + * \cgalParamDescription{a tag specifying whether the task should be performed using a single or multiple threads.} + * \cgalParamType{Either `CGAL::Sequential_tag`, or `CGAL::Parallel_tag`, or `CGAL::Parallel_if_available_tag`} + * \cgalParamDefault{`CGAL::Sequential_tag`} + * \cgalParamExtra{`np1` only} + * \cgalParamNEnd + * * \cgalParamNBegin{vertex_point_map} * \cgalParamDescription{a property map associating points to the vertices of `tm1` (`tm2`)} * \cgalParamType{a class model of `ReadablePropertyMap` with `boost::graph_traits::%vertex_descriptor` @@ -712,6 +732,13 @@ corefine_and_compute_difference( TriangleMesh& tm1, * @param np2 an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below * * \cgalNamedParamsBegin + * \cgalParamNBegin{concurrency_tag} + * \cgalParamDescription{a tag specifying whether the task should be performed using a single or multiple threads.} + * \cgalParamType{Either `CGAL::Sequential_tag`, or `CGAL::Parallel_tag`, or `CGAL::Parallel_if_available_tag`} + * \cgalParamDefault{`CGAL::Sequential_tag`} + * \cgalParamExtra{`np1` only} + * \cgalParamNEnd + * * \cgalParamNBegin{vertex_point_map} * \cgalParamDescription{a property map associating points to the vertices of `tm1` (`tm2`)} * \cgalParamType{a class model of `ReadablePropertyMap` with `boost::graph_traits::%vertex_descriptor` @@ -774,6 +801,12 @@ corefine( TriangleMesh& tm1, using parameters::choose_parameter; using parameters::get_parameter; + using ConcurrencyTag = typename internal_np::Lookup_named_param_def < + internal_np::concurrency_tag_t, + NamedParameters1, + Sequential_tag + > ::type; + TriangleMesh* const_mesh_ptr=nullptr; if (choose_parameter(get_parameter(np1, internal_np::do_not_modify), false)) { @@ -833,7 +866,7 @@ corefine( TriangleMesh& tm1, TriangleMesh, VPM1, VPM2, Ob, Edge_properties, User_visitor, false, handle_non_manifold_features> Algo_visitor; Ob ob; - Corefinement::Intersection_of_triangle_meshes + Corefinement::Intersection_of_triangle_meshes functor(tm1, tm2, vpm1, vpm2, Algo_visitor(uv,ob,em,const_mesh_ptr), const_mesh_ptr); // Fill non-manifold feature maps if provided @@ -859,6 +892,12 @@ namespace experimental { * @param np an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below * * \cgalNamedParamsBegin + * \cgalParamNBegin{concurrency_tag} + * \cgalParamDescription{a tag specifying whether the task should be performed using a single or multiple threads.} + * \cgalParamType{Either `CGAL::Sequential_tag`, or `CGAL::Parallel_tag`, or `CGAL::Parallel_if_available_tag`} + * \cgalParamDefault{`CGAL::Sequential_tag`} + * \cgalParamNEnd + * * \cgalParamNBegin{vertex_point_map} * \cgalParamDescription{a property map associating points to the vertices of `tm`} * \cgalParamType{a class model of `ReadablePropertyMap` with `boost::graph_traits::%vertex_descriptor` @@ -901,6 +940,12 @@ autorefine( TriangleMesh& tm, using parameters::choose_parameter; using parameters::get_parameter; + using ConcurrencyTag = typename internal_np::Lookup_named_param_def < + internal_np::concurrency_tag_t, + NamedParameters, + Sequential_tag + > ::type; + // Vertex point maps typedef typename GetVertexPointMap::type VPM; @@ -930,7 +975,7 @@ autorefine( TriangleMesh& tm, TriangleMesh, VPM, VPM, Ob, Edge_properties, User_visitor,true> Algo_visitor; Ob ob; - Corefinement::Intersection_of_triangle_meshes + Corefinement::Intersection_of_triangle_meshes functor(tm, vpm, Algo_visitor(uv,ob,em) ); functor(CGAL::Emptyset_iterator(), true); @@ -952,6 +997,11 @@ autorefine( TriangleMesh& tm, * @param np an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below * * \cgalNamedParamsBegin + * \cgalParamNBegin{concurrency_tag} + * \cgalParamDescription{a tag specifying whether the task should be performed using a single or multiple threads.} + * \cgalParamType{Either `CGAL::Sequential_tag`, or `CGAL::Parallel_tag`, or `CGAL::Parallel_if_available_tag`} + * \cgalParamDefault{`CGAL::Sequential_tag`} + * \cgalParamNEnd * \cgalParamNBegin{vertex_point_map} * \cgalParamDescription{a property map associating points to the vertices of `tm`} * \cgalParamType{a class model of `ReadablePropertyMap` with `boost::graph_traits::%vertex_descriptor` @@ -995,6 +1045,12 @@ autorefine_and_remove_self_intersections( TriangleMesh& tm, using parameters::choose_parameter; using parameters::get_parameter; + using ConcurrencyTag = typename internal_np::Lookup_named_param_def < + internal_np::concurrency_tag_t, + NamedParameters, + Sequential_tag + > ::type; + // Vertex point maps typedef typename GetVertexPointMap::type VPM; VPM vpm = choose_parameter(get_parameter(np, internal_np::vertex_point), @@ -1032,7 +1088,7 @@ autorefine_and_remove_self_intersections( TriangleMesh& tm, TriangleMesh, VPM, VPM, Ob, Edge_properties, User_visitor,true> Algo_visitor; Ob ob(tm, vpm, fid_map, em); - Corefinement::Intersection_of_triangle_meshes + Corefinement::Intersection_of_triangle_meshes functor(tm, vpm, Algo_visitor(uv,ob,em) ); functor(CGAL::Emptyset_iterator(), true); diff --git a/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/internal/Corefinement/Output_builder_for_autorefinement.h b/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/internal/Corefinement/Output_builder_for_autorefinement.h index 86e34e91d22f..d897d5dfe45c 100644 --- a/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/internal/Corefinement/Output_builder_for_autorefinement.h +++ b/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/internal/Corefinement/Output_builder_for_autorefinement.h @@ -1185,6 +1185,7 @@ class Output_builder_for_autorefinement Patches patches(tm, patch_ids, fids, intersection_edges, nb_patches); //remove the extra patch remove_patches(tm, ~patches_to_keep,patches, ecm, ecm); // WARNING there should be edge_mark_map but this file will disappear soon + CGAL_assertion(is_valid_polygon_mesh(tm)); stitch_borders(tm, hedge_pairs_to_stitch, parameters::vertex_point_map(vpm)); } diff --git a/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/internal/Corefinement/intersection_callbacks.h b/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/internal/Corefinement/intersection_callbacks.h index 6e0a2f38f9ce..1dd2de61188c 100644 --- a/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/internal/Corefinement/intersection_callbacks.h +++ b/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/internal/Corefinement/intersection_callbacks.h @@ -15,7 +15,6 @@ #include -#include #include #include #include @@ -29,44 +28,6 @@ namespace CGAL { namespace Polygon_mesh_processing { namespace Corefinement { -template -class Collect_face_bbox_per_edge_bbox { -protected: - const TriangleMesh& tm_faces; - const TriangleMesh& tm_edges; - EdgeToFaces& edge_to_faces; - - typedef boost::graph_traits Graph_traits; - typedef typename Graph_traits::face_descriptor face_descriptor; - typedef typename Graph_traits::halfedge_descriptor halfedge_descriptor; - - typedef CGAL::Box_intersection_d::ID_FROM_BOX_ADDRESS Box_policy; - typedef CGAL::Box_intersection_d::Box_with_info_d Box; - -public: - Collect_face_bbox_per_edge_bbox( - const TriangleMesh& tm_faces, - const TriangleMesh& tm_edges, - EdgeToFaces& edge_to_faces) - : tm_faces(tm_faces) - , tm_edges(tm_edges) - , edge_to_faces(edge_to_faces) - {} - - void operator()( const Box& face_box, const Box& edge_box) const - { - halfedge_descriptor fh = face_box.info(); - halfedge_descriptor eh = edge_box.info(); - - edge_to_faces[edge(eh,tm_edges)].insert(face(fh, tm_faces)); - } - - void operator()( const Box* face_box_ptr, const Box* edge_box_ptr) const - { - operator()(*face_box_ptr, *edge_box_ptr); - } -}; - template::reference Point; - typedef CGAL::Box_intersection_d::ID_FROM_BOX_ADDRESS Box_policy; - typedef CGAL::Box_intersection_d::Box_with_info_d Box; - public: Collect_face_bbox_per_edge_bbox_with_coplanar_handling( const TriangleMesh& tm_faces, @@ -109,9 +67,7 @@ class Collect_face_bbox_per_edge_bbox_with_coplanar_handling { , visitor(visitor) {} - void operator()( const Box& face_box, const Box& edge_box) const { - halfedge_descriptor fh = face_box.info(); - halfedge_descriptor eh = edge_box.info(); + void operator()(halfedge_descriptor fh, halfedge_descriptor eh) const { if(is_border(eh,tm_edges)) eh = opposite(eh, tm_edges); //check if the segment intersects the plane of the facet or if it is included in the plane @@ -120,8 +76,10 @@ class Collect_face_bbox_per_edge_bbox_with_coplanar_handling { Point c = get(vpmap_tmf, target(next(fh, tm_faces), tm_faces)); /// SHOULD_USE_TRAITS_TAG - const Orientation abcp = orientation(a,b,c, get(vpmap_tme, target(eh, tm_edges))); - const Orientation abcq = orientation(a,b,c, get(vpmap_tme, source(eh, tm_edges))); + using K = typename Kernel_traits>::Kernel; + auto orientation = K().orientation_3_object(); + const auto [abcp,abcq] = orientation(a,b,c, get(vpmap_tme, target(eh, tm_edges)), get(vpmap_tme, source(eh, tm_edges))); + if (abcp==abcq){ if (abcp!=COPLANAR){ return; //no intersection @@ -182,12 +140,6 @@ class Collect_face_bbox_per_edge_bbox_with_coplanar_handling { return false; } - - void operator()(const Box* face_box_ptr, const Box* edge_box_ptr) const - { - operator()(*face_box_ptr, *edge_box_ptr); - } - void progress(double d) { visitor.progress_filtering_intersections(d); @@ -211,9 +163,6 @@ class Collect_face_bbox_per_edge_bbox_with_coplanar_handling_one_mesh { typedef typename Graph_traits::halfedge_descriptor halfedge_descriptor; typedef typename Graph_traits::vertex_descriptor vertex_descriptor; - typedef CGAL::Box_intersection_d::ID_FROM_BOX_ADDRESS Box_policy; - typedef CGAL::Box_intersection_d::Box_with_info_d Box; - typedef typename boost::property_traits::reference Point; bool is_edge_target_incident_to_face(halfedge_descriptor hd, @@ -274,10 +223,7 @@ class Collect_face_bbox_per_edge_bbox_with_coplanar_handling_one_mesh { , coplanar_faces(coplanar_faces) {} - void operator()( const Box& face_box, const Box& edge_box) const { - halfedge_descriptor fh = face_box.info(); - halfedge_descriptor eh = edge_box.info(); - + void operator()(halfedge_descriptor fh, halfedge_descriptor eh) const { if ( face(eh, tm) == face(fh, tm) || face(opposite(eh,tm), tm) == face(fh, tm) ) return; //edge incident to the triangle @@ -356,7 +302,16 @@ class Collect_face_bbox_per_edge_bbox_with_coplanar_handling_one_mesh { edge_to_faces[edge(eh,tm)].insert(face(fh, tm)); } - void operator()(const Box* face_box_ptr, const Box* edge_box_ptr) const + template + void operator()(const Box& face_box, const Box& edge_box) const + { + halfedge_descriptor fh = face_box.info(); + halfedge_descriptor eh = edge_box.info(); + return operator()(fh, eh); + } + + template + void operator()(Box* const face_box_ptr, Box* const edge_box_ptr) const { operator()(*face_box_ptr, *edge_box_ptr); } @@ -368,7 +323,6 @@ class Callback_with_self_intersection_report { typedef typename Base::face_descriptor face_descriptor; typedef typename Base::halfedge_descriptor halfedge_descriptor; - typedef typename Base::Box Box; std::set* tmf_collected_faces_ptr; std::set* tme_collected_faces_ptr; public: @@ -380,24 +334,24 @@ class Callback_with_self_intersection_report tme_collected_faces_ptr(&tme_collected_faces) {} - void operator()( const Box* fb, const Box* eb) { - halfedge_descriptor h = eb->info(); - if (!is_border(h, this->tm_edges)) - tme_collected_faces_ptr->insert( face(h, this->tm_edges) ); - h = opposite(h, this->tm_edges); - if (!is_border(h, this->tm_edges)) - tme_collected_faces_ptr->insert( face(h, this->tm_edges) ); - tmf_collected_faces_ptr->insert( face(fb->info(), this->tm_faces) ); + void operator()(halfedge_descriptor fh, halfedge_descriptor eh) { + if (!is_border(eh, this->tm_edges)) + tme_collected_faces_ptr->insert( face(eh, this->tm_edges) ); + eh = opposite(eh, this->tm_edges); + if (!is_border(eh, this->tm_edges)) + tme_collected_faces_ptr->insert( face(eh, this->tm_edges) ); + tmf_collected_faces_ptr->insert( face(fh, this->tm_faces) ); // throw if one of the faces are degenerated - if (this->is_face_degenerated(fb->info()) || - this->are_edge_faces_degenerated(h)) + if (this->is_face_degenerated(fh) || + this->are_edge_faces_degenerated(eh)) { throw Self_intersection_exception(); } - Base::operator()(fb, eb); + Base::operator()(fh, eh); } + bool self_intersections_found() { return diff --git a/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/internal/Corefinement/intersection_impl.h b/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/internal/Corefinement/intersection_impl.h index 33a34af61141..26fa76805d0f 100644 --- a/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/internal/Corefinement/intersection_impl.h +++ b/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/internal/Corefinement/intersection_impl.h @@ -15,18 +15,22 @@ #include - #include -#include #include #include #include #include #include +#include #include #include +#include #include +#ifdef CGAL_LINKED_WITH_TBB +#include +#endif + #include #include #include @@ -51,8 +55,7 @@ struct Triple_intersection_exception : // The algorithm works as follow: // From each triangle mesh, we extract a set of segments from the edges and a // set of triangles from the faces. -// We use Box_intersection_d to filter intersection between the segments from -// one mesh with the triangles from the other one. +// We use AABB_trees to filter pairs of candidates intersecting faces and extract the intersection of between an edge and a face. // From this filtered set, for each pair (segment,triangle), we look at the // intersection type. If not empty, we can have three different cases // 1)the segment intersect the interior of the triangle: @@ -196,7 +199,8 @@ struct Node_id_set { template< class TriangleMesh, class VertexPointMap1, class VertexPointMap2, - class Node_visitor=Default_surface_intersection_visitor + class Node_visitor=Default_surface_intersection_visitor, + class ConcurrencyTag=Sequential_tag > class Intersection_of_triangle_meshes { @@ -206,9 +210,6 @@ class Intersection_of_triangle_meshes typedef typename graph_traits::halfedge_descriptor halfedge_descriptor; typedef typename graph_traits::vertex_descriptor vertex_descriptor; - typedef CGAL::Box_intersection_d::ID_FROM_BOX_ADDRESS Box_policy; - typedef CGAL::Box_intersection_d::Box_with_info_d Box; - typedef std::unordered_set Face_set; typedef std::unordered_map Edge_to_faces; @@ -244,164 +245,239 @@ class Intersection_of_triangle_meshes CGAL_assertion_code(bool doing_autorefinement;) // member functions - template - void filter_intersections(const TriangleMesh& tm_f, - const TriangleMesh& tm_e, - const VPMF& vpm_f, - const VPME& vpm_e, - const Non_manifold_feature_map& non_manifold_feature_map, + template + void filter_intersections(const TriangleMesh& tm1, + const TriangleMesh& tm2, + const VPM1& vpm1, + const VPM2& vpm2, + const Non_manifold_feature_map& non_manifold_feature_map_1, + const Non_manifold_feature_map& non_manifold_feature_map_2, bool throw_on_self_intersection, - std::set& tm_f_faces, - std::set& tm_e_faces, - Bbox_3 g_bb, - IFSM is_shared_map_f, - IESM is_shared_map_e, - bool run_check) + std::set& tm1_faces, + std::set& tm2_faces, + Bbox_3 bb, + ISFM1 is_shared_face_map_1, + ISFM2 is_shared_face_map_2, + ISEM1 is_shared_edge_map_1, + ISEM2 is_shared_edge_map_2) { - std::vector face_boxes, edge_boxes; - std::vector face_boxes_ptr, edge_boxes_ptr; + using Point = typename boost::property_traits::value_type; + using GT = typename CGAL::Kernel_traits::Kernel; + using AABB_tree_helper_1 = CGAL::Polygon_mesh_processing::internal::AABB_tree_graph_helper; + using AABB_tree_helper_2 = CGAL::Polygon_mesh_processing::internal::AABB_tree_graph_helper; + using Tree_1 = typename AABB_tree_helper_1::Tree; + using Tree_2 = typename AABB_tree_helper_2::Tree; + AABB_tree_helper_1 helper_1; + AABB_tree_helper_2 helper_2; + + std::vector tm1_faces_intersecting_bb; + std::vector tm2_faces_intersecting_bb; + tm1_faces_intersecting_bb.reserve((std::min)(faces(tm1).size(), faces(tm2).size())); + tm2_faces_intersecting_bb.reserve((std::min)(faces(tm1).size(), faces(tm2).size())); + + for(face_descriptor f: faces(tm1)) + if( !get(is_shared_face_map_1, f) && + do_overlap(face_bbox(f, tm1, parameters::vertex_point_map(vpm1)), bb)) + tm1_faces_intersecting_bb.push_back(f); + for(face_descriptor f: faces(tm2)) + if( !get(is_shared_face_map_2, f) && + do_overlap(face_bbox(f, tm2, parameters::vertex_point_map(vpm2)), bb)) + tm2_faces_intersecting_bb.push_back(f); + + // If one set is empty, no intersection + if(tm1_faces_intersecting_bb.empty() || tm2_faces_intersecting_bb.empty()) + return; - face_boxes.reserve(num_faces(tm_f)); - face_boxes_ptr.reserve(num_faces(tm_f)); - for(face_descriptor fd : faces(tm_f)) - { - if (get(is_shared_map_f,fd)) continue; - halfedge_descriptor h=halfedge(fd,tm_f); - Bbox_3 bb = get(vpm_f,source(h,tm_f)).bbox() + - get(vpm_f,target(h,tm_f)).bbox() + - get(vpm_f,target(next(h,tm_f),tm_f)).bbox(); - if (do_overlap(bb, g_bb)) - { - face_boxes.emplace_back(bb, h); - face_boxes_ptr.push_back( &face_boxes.back() ); + Tree_1 tree1; + Tree_2 tree2; + + auto process_candidates_without_non_manifold_map = [&](face_descriptor f_1, face_descriptor f_2, auto &callback12, auto &callback21){ + std::array hf1 = { halfedge(f_1, tm1), + next(halfedge(f_1, tm1), tm1), + next(next(halfedge(f_1, tm1), tm1), tm1) }; + + std::array hf2 = { halfedge(f_2, tm2), + next(halfedge(f_2, tm2), tm2), + next(next(halfedge(f_2, tm2), tm2), tm2) }; + + for(halfedge_descriptor h : hf2){ + if( (is_border_edge(h, tm2) || h < opposite(h, tm2)) && !get(is_shared_edge_map_2, edge(h, tm2)) ) + callback12(hf1[0], h); } - } + for(halfedge_descriptor h : hf1){ + if( (is_border_edge(h, tm1) || h < opposite(h, tm1)) && !get(is_shared_edge_map_1, edge(h, tm1)) ) + callback21(hf2[0], h); + } + }; + auto process_candidates_with_non_manifold_map = [&](face_descriptor f_1, face_descriptor f_2, auto &callback12, auto &callback21){ + std::array hf1 = { halfedge(f_1, tm1), + next(halfedge(f_1, tm1), tm1), + next(next(halfedge(f_1, tm1), tm1), tm1) }; + + std::array hf2 = { halfedge(f_2, tm2), + next(halfedge(f_2, tm2), tm2), + next(next(halfedge(f_2, tm2), tm2), tm2) }; + + for(halfedge_descriptor h : hf2){ + edge_descriptor ed = edge(h, tm2); + std::size_t eid = non_manifold_feature_map_2.non_manifold_edges.empty() + ? NM_NID + : get(non_manifold_feature_map_2.e_nm_id, ed); + if (eid!=NM_NID && non_manifold_feature_map_2.non_manifold_edges[eid].front()!=ed) continue; + + if( !get(is_shared_edge_map_2, ed) && (is_border_edge(h, tm2) || h < opposite(h, tm2))) + callback12(hf1[0], h); + } + for(halfedge_descriptor h : hf1){ + edge_descriptor ed = edge(h, tm1); + std::size_t eid = non_manifold_feature_map_1.non_manifold_edges.empty() + ? NM_NID + : get(non_manifold_feature_map_1.e_nm_id, ed); + if (eid!=NM_NID && non_manifold_feature_map_1.non_manifold_edges[eid].front()!=ed) continue; + + if( !get(is_shared_edge_map_1, ed) && (is_border_edge(h, tm1) || h < opposite(h, tm1))) + callback21(hf2[0], h); + } + }; - edge_boxes.reserve(num_edges(tm_e)); - edge_boxes_ptr.reserve(num_edges(tm_e)); - if (non_manifold_feature_map.non_manifold_edges.empty()) - // general manifold case - for(edge_descriptor ed : edges(tm_e)) + // Wrap the call of AABB intersections given two callback functions + auto AABB_call = [&](auto &callback12, auto &callback21){ +#ifdef CGAL_LINKED_WITH_TBB + if constexpr(ConcurrencyTag::is_parallel) { - if (get(is_shared_map_e,ed)) continue; - halfedge_descriptor h=halfedge(ed,tm_e); - Bbox_3 bb = get(vpm_e,source(h,tm_e)).bbox() + - get(vpm_e,target(h,tm_e)).bbox(); - - if (do_overlap(bb, g_bb)) - { - edge_boxes.emplace_back(bb,h); - edge_boxes_ptr.push_back( &edge_boxes.back() ); - } + oneapi::tbb::task_group tg; + tg.run([&]{ helper_1.template build(tm1_faces_intersecting_bb, tree1, tm1, vpm1); }); + helper_2.template build(tm2_faces_intersecting_bb, tree2, tm2, vpm2); + tg.wait(); + + tbb::concurrent_vector> inter; + CGAL::AABB_trees::all_pairs_of_primitives_with_overlapping_bbox(tree1, tree2, std::back_inserter(inter), parameters::concurrency_tag(ConcurrencyTag())); + + // Callback are not thread safe since Edge_to_faces is not. + // Edge_to_faces is an unordered_map> + // pass them would be a lot of concurrent write and unefficient, use local vectors then merged and check doublon is probably better + // Currently, in explored examples, this step is negligeable in runtime and thus not parallellized + if(non_manifold_feature_map_1.non_manifold_edges.empty() && non_manifold_feature_map_2.non_manifold_edges.empty()) + for(const auto& [f_1, f_2]: inter) + process_candidates_without_non_manifold_map(f_1, f_2, callback12, callback21); + else + for(const auto& [f_1, f_2]: inter) + process_candidates_with_non_manifold_map(f_1, f_2, callback12, callback21); } - else - // non-manifold case - for(edge_descriptor ed : edges(tm_e)) + else +#endif { - std::size_t eid=get(non_manifold_feature_map.e_nm_id, ed); - halfedge_descriptor h=halfedge(ed,tm_e); - // insert only one copy of a non-manifold edge - if (eid!=NM_NID) - { - if (non_manifold_feature_map.non_manifold_edges[eid].front()!=ed) - continue; - else - // make sure the halfedge used is consistent with stored one - h = halfedge(non_manifold_feature_map.non_manifold_edges[eid].front(), tm_e); - } - if (get(is_shared_map_e,edge(h,tm_e))) continue; - Bbox_3 bb = get(vpm_e,source(h,tm_e)).bbox() + - get(vpm_e,target(h,tm_e)).bbox(); + helper_1.template build(tm1_faces_intersecting_bb, tree1, tm1, vpm1); + helper_2.template build(tm2_faces_intersecting_bb, tree2, tm2, vpm2); - if (do_overlap(bb, g_bb)) - { - edge_boxes.emplace_back(bb,h); - edge_boxes_ptr.push_back( &edge_boxes.back() ); - } + std::vector> inter; + CGAL::AABB_trees::all_pairs_of_primitives_with_overlapping_bbox(tree1, tree2, std::back_inserter(inter)); + + if(non_manifold_feature_map_1.non_manifold_edges.empty() && non_manifold_feature_map_2.non_manifold_edges.empty()) + for(const auto& [f_1, f_2]: inter) + process_candidates_without_non_manifold_map(f_1, f_2, callback12, callback21); + else + for(const auto& [f_1, f_2]: inter) + process_candidates_with_non_manifold_map(f_1, f_2, callback12, callback21); } + }; + + Edge_to_faces& tm1_edge_to_tm2_faces = &tm1 < &tm2 + ? stm_edge_to_ltm_faces + : ltm_edge_to_stm_faces; + Edge_to_faces& tm2_edge_to_tm1_faces = &tm2 < &tm1 + ? stm_edge_to_ltm_faces + : ltm_edge_to_stm_faces; + // Select the desire callbacks + using Callback = Collect_face_bbox_per_edge_bbox_with_coplanar_handling< + TriangleMesh, VPM1, VPM2, Edge_to_faces, Coplanar_face_set, Node_visitor>; + Callback callback12(tm1, tm2, vpm1, vpm2, tm2_edge_to_tm1_faces, coplanar_faces, visitor); + Callback callback21(tm2, tm1, vpm2, vpm1, tm1_edge_to_tm2_faces, coplanar_faces, visitor); - /// \todo experiments different cutoff values - std::ptrdiff_t cutoff = 2 * std::ptrdiff_t( - std::sqrt(face_boxes.size()+edge_boxes.size()) ); - - Edge_to_faces& edge_to_faces = &tm_e < &tm_f - ? stm_edge_to_ltm_faces - : ltm_edge_to_stm_faces; - - #ifdef DO_NOT_HANDLE_COPLANAR_FACES - typedef Collect_face_bbox_per_edge_bbox - Callback; - Callback callback(tm_f, tm_e, edge_to_faces); - #else - typedef Collect_face_bbox_per_edge_bbox_with_coplanar_handling< - TriangleMesh, VPMF, VPME, Edge_to_faces, Coplanar_face_set, Node_visitor> - Callback; - Callback callback(tm_f, tm_e, vpm_f, vpm_e, edge_to_faces, coplanar_faces, visitor); - #endif - //using pointers in box_intersection_d is about 10% faster if (throw_on_self_intersection){ - Callback_with_self_intersection_report callback_si(callback, tm_f_faces, tm_e_faces); - CGAL::box_intersection_d(face_boxes_ptr.begin(), face_boxes_ptr.end(), - edge_boxes_ptr.begin(), edge_boxes_ptr.end(), - callback_si, cutoff); - if (run_check && callback_si.self_intersections_found()) - throw Self_intersection_exception(); + Callback_with_self_intersection_report callback_si_12(callback12, tm1_faces, tm2_faces); + Callback_with_self_intersection_report callback_si_21(callback21, tm2_faces, tm1_faces); + AABB_call(callback_si_12, callback_si_21); + if (throw_on_self_intersection && (callback_si_21.self_intersections_found() || callback_si_12.self_intersections_found())) + throw Self_intersection_exception(); } else { - if (const_mesh_ptr==&tm_e) + if (const_mesh_ptr==&tm1) { - // tm_f might feature degenerate faces - auto filtered_callback = [&callback](const Box* fb, const Box* eb) - { - if (!callback.is_face_degenerated(fb->info())) - callback(fb, eb); + // tm1 might feature degenerate features + auto filtered_callback_12 = [&](halfedge_descriptor h1, halfedge_descriptor h2){ + if (get(vpm2, source(h2, tm2)) != get(vpm2, target(h2, tm2))) + callback12(h1, h2); + else + { + for (int i=0; i<2; ++i) + { + if (!is_border(h2, tm2)) + { + if ( get(vpm2, target(next(h2, tm2), tm2))==get(vpm2, target(h2, tm2)) && + coplanar(get(vpm1, source(h1, tm1)), + get(vpm1, target(h1, tm1)), + get(vpm1, target(next(h1, tm1), tm1)), + get(vpm2, target(h2, tm2))) ) + { + coplanar_faces.insert( + &tm1 < &tm2 + ? std::make_pair(face(h1, tm1), face(h2, tm2)) + : std::make_pair(face(h2, tm2), face(h1, tm1)) + ); + } + } + h2=opposite(h2, tm2); + } + } + }; + auto filtered_callback_21 = [&](halfedge_descriptor h2, halfedge_descriptor h1){ + if(!callback21.is_face_degenerated(h2)) + callback21(h2, h1); }; - CGAL::box_intersection_d( face_boxes_ptr.begin(), face_boxes_ptr.end(), - edge_boxes_ptr.begin(), edge_boxes_ptr.end(), - filtered_callback, cutoff ); + AABB_call(filtered_callback_12, filtered_callback_21); } else { - if (const_mesh_ptr==&tm_f) + if (const_mesh_ptr==&tm2) { - // tm_e might feature degenerate edges - auto filtered_callback = [&,this](const Box* fb, const Box* eb) - { - if (get(vpm_e, source(eb->info(), tm_e)) != get(vpm_e, target(eb->info(), tm_e))) - callback(fb, eb); + // tm2 might feature degenerate features + auto filtered_callback_12 = [&](halfedge_descriptor h1, halfedge_descriptor h2){ + if(!callback12.is_face_degenerated(h1)) + callback12(h1, h2); + }; + auto filtered_callback_21 = [&](halfedge_descriptor h2, halfedge_descriptor h1){ + if (get(vpm1, source(h1, tm1)) != get(vpm1, target(h1, tm1))) + callback21(h2, h1); else { - halfedge_descriptor hf = fb->info(); - halfedge_descriptor he = eb->info(); for (int i=0; i<2; ++i) { - if (!is_border(he, tm_e)) + if (!is_border(h1, tm1)) { - if ( get(vpm_e, target(next(he, tm_e), tm_e))==get(vpm_e, target(he, tm_e)) && - coplanar(get(vpm_f, source(hf, tm_f)), - get(vpm_f, target(hf, tm_f)), - get(vpm_f, target(next(hf, tm_f), tm_f)), - get(vpm_e, target(he, tm_e))) ) + if ( get(vpm1, target(next(h1, tm1), tm1))==get(vpm1, target(h1, tm1)) && + coplanar(get(vpm2, source(h2, tm2)), + get(vpm2, target(h2, tm2)), + get(vpm2, target(next(h2, tm2), tm2)), + get(vpm1, target(h1, tm1))) ) { coplanar_faces.insert( - &tm_e < &tm_f - ? std::make_pair(face(he, tm_e), face(hf, tm_f)) - : std::make_pair(face(hf, tm_f), face(he, tm_e)) + &tm1 < &tm2 + ? std::make_pair(face(h1, tm1), face(h2, tm2)) + : std::make_pair(face(h2, tm2), face(h1, tm1)) ); } } - he=opposite(he, tm_e); + h1=opposite(h1, tm1); } } }; - CGAL::box_intersection_d( face_boxes_ptr.begin(), face_boxes_ptr.end(), - edge_boxes_ptr.begin(), edge_boxes_ptr.end(), - filtered_callback, cutoff ); + AABB_call(filtered_callback_12, filtered_callback_21); } else - CGAL::box_intersection_d( face_boxes_ptr.begin(), face_boxes_ptr.end(), - edge_boxes_ptr.begin(), edge_boxes_ptr.end(), - callback, cutoff ); + { + AABB_call(callback12, callback21); + } } } } @@ -411,49 +487,62 @@ class Intersection_of_triangle_meshes void filter_intersections(const TriangleMesh& tm, const VPM& vpm) { - std::vector face_boxes, edge_boxes; - std::vector face_boxes_ptr, edge_boxes_ptr; - - face_boxes.reserve(num_faces(tm)); - face_boxes_ptr.reserve(num_faces(tm)); - for(face_descriptor fd : faces(tm)) + using Point = typename boost::property_traits::value_type; + using GT = typename CGAL::Kernel_traits::Kernel; + using AABB_tree_helper = CGAL::Polygon_mesh_processing::internal::AABB_tree_graph_helper; + using Tree = typename AABB_tree_helper::Tree; + AABB_tree_helper helper; + + Tree tree; + helper.template build(faces(tm), tree, tm, vpm); + + using Callback = Collect_face_bbox_per_edge_bbox_with_coplanar_handling_one_mesh< + TriangleMesh, VPM, Edge_to_faces, Coplanar_face_set>; + Callback callback(tm, vpm, stm_edge_to_ltm_faces, coplanar_faces); + +#ifdef CGAL_LINKED_WITH_TBB + using Intersections = std::conditional_t>, + std::vector>>; +#else + using Intersections = std::vector>; +#endif + Intersections inter; +#ifdef CGAL_LINKED_WITH_TBB + if constexpr(ConcurrencyTag::is_parallel) { - halfedge_descriptor h=halfedge(fd,tm); - face_boxes.push_back( Box( - get(vpm,source(h,tm)).bbox() + - get(vpm,target(h,tm)).bbox() + - get(vpm,target(next(h,tm),tm)).bbox(), - h ) ); - face_boxes_ptr.push_back( &face_boxes.back() ); + CGAL::AABB_trees::all_pairs_of_intersecting_primitives(tree, std::back_inserter(inter)); } - - edge_boxes.reserve(num_edges(tm)); - edge_boxes_ptr.reserve(num_edges(tm)); - for(edge_descriptor ed : edges(tm)) + else +#endif { - halfedge_descriptor h=halfedge(ed,tm); - edge_boxes.push_back( Box( - get(vpm,source(h,tm)).bbox() + - get(vpm,target(h,tm)).bbox(), - h ) ); - edge_boxes_ptr.push_back( &edge_boxes.back() ); + CGAL::AABB_trees::all_pairs_of_intersecting_primitives(tree, std::back_inserter(inter)); + } + for(std::size_t i=0; i - Callback; - Callback callback(tm, vpm, edge_to_faces, coplanar_faces); - - //using pointers in box_intersection_d is about 10% faster - CGAL::box_intersection_d( face_boxes_ptr.begin(), face_boxes_ptr.end(), - edge_boxes_ptr.begin(), edge_boxes_ptr.end(), - callback, cutoff ); } template @@ -1081,11 +1170,7 @@ class Intersection_of_triangle_meshes typename std::vector::iterator it_edge=all_edges.begin(); switch(type){ case COPLANAR_TRIANGLES: - #ifndef DO_NOT_HANDLE_COPLANAR_FACES - CGAL_error_msg("COPLANAR_TRIANGLES : this point should never be reached!"); - #else //nothing needs to be done, cf. comments at the beginning of the file - #endif break; case EMPTY: fset.erase(fset.begin()); @@ -1896,10 +1981,12 @@ class Intersection_of_triangle_meshes if (!identical_meshes) { visitor.start_filtering_intersections(); - filter_intersections(tm1, tm2, vpm1, vpm2, non_manifold_feature_map_2, throw_on_self_intersection, tm1_faces, tm2_faces, bb12, - is_fshared_map1, is_eshared_map2, false); - filter_intersections(tm2, tm1, vpm2, vpm1, non_manifold_feature_map_1, throw_on_self_intersection, tm2_faces, tm1_faces, bb12, - is_fshared_map2, is_eshared_map1, true); + filter_intersections(tm1, tm2, vpm1, vpm2, + non_manifold_feature_map_1, non_manifold_feature_map_2, + throw_on_self_intersection, + tm1_faces, tm2_faces, + bb12, + is_fshared_map1, is_fshared_map2, is_eshared_map1, is_eshared_map2); visitor.end_filtering_intersections(); // dumping shared edges in output @@ -1943,17 +2030,13 @@ class Intersection_of_triangle_meshes Static_boolean_property_map is_fshared_map; Static_boolean_property_map is_eshared_map; visitor.start_filtering_intersections(); - filter_intersections(tm1, tm2, vpm1, vpm2, non_manifold_feature_map_2, throw_on_self_intersection, tm1_faces, tm2_faces, bb12, - is_fshared_map, is_eshared_map, false); - filter_intersections(tm2, tm1, vpm2, vpm1, non_manifold_feature_map_1, throw_on_self_intersection, tm2_faces, tm1_faces, bb12, - is_fshared_map, is_eshared_map, true); + filter_intersections(tm1, tm2, vpm1, vpm2, non_manifold_feature_map_1, non_manifold_feature_map_2, throw_on_self_intersection, tm1_faces, tm2_faces, bb12, is_fshared_map, is_fshared_map, is_eshared_map, is_eshared_map); visitor.end_filtering_intersections(); } Node_id current_node((std::numeric_limits::max)()); CGAL_assertion(current_node+1==0); // TODO: handle non-manifold edges in coplanar - #ifndef DO_NOT_HANDLE_COPLANAR_FACES //first handle coplanar triangles std::map vids1; if (&tm1<&tm2) @@ -2005,7 +2088,6 @@ class Intersection_of_triangle_meshes visitor.set_number_of_intersection_points_from_coplanar_faces(current_node+1); if (!coplanar_faces.empty()) visitor.input_have_coplanar_faces(); - #endif // not DO_NOT_HANDLE_COPLANAR_FACES //compute intersection points of segments and triangles. //build the nodes of the graph and connectivity infos diff --git a/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/refine_with_plane.h b/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/refine_with_plane.h index d2bf3327022b..97e597311890 100644 --- a/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/refine_with_plane.h +++ b/PMP_Boolean_operations/include/CGAL/Polygon_mesh_processing/refine_with_plane.h @@ -150,16 +150,41 @@ struct Orthogonal_cut_plane_traits Construct_direction_3 construct_direction_3_object() const { return Construct_direction_3(); } Compare_projection_along_direction_3 compare_projection_along_direction_3_object() const { return Compare_projection_along_direction_3(); } -#ifndef CGAL_PLANE_CLIP_DO_NOT_USE_BOX_INTERSECTION_D -// for does self-intersect +#ifndef CGAL_PLANE_CLIP_DO_NOT_USE_AABB_TREE using Segment_3 = typename Kernel::Segment_3; using Triangle_3 = typename Kernel::Triangle_3; using Construct_segment_3 = typename Kernel::Construct_segment_3; using Construct_triangle_3 =typename Kernel::Construct_triangle_3; using Do_intersect_3 = typename Kernel::Do_intersect_3; + using Construct_sphere_3 = typename Kernel::Construct_sphere_3; + using Sphere_3 = typename Kernel::Sphere_3; + using Iso_cuboid_3 = typename Kernel::Iso_cuboid_3; + using Cartesian_const_iterator_3 = typename Kernel::Cartesian_const_iterator_3; + using Construct_cartesian_const_iterator_3 = typename Kernel::Construct_cartesian_const_iterator_3; + using Construct_min_vertex_3 = typename Kernel::Construct_min_vertex_3; + using Construct_max_vertex_3 = typename Kernel::Construct_max_vertex_3; + using Construct_center_3 = typename Kernel::Construct_center_3; + using Compute_squared_radius_3 = typename Kernel::Compute_squared_radius_3; + using Construct_iso_cuboid_3 = typename Kernel::Construct_iso_cuboid_3; + using Equal_3 = typename Kernel::Equal_3; + using Less_x_3 = typename Kernel::Less_x_3; + using Less_y_3 = typename Kernel::Less_y_3; + using Less_z_3 = typename Kernel::Less_z_3; + + Construct_sphere_3 construct_sphere_3_object() const { return Construct_sphere_3(); } Construct_segment_3 construct_segment_3_object() const { return Construct_segment_3(); } Construct_triangle_3 construct_triangle_3_object() const { return Construct_triangle_3(); } Do_intersect_3 do_intersect_3_object() const { return Do_intersect_3(); } + Construct_cartesian_const_iterator_3 construct_cartesian_const_iterator_3_object() const { return Construct_cartesian_const_iterator_3(); } + Construct_min_vertex_3 construct_min_vertex_3_object() const { return Construct_min_vertex_3(); } + Construct_max_vertex_3 construct_max_vertex_3_object() const { return Construct_max_vertex_3(); } + Construct_center_3 construct_center_3_object() const { return Construct_center_3(); } + Compute_squared_radius_3 compute_squared_radius_3_object() const { return Compute_squared_radius_3(); } + Construct_iso_cuboid_3 construct_iso_cuboid_3_object() const { return Construct_iso_cuboid_3(); } + Equal_3 equal_3_object() const { return Equal_3(); } + Less_x_3 less_x_3_object() const { return Less_x_3(); } + Less_y_3 less_y_3_object() const { return Less_y_3(); } + Less_z_3 less_z_3_object() const { return Less_z_3(); } #endif }; #endif diff --git a/PMP_Boolean_operations/test/PMP_Boolean_operations/test_corefinement_bool_op.cpp b/PMP_Boolean_operations/test/PMP_Boolean_operations/test_corefinement_bool_op.cpp index 49a182d2bd31..306969d5645f 100644 --- a/PMP_Boolean_operations/test/PMP_Boolean_operations/test_corefinement_bool_op.cpp +++ b/PMP_Boolean_operations/test/PMP_Boolean_operations/test_corefinement_bool_op.cpp @@ -276,6 +276,9 @@ void run(char* P_fname, char* Q_fname, int k, int main(int argc,char** argv) { + // Check if DerivedMesh is correctly identified + static_assert( CGAL::Is_base_of_surface_mesh::value ); + if (argc<3){ std::cerr << "Usage "<< argv[0] << " file1.off file2.off [scenario_id/ALL] [0/1 0/1 0/1 0/1 (expected valid operations U I P-Q Q-P)]\n"; return 1; diff --git a/PMP_Remeshing/package_info/PMP_Remeshing/dependencies b/PMP_Remeshing/package_info/PMP_Remeshing/dependencies index 93ff9a692b37..0eea174a7341 100644 --- a/PMP_Remeshing/package_info/PMP_Remeshing/dependencies +++ b/PMP_Remeshing/package_info/PMP_Remeshing/dependencies @@ -2,7 +2,6 @@ AABB_tree Algebraic_foundations Arithmetic_kernel BGL -Box_intersection_d CGAL_Core Cartesian_kernel Circulator diff --git a/Polygon_mesh_processing/benchmark/Polygon_mesh_processing/include/AABB_meshes_intersections.h b/Polygon_mesh_processing/benchmark/Polygon_mesh_processing/include/AABB_meshes_intersections.h index a8cb29fb73b6..de3096de98d8 100644 --- a/Polygon_mesh_processing/benchmark/Polygon_mesh_processing/include/AABB_meshes_intersections.h +++ b/Polygon_mesh_processing/benchmark/Polygon_mesh_processing/include/AABB_meshes_intersections.h @@ -111,7 +111,7 @@ void mixed_meshes_intersections(const TriangleMesh1 &tm1, Bbox_pmap_1 bb1 = get(Face_bbox_tag(), tm1); Bbox_pmap_2 bb2 = get(Face_bbox_tag(), tm2); #ifdef CGAL_LINKED_WITH_TBB - if constexpr(std::is_same_v) + if constexpr(Concurrency_tag::is_parallel) { oneapi::tbb::parallel_for( oneapi::tbb::blocked_range(0, faces(tm1).size()), @@ -151,7 +151,7 @@ void mixed_meshes_intersections(const TriangleMesh1 &tm1, tree2.insert(faces(tm2).first, faces(tm2).second, tm2); #ifdef CGAL_LINKED_WITH_TBB - if constexpr(std::is_same_v) + if constexpr(Concurrency_tag::is_parallel) { CGAL_MUTEX m; oneapi::tbb::task_group tg; @@ -474,7 +474,7 @@ void AABB_two_trees_meshes_intersections(const TriangleMesh1 &tm1, Ref_point_map_2 rpm2 = get(Face_ref_point_tag(), tm); #ifdef CGAL_LINKED_WITH_TBB - if constexpr(std::is_same_v) + if constexpr(Concurrency_tag::is_parallel) { tbb::parallel_for(std::size_t(0), faces(tm1).size(), [&](std::size_t i){ face_descriptor f(i); @@ -512,7 +512,7 @@ void AABB_two_trees_meshes_intersections(const TriangleMesh1 &tm1, tree2.insert(faces(tm2).first, faces(tm2).second, tm2); #ifdef CGAL_LINKED_WITH_TBB - if constexpr(std::is_same_v) + if constexpr(Concurrency_tag::is_parallel) { oneapi::tbb::task_group tg; tg.run([&]{ tree1.template custom_build(compute_bbox1, split_primitives1); }); @@ -578,7 +578,7 @@ void AABB_self_intersections(const TriangleMesh &tm, OutputIterator out, const N tree.template build(); #ifdef CGAL_LINKED_WITH_TBB - if constexpr(std::is_same_v) + if constexpr(Concurrency_tag::is_parallel) { CGAL_MUTEX mutex; tbb::concurrent_vector> inter; @@ -679,7 +679,7 @@ void AABB_meshes_intersections(const TriangleMesh1 &tm1, tree.template build(); #ifdef CGAL_LINKED_WITH_TBB - if constexpr(std::is_same_v) + if constexpr(Concurrency_tag::is_parallel) { CGAL_MUTEX mutex; tbb::concurrent_vector> inter; diff --git a/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/connected_components.h b/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/connected_components.h index a389e983957b..40bf990f5649 100644 --- a/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/connected_components.h +++ b/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/connected_components.h @@ -124,6 +124,9 @@ connected_component(typename boost::graph_traits::face_descriptor s using parameters::choose_parameter; using parameters::get_parameter; + using face_descriptor = typename boost::graph_traits::face_descriptor; + using halfedge_descriptor = typename boost::graph_traits::halfedge_descriptor; + typedef typename internal_np::Lookup_named_param_def < internal_np::edge_is_constrained_t, NamedParameters, @@ -132,27 +135,28 @@ connected_component(typename boost::graph_traits::face_descriptor s EdgeConstraintMap ecmap = choose_parameter(get_parameter(np, internal_np::edge_is_constrained)); - typedef typename boost::graph_traits::face_descriptor face_descriptor; - typedef typename boost::graph_traits::halfedge_descriptor halfedge_descriptor; - std::set already_processed; + using Face_bool_tag = typename CGAL::dynamic_face_property_t; + using Bool_map = typename boost::property_map::const_type; + + Bool_map already_processed = get(Face_bool_tag(), pmesh, false); std::vector< face_descriptor > stack; stack.push_back(seed_face); while (!stack.empty()) + { + seed_face=stack.back(); + stack.pop_back(); + if (get(already_processed, seed_face)) continue; + put(already_processed, seed_face, true); + *out++=seed_face; + for(halfedge_descriptor hd: halfedges_around_face(halfedge(seed_face, pmesh), pmesh) ) { - seed_face=stack.back(); - stack.pop_back(); - if (!already_processed.insert(seed_face).second) continue; - *out++=seed_face; - for(halfedge_descriptor hd : - halfedges_around_face(halfedge(seed_face, pmesh), pmesh) ) - { - if(! get(ecmap, edge(hd, pmesh))){ - face_descriptor neighbor = face( opposite(hd, pmesh), pmesh ); - if ( neighbor != boost::graph_traits::null_face() ) - stack.push_back(neighbor); - } + if(! get(ecmap, edge(hd, pmesh))){ + face_descriptor neighbor = face( opposite(hd, pmesh), pmesh ); + if ( neighbor != boost::graph_traits::null_face() ) + stack.push_back(neighbor); } } + } return out; } diff --git a/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/internal/soup_and_face_graph_tree_helper.h b/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/internal/soup_and_face_graph_tree_helper.h new file mode 100644 index 000000000000..56574b4b219e --- /dev/null +++ b/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/internal/soup_and_face_graph_tree_helper.h @@ -0,0 +1,251 @@ +// Copyright (c) 2016 GeometryFactory (France). +// All rights reserved. +// +// This file is part of CGAL (www.cgal.org). +// +// $URL$ +// $Id$ +// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial +// +// +// Author(s) : Sebastien Loriot + +#ifndef CGAL_POLYGON_MESH_PROCESSING_INTERNAL_SOUP_AND_TREE_HELPER_H +#define CGAL_POLYGON_MESH_PROCESSING_INTERNAL_SOUP_AND_TREE_HELPER_H + +#include + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace CGAL { +namespace Polygon_mesh_processing { +namespace internal { + +template +struct AABB_tree_graph_helper +{ + using Primitive = AABB_face_graph_triangle_primitive; + using Traits = AABB_traits_3; + using Tree = AABB_tree; + + using Graph_traits = boost::graph_traits; + using vertex_descriptor = typename Graph_traits::vertex_descriptor; + using face_descriptor = typename Graph_traits::face_descriptor; + + template + struct Split_primitives + { + Split_primitives(const RPM &rpm): rpm(rpm){} + + template + void operator()(PrimitiveIterator first, + PrimitiveIterator beyond, + const CGAL::Bbox_3& bbox) const + { + PrimitiveIterator middle = first + (beyond - first)/2; + const int crd = bbox.largest_span_index(); + std::nth_element(first, middle, beyond, [this, crd](const Primitive& p1, const Primitive& p2){ return get(rpm, p1.id())[crd] < get(rpm, p2.id())[crd];}); + } + const RPM &rpm; + }; + + // For exact side_of_triangle_mesh + template + struct Compute_bbox { + Compute_bbox(const BPM& bpm): bpm(bpm){} + + template + CGAL::Bbox_3 operator()(ConstPrimitiveIterator first, + ConstPrimitiveIterator beyond) const + { + CGAL::Bbox_3 bbox = get(bpm, first->id()); + for(++first; first != beyond; ++first) + bbox += get(bpm, first->id()); + return bbox; + } + BPM bpm; + }; + + template + void build(const FaceRange &face_range, Tree& tree, const TriangleMesh& tm, VertexPointMap& vpm){ + using Face_bbox_tag = typename CGAL::dynamic_face_property_t; + // Reference point do not need to be exact, so we use Simple_cartesian for them + using FloatK = Simple_cartesian; + using Face_ref_point_tag = typename CGAL::dynamic_face_property_t; + using Bbox_map = typename boost::property_map::const_type; + using Ref_point_map = typename boost::property_map::const_type; + + using VPM_kernel = typename Kernel_traits::value_type>::Kernel; + CGAL::Cartesian_converter to_input; + + // we put a default value for case the property vector is not fully allocated. + // For exampe maps using a unordered map would have an issue with the concurrent insertion + Bbox_map bb_map = get(Face_bbox_tag(), tm, Bbox_3()); + Ref_point_map rp_map = get(Face_ref_point_tag(), tm, FloatK::Point_3(0.f,0.f,0.f)); + +#ifdef CGAL_LINKED_WITH_TBB + if constexpr(Concurrency_tag::is_parallel) + { + tbb::parallel_for( + tbb::blocked_range(0, face_range.size()), + [&](const tbb::blocked_range& block) + { + auto it = std::next(std::begin(face_range), block.begin()); + for (std::size_t i = block.begin(); i != block.end(); ++i, ++it) + { + face_descriptor f = *it; + put(bb_map, f, face_bbox(f, tm, parameters::vertex_point_map(vpm))); + put(rp_map, f, to_input(get(vpm, target(halfedge(f, tm), tm)))); + } + }); + } + else +#endif + { + for(face_descriptor f : face_range){ + put(bb_map, f, face_bbox(f, tm, parameters::vertex_point_map(vpm))); + put(rp_map, f, to_input(get(vpm, target(halfedge(f, tm), tm))) ); + } + } + tree.insert(face_range.begin(), face_range.end(), tm, vpm); + + Compute_bbox compute_bbox(bb_map); + Split_primitives split_primitives(rp_map); + tree.template custom_build(compute_bbox, split_primitives); + } + + template + void build(Tree& tree, const TriangleMesh& tm, VertexPointMap& vpm){ + build(faces(tm), tree, tm, vpm); + } +}; + +#ifndef DOXYGEN_RUNNING +template +struct Property_map_for_soup +{ + using VPM_base = VPM; + using key_type = std::size_t; + using value_type = typename boost::property_traits::value_type; + using category = boost::readable_property_map_tag; + using reference = typename boost::property_traits::reference; + + const PointRange& points; + VPM vpm; + + Property_map_for_soup(const PointRange& points, VPM vpm) + : points(points) + , vpm(vpm) + {} + + inline friend + reference get(const Property_map_for_soup& map, key_type k) + { + return get(map.vpm, map.points[k]); + } +}; + +template +struct AABB_tree_soup_helper +{ + using Primitive = AABB_indexed_triangle_primitive_3; + using Traits = AABB_traits_3; + using Tree = AABB_tree; + + template + struct Split_primitives + { + Split_primitives(const RPM &rpm): rpm(rpm){} + + template + void operator()(PrimitiveIterator first, + PrimitiveIterator beyond, + const CGAL::Bbox_3& bbox) const + { + PrimitiveIterator middle = first + (beyond - first)/2; + const int crd = bbox.largest_span_index(); + std::nth_element(first, middle, beyond, [this, crd](const auto& p1, const auto& p2){ return get(rpm, p1.id())[crd] < get(rpm, p2.id())[crd];}); + } + const RPM &rpm; + }; + + // For exact side_of_triangle_mesh + template + struct Compute_bbox { + Compute_bbox(const BPM& bpm): bpm(bpm){} + + template + CGAL::Bbox_3 operator()(ConstPrimitiveIterator first, + ConstPrimitiveIterator beyond) const + { + CGAL::Bbox_3 bbox; + for(; first != beyond; ++first) + bbox += get(bpm, first->id()); + return bbox; + } + BPM bpm; + }; + + template + void build(const FaceRange &face_range, Tree& tree, const PointRange& pts, const TriangleRange& triangles, VPM vpm){ + using PM_kernel = typename Kernel_traits::value_type>::Kernel; + using FloatK = Simple_cartesian; + using Bbox_map = Pointer_property_map::type; + using Ref_point_map = Pointer_property_map::type; + + CGAL::Cartesian_converter to_input; + + tree.insert(face_range.begin(), face_range.end(), pts, triangles, vpm.vpm); + + std::vector bb_vector(triangles.size(), Bbox_3()); + std::vector rp_vector(triangles.size(), FloatK::Point_3()); + Bbox_map bb_map = make_property_map(bb_vector); + Ref_point_map rp_map = make_property_map(rp_vector); + +#ifdef CGAL_LINKED_WITH_TBB + if constexpr(ConcurrencyTag::is_parallel) + { + tbb::parallel_for(std::size_t(0), face_range.size(), [&](std::size_t i){ + auto tid = face_range[i]; + put(bb_map, tid, get(vpm, triangles[tid][0]).bbox() + + get(vpm, triangles[tid][1]).bbox() + + get(vpm, triangles[tid][2]).bbox()); + put(rp_map, tid, to_input(get(vpm, triangles[tid][0])) ); + }); + } + else +#endif + { + for(std::size_t i: face_range){ + put(bb_map, i, get(vpm, triangles[i][0]).bbox() + + get(vpm, triangles[i][1]).bbox() + + get(vpm, triangles[i][2]).bbox()); + put(rp_map, i, to_input(get(vpm, triangles[i][0])) ); + } + } + Compute_bbox compute_bbox(bb_map); + Split_primitives split_primitives(rp_map); + tree.template custom_build(compute_bbox, split_primitives); + } + + template + void build(Tree& tree, const PointRange& pts, const TriangleRange& triangles, VPM vpm){ + build(triangles, tree, pts, triangles, vpm); + } +}; + +#endif + +} } } // CGAL::Polygon_mesh_processing::internal + +#endif // CGAL_POLYGON_MESH_PROCESSING_INTERNAL_SOUP_AND_TREE_HELPER_H diff --git a/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/intersection.h b/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/intersection.h index ad7cbcf36f9f..afd7292d0cc2 100644 --- a/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/intersection.h +++ b/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/intersection.h @@ -17,11 +17,9 @@ #include -#include -#include -#include -#include -#include +#include +#include + #include #include #include @@ -30,6 +28,10 @@ #include #include +#ifdef CGAL_LINKED_WITH_TBB +#include +#endif + #include #include #include @@ -40,1020 +42,6 @@ namespace CGAL { namespace Polygon_mesh_processing { namespace internal { -template -struct Intersect_faces -{ - // typedefs - typedef typename Kernel::Segment_3 Segment; - typedef typename Kernel::Triangle_3 Triangle; - - typedef typename boost::graph_traits::halfedge_descriptor halfedge_descriptor; - typedef typename boost::property_map::const_type Ppmap; - - // members - const TM& m_tm1; - const VertexPointMap1 m_vpmap1; - const TM& m_tm2; - const VertexPointMap2 m_vpmap2; - mutable OutputIterator m_iterator; - - typename Kernel::Construct_triangle_3 triangle_functor; - typename Kernel::Do_intersect_3 do_intersect_3_functor; - - Intersect_faces(const TM& tm1, const TM& tm2, - OutputIterator it, - VertexPointMap1 vpmap1, VertexPointMap2 vpmap2, - const Kernel& kernel) - : - m_tm1(tm1), - m_vpmap1(vpmap1), - m_tm2(tm2), - m_vpmap2(vpmap2), - m_iterator(it), - triangle_functor(kernel.construct_triangle_3_object()), - do_intersect_3_functor(kernel.do_intersect_3_object()) - { } - - void operator()(const Box* b, const Box* c) const - { - halfedge_descriptor h = halfedge(b->info(), m_tm1); - halfedge_descriptor g = halfedge(c->info(), m_tm2); - - - // check for geometric intersection - Triangle t1 = triangle_functor( get(m_vpmap1, target(h,m_tm1)), - get(m_vpmap1, target(next(h,m_tm1),m_tm1)), - get(m_vpmap1, source(h,m_tm1))); - - Triangle t2 = triangle_functor( get(m_vpmap2, target(g,m_tm2)), - get(m_vpmap2, target(next(g,m_tm2),m_tm2)), - get(m_vpmap2, source(g,m_tm2))); - if(do_intersect_3_functor(t1, t2)){ - *m_iterator++ = std::make_pair(b->info(), c->info()); - } - } // end operator () -}; // end struct Intersect_faces - -template -struct Intersect_face_polyline -{ - // wrapper to check whether anything is inserted to output iterator - - // typedefs - typedef typename Kernel::Segment_3 Segment; - typedef typename Kernel::Triangle_3 Triangle; - - typedef typename boost::graph_traits::halfedge_descriptor halfedge_descriptor; - typedef typename boost::graph_traits::face_descriptor face_descriptor; - typedef typename boost::property_map::const_type Ppmap; - typedef typename boost::property_traits::value_type Point; - - - // members - const TM& m_tm; - const std::vector& faces; - const VertexPointMap m_vpmap; - const Polyline& polyline; - mutable OutputIterator m_iterator; - - typename Kernel::Construct_segment_3 segment_functor; - typename Kernel::Construct_triangle_3 triangle_functor; - typename Kernel::Do_intersect_3 do_intersect_3_functor; - - Intersect_face_polyline(const TM& tm, - const std::vector& faces, - const Polyline& polyline, - OutputIterator it, - VertexPointMap vpmap, - const Kernel& kernel) - : - m_tm(tm), - faces(faces), - m_vpmap(vpmap), - polyline(polyline), - m_iterator(it), - segment_functor(kernel.construct_segment_3_object()), - triangle_functor(kernel.construct_triangle_3_object()), - do_intersect_3_functor(kernel.do_intersect_3_object()) - { } - - void operator()(const Box* b, const Box* c) const - { - halfedge_descriptor h = halfedge(faces[b->info()], m_tm); - - - // check for geometric intersection - Triangle t = triangle_functor( get(m_vpmap, target(h,m_tm)), - get(m_vpmap, target(next(h,m_tm),m_tm)), - get(m_vpmap, source(h,m_tm))); - - Segment s = segment_functor(polyline[c->info()], polyline[c->info() + 1]); - if(do_intersect_3_functor(t, s)){ - *m_iterator++ = std::make_pair(b->info(), c->info()); - } - } // end operator () -}; // end struct Intersect_face_polyline - -template -struct Intersect_face_polylines -{ - // wrapper to check whether anything is inserted to output iterator - - // typedefs - typedef typename Kernel::Segment_3 Segment; - typedef typename Kernel::Triangle_3 Triangle; - - typedef typename boost::graph_traits::halfedge_descriptor halfedge_descriptor; - typedef typename boost::graph_traits::face_descriptor face_descriptor; - typedef typename boost::property_map::const_type Ppmap; - typedef typename boost::property_traits::value_type Point; - - // members - const TM& m_tm; - const std::vector& faces; - const VertexPointMap m_vpmap; - const PolylineRange& polylines; - mutable OutputIterator m_iterator; - - typename Kernel::Construct_segment_3 segment_functor; - typename Kernel::Construct_triangle_3 triangle_functor; - typename Kernel::Do_intersect_3 do_intersect_3_functor; - - Intersect_face_polylines(const TM& tm, - const std::vector& faces, - const PolylineRange& polylines, - OutputIterator it, - VertexPointMap vpmap, - const Kernel& kernel) - : - m_tm(tm), - faces(faces), - m_vpmap(vpmap), - polylines(polylines), - m_iterator(it), - segment_functor(kernel.construct_segment_3_object()), - triangle_functor(kernel.construct_triangle_3_object()), - do_intersect_3_functor(kernel.do_intersect_3_object()) - { } - - void operator()(const Box* b, const Box* c) const - { - halfedge_descriptor h = halfedge(faces[b->info().second], m_tm); - - - // check for geometric intersection - Triangle t = triangle_functor( get(m_vpmap, target(h,m_tm)), - get(m_vpmap, target(next(h,m_tm),m_tm)), - get(m_vpmap, source(h,m_tm))); - - Segment s = segment_functor(polylines[c->info().first][c->info().second], polylines[c->info().first][c->info().second + 1]); - if(do_intersect_3_functor(t, s)){ - *m_iterator++ = std::make_pair(b->info().second, c->info()); - } - } // end operator () -}; // end struct Intersect_face_polylines - - -template -struct Intersect_polylines -{ - // typedefs - typedef typename Kernel::Segment_3 Segment; - typedef typename Kernel::Point_3 Point; - - - // members - const Polyline& polyline1; - const Polyline& polyline2; - mutable OutputIterator m_iterator; - - typename Kernel::Construct_segment_3 segment_functor; - typename Kernel::Do_intersect_3 do_intersect_3_functor; - - Intersect_polylines(const Polyline& polyline1, - const Polyline& polyline2, - OutputIterator it, - const Kernel& kernel) - : - polyline1(polyline1), - polyline2(polyline2), - m_iterator(it), - segment_functor(kernel.construct_segment_3_object()), - do_intersect_3_functor(kernel.do_intersect_3_object()) - { } - - void operator()(const Box* b, const Box* c) const - { - - - // check for geometric intersection - - Segment s1 = segment_functor(polyline1[b->info()], polyline1[b->info() + 1]); - Segment s2 = segment_functor(polyline2[c->info()], polyline2[c->info() + 1]); - if(do_intersect_3_functor(s1, s2)){ - *m_iterator++ = std::make_pair(b->info(), c->info()); - } - } // end operator () -}; // end struct Intersect_polylines - -template -struct Intersect_polyline_ranges -{ - // typedefs - typedef typename Kernel::Segment_3 Segment; - typedef typename Kernel::Point_3 Point; - - - // members - const PolylineRange& polyline1; - const PolylineRange& polyline2; - mutable OutputIterator m_iterator; - - typename Kernel::Construct_segment_3 segment_functor; - typename Kernel::Do_intersect_3 do_intersect_3_functor; - - Intersect_polyline_ranges(const PolylineRange& polyline1, - const PolylineRange& polyline2, - OutputIterator it, - const Kernel& kernel) - : - polyline1(polyline1), - polyline2(polyline2), - m_iterator(it), - segment_functor(kernel.construct_segment_3_object()), - do_intersect_3_functor(kernel.do_intersect_3_object()) - { } - - void operator()(const Box* b, const Box* c) const - { - - - // check for geometric intersection - - Segment s1 = segment_functor(polyline1[b->info().first][b->info().second], polyline1[b->info().first][b->info().second + 1]); - Segment s2 = segment_functor(polyline2[c->info().first][c->info().second], polyline2[c->info().first][c->info().second + 1]); - - if(do_intersect_3_functor(s1, s2)){ - *m_iterator++ = std::make_pair(b->info(), c->info()); - } - } // end operator () -}; // end struct Intersect_polyline_ranges - -struct Throw_at_first_output { - class Throw_at_first_output_exception: public std::exception - { }; - - template - void operator()(const T& /* t */) const { - throw Throw_at_first_output_exception(); - } -}; - -// Note this is not officially documented -/* \ingroup PMP_intersection_grp - * - * reports all the pairs of faces intersecting between two triangulated surface meshes. - * - * This function depends on the package \ref PkgBoxIntersectionD. - * - * @pre \link CGAL::is_triangle_mesh `CGAL::is_triangle_mesh(tm1)` \endlink - * @pre \link CGAL::is_triangle_mesh `CGAL::is_triangle_mesh(tm2)` \endlink - * - * \tparam TriangleMesh a model of `FaceListGraph` - * \tparam FaceRange range of `boost::graph_traits::%face_descriptor`, - * model of `RandomAccessRange`. - * \tparam OutputIterator a model of `OutputIterator` holding objects of type - * `std::pair::%face_descriptor, boost::graph_traits::%face_descriptor>` - * \tparam NamedParameters a sequence of \ref bgl_namedparameters "Named Parameters" - * - * \param face_range1 the range of faces of `tm1` to check for intersections. - * \param face_range2 the range of faces of `tm2` to check for intersections. - * \param tm1 the first triangulated surface mesh. - * \param tm2 the second triangulated surface mesh. - * \param out output iterator to be filled with all pairs of faces that intersect. - * First and second element in the pairs correspond to faces of `tm1` and `tm2` respectively - * \param np1 an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below - * \param np2 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 `tm1` (`tm2`)} - * \cgalParamType{a class model of `ReadablePropertyMap` with `boost::graph_traits::%vertex_descriptor` - * as key type and `%Point_3` as value type} - * \cgalParamDefault{`boost::get(CGAL::vertex_point, tm1 (tm2))`} - * \cgalParamExtra{If this parameter is omitted, an internal property map for `CGAL::vertex_point_t` - * should be available for the vertices of `tm1` (`tm2`)} - * \cgalParamExtra{Both vertex point maps must have the same value type} - * \cgalParamNEnd - * - * \cgalParamNBegin{geom_traits} - * \cgalParamDescription{an instance of a geometric traits class} - * \cgalParamType{a class model of `PMPSelfIntersectionTraits`} - * \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.} - * \cgalParamExtra{np1 only} - * \cgalParamNEnd - * \cgalNamedParamsEnd - * - * \return `out` - */ -template -OutputIterator -compute_face_face_intersection(const FaceRange& face_range1, - const FaceRange& face_range2, - const TriangleMesh& tm1, - const TriangleMesh& tm2, - OutputIterator out, - const NamedParameters1& np1, - const NamedParameters2& np2) -{ - using parameters::get_parameter; - using parameters::choose_parameter; - - CGAL_precondition(CGAL::is_triangle_mesh(tm1)); - CGAL_precondition(CGAL::is_triangle_mesh(tm2)); - - typedef TriangleMesh TM; - typedef typename boost::graph_traits::face_descriptor face_descriptor; - - typedef CGAL::Box_intersection_d::ID_FROM_BOX_ADDRESS Box_policy; - typedef CGAL::Box_intersection_d::Box_with_info_d Box; - - CGAL::Bbox_3 b1 = CGAL::Polygon_mesh_processing::bbox(tm1, np1), - b2 = CGAL::Polygon_mesh_processing::bbox(tm2, np2); - - if(!CGAL::do_overlap(b1, b2)) - { - return out; - } - - // make one box per facet - std::vector boxes1; - std::vector boxes2; - boxes1.reserve(std::distance(std::begin(face_range1), std::end(face_range1))); - boxes2.reserve(std::distance(std::begin(face_range2), std::end(face_range2))); - - typedef typename GetVertexPointMap::const_type VertexPointMap1; - typedef typename GetVertexPointMap::const_type VertexPointMap2; - - VertexPointMap1 vpmap1 = choose_parameter(get_parameter(np1, internal_np::vertex_point), - get_const_property_map(boost::vertex_point, tm1)); - VertexPointMap2 vpmap2 = choose_parameter(get_parameter(np2, internal_np::vertex_point), - get_const_property_map(boost::vertex_point, tm2)); - static_assert( - (std::is_same< - typename boost::property_traits::value_type, - typename boost::property_traits::value_type - >::value) ); - - for(face_descriptor f : face_range1) - { - boxes1.push_back(Box(Polygon_mesh_processing::face_bbox(f, tm1), f)); - } - - for(face_descriptor f : face_range2) - { - boxes2.push_back(Box(Polygon_mesh_processing::face_bbox(f, tm2), f)); - } - - // generate box pointers - std::vector box1_ptr(boost::make_counting_iterator(&boxes1[0]), - boost::make_counting_iterator(&boxes1[0]+boxes1.size())); - std::vector box2_ptr(boost::make_counting_iterator(&boxes2[0]), - boost::make_counting_iterator(&boxes2[0]+boxes2.size())); - - // compute intersections filtered out by boxes - typedef typename GetGeomTraits::type GeomTraits; - GeomTraits gt = choose_parameter(get_parameter(np1, internal_np::geom_traits)); - - internal::Intersect_faces Intersect_faces(tm1, tm2, out, vpmap1, vpmap2, gt); - - std::ptrdiff_t cutoff = 2000; - CGAL::box_intersection_d(box1_ptr.begin(), box1_ptr.end(), - box2_ptr.begin(), box2_ptr.end(), - Intersect_faces,cutoff); - return Intersect_faces.m_iterator; -} - -// Note this is not officially documented -/* \ingroup PMP_intersection_grp - * - * reports all the pairs of segments and faces intersecting between - * a triangulated surface mesh and a polyline. - * - * This function depends on the package \ref PkgBoxIntersectionD. - * - * \attention If a polyline vertex intersects a face, the intersection will - * be reported twice (or more if it is on a vertex, edge, or point). - * - * @pre \link CGAL::is_triangle_mesh `CGAL::is_triangle_mesh(tm)` \endlink - * - * \tparam TriangleMesh a model of `FaceListGraph` - * \tparam FaceRange range of `boost::graph_traits::%face_descriptor`, - * model of `RandomAccessRange`. - * \tparam Polyline a `RandomAccessRange` of points. The point type of the range must be - * the same as the value type of the vertex point map. - * \tparam OutputIterator a model of `OutputIterator` holding objects of type - * `std::pair`.This `OutputIterator` will hold the position of the - * elements in their respective range. In the case of the polyline, this position is the index of - * the segment intersecting the face (which is the index of the first point of the - * segment following the range order.) - * \tparam NamedParameters a sequence of \ref bgl_namedparameters "Named Parameters" - * - * \param face_range the range of faces of `tm` to check for intersections. - * \param polyline the polyline to check for intersections. - * \param tm the triangulated surface mesh to check for intersections. - * \param out output iterator to be filled with all pairs of face-segment that intersect - * \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 `tm`} - * \cgalParamType{a class model of `ReadablePropertyMap` with `boost::graph_traits::%vertex_descriptor` as key type and `%Point_3` as value type} - * \cgalParamDefault{`boost::get(CGAL::vertex_point, tm)`} - * \cgalParamExtra{If this parameter is omitted, an internal property map for `CGAL::vertex_point_t` - * should be available for the vertices of `tm`.} - * \cgalParamNEnd - * - * \cgalParamNBegin{geom_traits} - * \cgalParamDescription{an instance of a geometric traits class} - * \cgalParamType{a class model of `PMPSelfIntersectionTraits`} - * \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 - * \cgalNamedParamsEnd - * - * \return `out` - */ -template -OutputIterator -compute_face_polyline_intersection(const FaceRange& face_range, - const Polyline& polyline, - const TriangleMesh& tm, - OutputIterator out, - const NamedParameters& np) -{ - using parameters::choose_parameter; - using parameters::get_parameter; - - CGAL_precondition(CGAL::is_triangle_mesh(tm)); - - CGAL::Bbox_3 b1 = CGAL::Polygon_mesh_processing::bbox(tm, np), - b2 = CGAL::bbox_3(polyline.begin(), polyline.end()); - - if(!CGAL::do_overlap(b1,b2)) - return out; - typedef TriangleMesh TM; - typedef typename boost::graph_traits::face_descriptor face_descriptor; - typedef typename GetVertexPointMap::const_type VertexPointMap; - - VertexPointMap vpmap = choose_parameter(get_parameter(np, internal_np::vertex_point), - get_const_property_map(boost::vertex_point, tm)); - typedef typename boost::property_traits::value_type Point; - static_assert( - (std::is_same::type>::value)); - - std::vector faces; - faces.reserve(std::distance(std::begin(face_range), std::end(face_range))); - - typedef CGAL::Box_intersection_d::ID_FROM_BOX_ADDRESS Box_policy; - typedef CGAL::Box_intersection_d::Box_with_info_d Box; - - // make one box per facet - std::vector boxes1; - std::vector boxes2; - boxes1.reserve(std::distance(std::begin(face_range), std::end(face_range))); - boxes2.reserve(std::distance(std::begin(polyline), std::end(polyline)) - 1); - - for(face_descriptor f : face_range) - { - faces.push_back(f); - boxes1.push_back(Box(Polygon_mesh_processing::face_bbox(f, tm), faces.size()-1)); - } - - for(std::size_t i =0; i< polyline.size()-1; ++i) - { - Point p1 = polyline[i]; - Point p2 = polyline[i+1]; - boxes2.push_back(Box(p1.bbox() + p2.bbox(), i)); - } - - // generate box pointers - std::vector box1_ptr(boost::make_counting_iterator(&boxes1[0]), - boost::make_counting_iterator(&boxes1[0]+boxes1.size())); - std::vector box2_ptr(boost::make_counting_iterator(&boxes2[0]), - boost::make_counting_iterator(&boxes2[0]+boxes2.size())); - - // compute intersections filtered out by boxes - typedef typename GetGeomTraits::type GeomTraits; - GeomTraits gt = choose_parameter(get_parameter(np, internal_np::geom_traits)); - - internal::Intersect_face_polyline - Intersect_face_polyline(tm, faces, polyline, out, vpmap, gt); - - std::ptrdiff_t cutoff = 2000; - CGAL::box_intersection_d(box1_ptr.begin(), box1_ptr.end(), - box2_ptr.begin(), box2_ptr.end(), - Intersect_face_polyline, cutoff); - return Intersect_face_polyline.m_iterator; -} - -// Note this is not officially documented -/* \ingroup PMP_intersection_grp - * - * reports all the pairs of segments and faces intersecting between - * a triangulated surface mesh and a range of polylines. - * - * This function depends on the package \ref PkgBoxIntersectionD. - * - * \attention If a polyline vertex intersects a face, the intersection will - * be reported twice (even more if it is on a vertex, edge, or point). - * - * @pre \link CGAL::is_triangle_mesh `CGAL::is_triangle_mesh(tm)` \endlink - * - * \tparam TriangleMesh a model of `FaceListGraph` - * \tparam FaceRange range of `boost::graph_traits::%face_descriptor`, - * model of `RandomAccessRange`. - * \tparam PolylineRange a `RandomAccessRange` of `RandomAccessRange` of points. The point type of the range must be - * the same as the value type of the vertex point map. - * \tparam OutputIterator a model of `OutputIterator` holding objects of type - * `std::pair >`. - * Each pair holds the index of the face and a pair containing the index of the polyline in the range and the index of - * the first point of the segment in the polyline. - * \tparam NamedParameters a sequence of \ref bgl_namedparameters "Named Parameters" - * - * \param face_range the range of `tm` faces to check for intersections. - * \param polyline_range the range of polylines to check for intersections. - * \param tm the triangulated surface mesh to check for intersections. - * \param out output iterator to be filled with all pairs of face-segment that intersect - * \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 `tm`} - * \cgalParamType{a class model of `ReadablePropertyMap` with `boost::graph_traits::%vertex_descriptor` - * as key type and `%Point_3` as value type} - * \cgalParamDefault{`boost::get(CGAL::vertex_point, tm)`} - * \cgalParamExtra{If this parameter is omitted, an internal property map for `CGAL::vertex_point_t` - * should be available for the vertices of `tm`.} - * \cgalParamNEnd - * - * \cgalParamNBegin{geom_traits} - * \cgalParamDescription{an instance of a geometric traits class} - * \cgalParamType{a class model of `PMPSelfIntersectionTraits`} - * \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 - * \cgalNamedParamsEnd - * \return `out` - */ -template -OutputIterator -compute_face_polylines_intersection(const FaceRange& face_range, - const PolylineRange& polyline_range, - const TriangleMesh& tm, - OutputIterator out, - const NamedParameters& np) -{ - using parameters::choose_parameter; - using parameters::get_parameter; - - CGAL_precondition(CGAL::is_triangle_mesh(tm)); - - CGAL::Bbox_3 b1,b2; - b1 = CGAL::Polygon_mesh_processing::bbox(tm, np); - for(std::size_t i =0; i< polyline_range.size(); ++i) - { - b2 += CGAL::bbox_3(polyline_range[i].begin(), - polyline_range[i].end()); - } - - if(!CGAL::do_overlap(b1,b2)) - return out; - - typedef TriangleMesh TM; - typedef typename boost::graph_traits::face_descriptor face_descriptor; - typedef typename GetVertexPointMap::const_type VertexPointMap; - - VertexPointMap vpmap = choose_parameter(get_parameter(np, internal_np::vertex_point), - get_const_property_map(boost::vertex_point, tm)); - typedef typename boost::property_traits::value_type Point; - typedef typename boost::range_value::type Polyline; - static_assert(std::is_same::type>::value); - - std::vector faces; - faces.reserve(std::distance( std::begin(face_range), std::end(face_range) )); - - typedef CGAL::Box_intersection_d::ID_FROM_BOX_ADDRESS Box_policy; - typedef CGAL::Box_intersection_d::Box_with_info_d, Box_policy> Box; - - // make one box per facet - std::vector boxes1; - std::vector boxes2; - boxes1.reserve(std::distance(std::begin(face_range), std::end(face_range))); - - std::size_t polylines_size = 0; - for(Polyline poly : polyline_range) - { - polylines_size += std::distance( std::begin(poly), std::end(poly) ) -1; - } - boxes2.reserve(polylines_size); - - for(face_descriptor f : face_range) - { - faces.push_back(f); - boxes1.push_back(Box(Polygon_mesh_processing::face_bbox(f, tm), std::make_pair(0, faces.size()-1))); - } - - std::size_t range_size = std::distance( std::begin(polyline_range), std::end(polyline_range) ); - for(std::size_t j = 0; j < range_size; ++j) - { - Polyline poly = polyline_range[j]; - std::size_t size = std::distance( std::begin(poly), std::end(poly) ); - for(std::size_t i =0; i< size - 1; ++i) - { - Point p1 = poly[i]; - Point p2 = poly[i+1]; - boxes2.push_back(Box(p1.bbox() + p2.bbox(), std::make_pair(j, i))); - } - } - - // generate box pointers - - std::vector box1_ptr(boost::make_counting_iterator(&boxes1[0]), - boost::make_counting_iterator(&boxes1[0]+boxes1.size())); - std::vector box2_ptr(boost::make_counting_iterator(&boxes2[0]), - boost::make_counting_iterator(&boxes2[0]+boxes2.size())); - - // compute intersections filtered out by boxes - typedef typename GetGeomTraits::type GeomTraits; - GeomTraits gt = choose_parameter(get_parameter(np, internal_np::geom_traits)); - - internal::Intersect_face_polylines - Intersect_face_polyline(tm, faces, polyline_range, out, vpmap, gt); - - std::ptrdiff_t cutoff = 2000; - CGAL::box_intersection_d(box1_ptr.begin(), box1_ptr.end(), - box2_ptr.begin(), box2_ptr.end(), - Intersect_face_polyline, cutoff); - return Intersect_face_polyline.m_iterator; -} - -// Note this is not officially documented -/* \ingroup PMP_intersection_grp - * - * detects and records intersections between two polylines. - * - * This function depends on the package \ref PkgBoxIntersectionD. - * - * \attention If a polyline vertex intersects another polyline, the intersection will - * be reported twice (even more if it is on a vertex). - * - * \tparam Polyline a `RandomAccessRange` of points. - * \tparam OutputIterator a model of `OutputIterator` holding objects of type - * `std::pair`. This OutputIterator will hold the position of the - * elements in their respective range. This position is the index of the segment that holds the - * intersection, so it is the index of the first point of the segment following the range order. - * \tparam Kernel a model of `Kernel` - * - * \param polyline1 the first polyline to check for intersections. - * \param polyline2 the second polyline to check for intersections. - * \param out output iterator to be filled with all pairs of segments that intersect - * \param K an instance of `Kernel` - * - * \return `out` - */ -template < class Polyline, - class OutputIterator, - class Kernel> -OutputIterator -compute_polyline_polyline_intersection(const Polyline& polyline1, - const Polyline& polyline2, - OutputIterator out, - const Kernel& K) -{ - typedef CGAL::Box_intersection_d::ID_FROM_BOX_ADDRESS Box_policy; - typedef CGAL::Box_intersection_d::Box_with_info_d Box; - - typedef typename Kernel::Point_3 Point; - // make one box per facet - std::vector boxes1; - std::vector boxes2; - boxes1.reserve(std::distance(std::begin(polyline1), std::end(polyline1)) - 1); - boxes2.reserve(std::distance(std::begin(polyline2), std::end(polyline2)) - 1); - - for(std::size_t i =0; i< polyline1.size()-1; ++i) - { - const Point& p1 = polyline1[i]; - const Point& p2 = polyline1[i+1]; - boxes1.push_back(Box(p1.bbox() + p2.bbox(), i)); - } - - for(std::size_t i =0; i< polyline2.size()-1; ++i) - { - const Point& p1 = polyline2[i]; - const Point& p2 = polyline2[i+1]; - boxes2.push_back(Box(p1.bbox() + p2.bbox(), i)); - } - - // generate box pointers - std::vector box1_ptr(boost::make_counting_iterator(&boxes1[0]), - boost::make_counting_iterator(&boxes1[0]+boxes1.size())); - std::vector box2_ptr(boost::make_counting_iterator(&boxes2[0]), - boost::make_counting_iterator(&boxes2[0]+boxes2.size())); - - - // compute intersections filtered out by boxes - - internal::Intersect_polylines - intersect_polylines(polyline1, polyline2, out, K); - - std::ptrdiff_t cutoff = 2000; - CGAL::box_intersection_d(box1_ptr.begin(), box1_ptr.end(), - box2_ptr.begin(), box2_ptr.end(), - intersect_polylines, cutoff); - return intersect_polylines.m_iterator; -} - -// Note this is not officially documented -/* \ingroup PMP_intersection_grp - * - * detects and records intersections between two ranges of polylines. - * - * This function depends on the package \ref PkgBoxIntersectionD. - * - * \attention If a polyline vertex intersects another polyline, the intersection will - * be reported twice (even more if it is on a vertex). - * - * \tparam PolylineRange a `RandomAccessRange` of `RandomAccessRange` of points. - * \tparam OutputIterator a model of `OutputIterator` holding objects of type - * `std::pair, std::pair >`. - * Each pair holds the index of the face and a pair containing the index of the polyline in the range and the index of - * the first point of the segment in the polyline. - * \tparam Kernel a model of `Kernel` - * - * \param polylines1 the first range of polylines to check for intersections. - * \param polylines2 the second range of polylines to check for intersections. - * \param out output iterator to be filled with all pairs of segments that intersect - * \param K an instance of `Kernel` - * - * \return `out` - */ -template < class PolylineRange, - class OutputIterator, - class Kernel> -OutputIterator -compute_polylines_polylines_intersection(const PolylineRange& polylines1, - const PolylineRange& polylines2, - OutputIterator out, - const Kernel& K) -{ - //info.first is the index of the polyline in the range, info.second is the index of the point in the polyline - typedef CGAL::Box_intersection_d::ID_FROM_BOX_ADDRESS Box_policy; - typedef CGAL::Box_intersection_d::Box_with_info_d, Box_policy> Box; - - typedef typename Kernel::Point_3 Point; - typedef typename boost::range_value::type Polyline; - - // make one box per facet - std::vector boxes1; - std::vector boxes2; - std::size_t polylines_size = 0; - CGAL::Bbox_3 b1, b2; - for(Polyline poly : polylines1) - { - polylines_size += std::distance( std::begin(poly), std::end(poly) ) -1; - b1 += CGAL::bbox_3(poly.begin(), poly.end()); - } - boxes1.reserve( polylines_size ); - - polylines_size = 0; - for(Polyline poly : polylines2) - { - polylines_size += std::distance( std::begin(poly), std::end(poly) ) -1; - b2 += CGAL::bbox_3(poly.begin(), poly.end()); - } - boxes2.reserve(polylines_size); - - if(!CGAL::do_overlap(b1,b2)) - return out; - - std::size_t range_size = std::distance( std::begin(polylines1), std::end(polylines1) ); - for(std::size_t j = 0; j < range_size; ++j) - { - Polyline poly = polylines1[j]; - std::size_t size = std::distance( std::begin(poly), std::end(poly) ); - for(std::size_t i =0; i< size - 1; ++i) - { - const Point& p1 = poly[i]; - const Point& p2 = poly[i+1]; - boxes1.push_back(Box(p1.bbox() + p2.bbox(), std::make_pair(j, i))); - } - } - - range_size = std::distance( std::begin(polylines2), std::end(polylines2) ); - for(std::size_t j = 0; j < range_size; ++j) - { - Polyline poly = polylines2[j]; - std::size_t size = std::distance( std::begin(poly), std::end(poly) ); - for(std::size_t i =0; i< size - 1; ++i) - { - const Point& p1 = poly[i]; - const Point& p2 = poly[i+1]; - boxes2.push_back(Box(p1.bbox() + p2.bbox(), std::make_pair(j, i))); - } - } - - // generate box pointers - std::vector box1_ptr(boost::make_counting_iterator(&boxes1[0]), - boost::make_counting_iterator(&boxes1[0]+boxes1.size())); - std::vector box2_ptr(boost::make_counting_iterator(&boxes2[0]), - boost::make_counting_iterator(&boxes2[0]+boxes2.size())); - - - // compute intersections filtered out by boxes - internal::Intersect_polyline_ranges - intersect_polylines(polylines1, polylines2, out, K); - - std::ptrdiff_t cutoff = 2000; - CGAL::box_intersection_d(box1_ptr.begin(), box1_ptr.end(), - box2_ptr.begin(), box2_ptr.end(), - intersect_polylines, cutoff); - return intersect_polylines.m_iterator; -} - -// Note this is not officially documented -/* \ingroup PMP_intersection_grp - * - * reports all the pairs of faces intersecting between two triangulated surface meshes. - * - * This function depends on the package \ref PkgBoxIntersectionD. - * - * @pre \link CGAL::is_triangle_mesh `CGAL::is_triangle_mesh(tm1)` \endlink - * @pre \link CGAL::is_triangle_mesh `CGAL::is_triangle_mesh(tm2)` \endlink - * - * \tparam TriangleMesh a model of `FaceListGraph` - * \tparam OutputIterator a model of `OutputIterator` holding objects of type - * `std::pair::%face_descriptor, boost::graph_traits::%face_descriptor>` - * \tparam NamedParameters a sequence of \ref bgl_namedparameters "Named Parameters" - * - * \param tm1 the first triangulated surface mesh to check for intersections - * \param tm2 the second triangulated surface mesh to check for intersections - * \param out output iterator to be filled with all pairs of faces that intersect - * \param np1 an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below - * \param np2 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 `tm1` (`tm2`)} - * \cgalParamType{a class model of `ReadablePropertyMap` with `boost::graph_traits::%vertex_descriptor` - * as key type and `%Point_3` as value type} - * \cgalParamDefault{`boost::get(CGAL::vertex_point, tm1 (tm2))`} - * \cgalParamExtra{If this parameter is omitted, an internal property map for `CGAL::vertex_point_t` - * should be available for the vertices of `tm1` (`tm2`)} - * \cgalParamNEnd - * - * \cgalParamNBegin{geom_traits} - * \cgalParamDescription{an instance of a geometric traits class} - * \cgalParamType{a class model of `PMPSelfIntersectionTraits`} - * \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.} - * \cgalParamExtra{np1 only} - * \cgalParamNEnd - * \cgalNamedParamsEnd - * - * \return `out` - */ -template -OutputIterator -compute_face_face_intersection(const TriangleMesh& tm1, - const TriangleMesh& tm2, - OutputIterator out, - const NamedParameters1& np1, - const NamedParameters2& np2) -{ - return compute_face_face_intersection(faces(tm1), faces(tm2), - tm1, tm2, out, np1, np2); -} - -// Note this is not officially documented -/* \ingroup PMP_intersection_grp - * - * detects and records intersections between a triangulated surface mesh and a polyline. - * - * This function depends on the package \ref PkgBoxIntersectionD. - * - * \attention If a polyline vertex intersects a face or another polyline, the intersection will - * be reported twice (even more if it is on a vertex, edge, or point). - * - * @pre \link CGAL::is_triangle_mesh `CGAL::is_triangle_mesh(tm)` \endlink - * - * \tparam TriangleMesh a model of `FaceListGraph` - * \tparam Polyline a `RandomAccessRange` of points. The point type of the range must be the - * same as the value type of the vertex point map. - * \cgalDescribePolylineType - * \tparam OutputIterator a model of `OutputIterator` holding objects of type - * `std::pair`. This OutputIterator will hold the position of the - * elements in their respective range. In the case of the polyline, this position is the index - * of the segment that holds the intersection, so it is the index of the first point of the - * segment following the range order. - * \tparam NamedParameters a sequence of \ref bgl_namedparameters "Named Parameters" - * - * \param tm the triangulated surface mesh to check for intersections. - * \param polyline the polyline to check for intersections. - * \param out output iterator to be filled with all pairs of face-segment that intersect - * \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 `tm`} - * \cgalParamType{a class model of `ReadWritePropertyMap` with `boost::graph_traits::%vertex_descriptor` as key type and `%Point_3` as value type} - * \cgalParamDefault{`boost::get(CGAL::vertex_point, tm)`} - * \cgalParamExtra{If this parameter is omitted, an internal property map for `CGAL::vertex_point_t` - * should be available for the vertices of `tm`.} - * \cgalParamNEnd - * - * \cgalParamNBegin{geom_traits} - * \cgalParamDescription{an instance of a geometric traits class} - * \cgalParamType{a class model of `PMPSelfIntersectionTraits`} - * \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 - * \cgalNamedParamsEnd - * - * \return `out` - */ -template -OutputIterator -compute_face_polyline_intersection(const TriangleMesh& tm, - const Polyline& polyline, - OutputIterator out, - const NamedParameters& np) -{ - return compute_face_polyline_intersection(faces(tm), polyline, tm, out, np); -} - // functions to check for overlap of meshes template void get_one_point_per_cc(TriangleMesh& tm, @@ -1096,38 +84,164 @@ bool is_mesh2_in_mesh1_impl(const AABB_tree& tree1, const std::vector& points_of_interest2, const GT& gt) { - //for each CC, take a point on it and test bounded side - Side_of_triangle_mesh sotm(tree1, gt); - for(const typename GT::Point_3& p : points_of_interest2) + //for each CC, take a point on it and test bounded side + Side_of_triangle_mesh sotm(tree1, gt); + for(const typename GT::Point_3& p : points_of_interest2) + { + if(sotm(p) == CGAL::ON_BOUNDED_SIDE) // sufficient as we know meshes do not intersect + { + return true; + } + } + return false; +} + +template +bool is_mesh2_in_mesh1(const TriangleMesh& tm1, + const TriangleMesh& tm2, + const VPM1& vpm1, + const VPM2& vpm2, + const GT& gt) +{ + typedef CGAL::AABB_face_graph_triangle_primitive Primitive; + typedef CGAL::AABB_traits_3 Traits; + typedef CGAL::AABB_tree AABBTree; + + AABBTree tree1(faces(tm1).begin(), faces(tm1).end(), tm1, vpm1); + std::vector points_of_interest2; + get_one_point_per_cc(tm2, vpm2, points_of_interest2); + + return is_mesh2_in_mesh1_impl(tree1, points_of_interest2, gt); +} + + +}// namespace internal + +#ifndef DOXYGEN_RUNNING // Not documented yet, used by CGAL Lab +/** + * \ingroup PMP_intersection_grp + * + * detects and records intersections between two polylines. + * + * \attention If a polyline vertex intersects another polyline, the intersection will + * be reported twice (even more if it is on a vertex). + * + * \tparam PolylineRange a `RandomAccessRange` of `RandomAccessRange` of points. + * The point type must be from a 3D point from a \cgal Kernel. + * \cgalDescribePolylineType + * \tparam OutputIterator a model of `OutputIterator` holding objects of type + * `std::pair, std::pair >`. + * Each pair holds the index of the face and a pair containing the index of the polyline in the range and the index of + * the first point of the segment in the polyline. + * \tparam NamedParameters a sequence of \ref bgl_namedparameters "Named Parameters" for the algorithm + * + * @param polylines1 the first range of polylines to check for intersections. + * @param polylines2 the second range of polylines to check for intersections. + * @param out output iterator to be filled with all pairs of segments that intersect + * @param np an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below + * + * \cgalNamedParamsBegin + * \cgalParamNBegin{concurrency_tag} + * \cgalParamDescription{a tag indicating if the task should be done using one or several threads.} + * \cgalParamType{Either `CGAL::Sequential_tag`, or `CGAL::Parallel_tag`, or `CGAL::Parallel_if_available_tag`} + * \cgalParamDefault{`CGAL::Sequential_tag`} + * \cgalParamExtra{`np1` only} + * \cgalParamNEnd + * \cgalNamedParamsEnd + * + */ +template +OutputIterator intersections(const PolylineRange& polylines1, + const PolylineRange& polylines2, + OutputIterator out, + const NamedParameters& np = parameters::default_values() +#ifndef DOXYGEN_RUNNING + , const std::enable_if_t< + boost::has_range_iterator< + typename boost::mpl::eval_if< + boost::has_range_iterator, + boost::range_value, + std::false_type >::type + >::value + >* = 0//end enable_if +#endif + ) +{ + CGAL_USE(np); + using Concurrency_tag = typename internal_np::Lookup_named_param_def < + internal_np::concurrency_tag_t, + NamedParameters, + Sequential_tag + > ::type; + + using Polyline = typename boost::range_value::type; + using Point = typename boost::range_value::type; + using GT = typename CGAL::Kernel_traits::Kernel; + using Segment_3 = typename GT::Segment_3; + + using Segment_primitive = CGAL::AABB_segment_primitive_3::const_iterator>; + using Segment_traits = CGAL::AABB_traits_3; + using Segment_tree = CGAL::AABB_tree; + + Bbox_3 b1; + for(const auto& polyline : polylines1) + b1 += bbox_3(polyline.begin(), polyline.end()); + Bbox_3 b2; + for(const auto& polyline : polylines2) + b2 += bbox_3(polyline.begin(), polyline.end()); + + if(!CGAL::do_overlap(b1, b2)) + return out; + + Bbox_3 bb((std::max)(b1.xmin(),b2.xmin()), (std::max)(b1.ymin(),b2.ymin()), (std::max)(b1.zmin(),b2.zmin()), + (std::min)(b1.xmax(),b2.xmax()), (std::min)(b1.ymax(),b2.ymax()), (std::min)(b1.zmax(),b2.zmax())); + + // Store filtered segments and their original indices. + std::vector segments1, segments2; + std::vector> segment_indices1, segment_indices2; + + auto collect_segments = [&](const PolylineRange& polylines, + std::vector& segments, + std::vector>& segment_indices) { - if(sotm(p) == CGAL::ON_BOUNDED_SIDE) // sufficient as we know meshes do not intersect + std::size_t polyline_index = 0; + for(const auto& polyline : polylines) { - return true; + if(polyline.size() >= 2) + { + auto pit = std::begin(polyline); + auto prev = ++pit; + + for(; pit != std::end(polyline); ++pit, ++prev) + { + if(do_overlap(bb, prev->bbox()+pit->bbox())){ + segments.emplace_back(*prev, *pit); + segment_indices.emplace_back(polyline_index, std::size_t(prev - std::begin(polyline))); + } + } + } + ++polyline_index; } - } - return false; -} - -template -bool is_mesh2_in_mesh1(const TriangleMesh& tm1, - const TriangleMesh& tm2, - const VPM1& vpm1, - const VPM2& vpm2, - const GT& gt) -{ - typedef CGAL::AABB_face_graph_triangle_primitive Primitive; - typedef CGAL::AABB_traits_3 Traits; - typedef CGAL::AABB_tree AABBTree; + }; - AABBTree tree1(faces(tm1).begin(), faces(tm1).end(), tm1, vpm1); - std::vector points_of_interest2; - get_one_point_per_cc(tm2, vpm2, points_of_interest2); + collect_segments(polylines1, segments1, segment_indices1); + collect_segments(polylines2, segments2, segment_indices2); - return is_mesh2_in_mesh1_impl(tree1, points_of_interest2, gt); -} + Segment_tree tree1(segments1.begin(), segments1.end()); + Segment_tree tree2(segments2.begin(), segments2.end()); + auto output = boost::make_function_output_iterator( + [&](const std::pair& ids) + { + const std::size_t index1 = std::size_t(ids.first - segments1.cbegin()); + const std::size_t index2 = std::size_t(ids.second - segments2.cbegin()); -}// namespace internal + *out++ = std::make_pair( segment_indices1[index1], segment_indices2[index2]); + }); + AABB_trees::all_pairs_of_intersecting_primitives(tree1, tree2, output, parameters::concurrency_tag(Concurrency_tag())); + return out; +} +#endif /** * \ingroup PMP_intersection_grp @@ -1140,14 +254,26 @@ bool is_mesh2_in_mesh1(const TriangleMesh& tm1, * \tparam PolylineRange a `RandomAccessRange` of `RandomAccessRange` of points. * The point type must be from a 3D point from a \cgal Kernel. * \cgalDescribePolylineType + * \tparam NamedParameters a sequence of \ref bgl_namedparameters "Named Parameters" for the algorithm * * @param polylines1 the first range of polylines to check for intersections. * @param polylines2 the second range of polylines to check for intersections. + * @param np an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below + * + * \cgalNamedParamsBegin + * \cgalParamNBegin{concurrency_tag} + * \cgalParamDescription{a tag indicating if the task should be done using one or several threads.} + * \cgalParamType{Either `CGAL::Sequential_tag`, or `CGAL::Parallel_tag`, or `CGAL::Parallel_if_available_tag`} + * \cgalParamDefault{`CGAL::Sequential_tag`} + * \cgalParamExtra{`np1` only} + * \cgalParamNEnd + * \cgalNamedParamsEnd * */ -template +template bool do_intersect(const PolylineRange& polylines1, - const PolylineRange& polylines2 + const PolylineRange& polylines2, + const NamedParameters& np = parameters::default_values() #ifndef DOXYGEN_RUNNING , const std::enable_if_t< boost::has_range_iterator< @@ -1160,18 +286,63 @@ bool do_intersect(const PolylineRange& polylines1, #endif ) { - typedef typename boost::range_value::type Polyline; - typedef typename boost::range_value::type Point; - typedef typename CGAL::Kernel_traits::Kernel K; - try + CGAL_USE(np); + using Concurrency_tag = typename internal_np::Lookup_named_param_def < + internal_np::concurrency_tag_t, + NamedParameters, + Sequential_tag + > ::type; + + using Polyline = typename boost::range_value::type; + using Point = typename boost::range_value::type; + using GT = typename CGAL::Kernel_traits::Kernel; + using Segment_3 = typename GT::Segment_3; + + using Segment_primitive = CGAL::AABB_segment_primitive_3::const_iterator>; + using Segment_traits = CGAL::AABB_traits_3; + using Segment_tree = CGAL::AABB_tree; + + Bbox_3 b1; + for(const auto& polyline : polylines1) + b1 += bbox_3(polyline.begin(), polyline.end()); + Bbox_3 b2; + for(const auto& polyline : polylines2) + b2 += bbox_3(polyline.begin(), polyline.end()); + + if(!CGAL::do_overlap(b1, b2)) + return false; + + Bbox_3 bb((std::max)(b1.xmin(),b2.xmin()), (std::max)(b1.ymin(),b2.ymin()), (std::max)(b1.zmin(),b2.zmin()), + (std::min)(b1.xmax(),b2.xmax()), (std::min)(b1.ymax(),b2.ymax()), (std::min)(b1.zmax(),b2.zmax())); + + // We store all polylines in one filtered range + std::vector segments1; + for (const auto& polyline : polylines1) { - typedef boost::function_output_iterator OutputIterator; - internal::compute_polylines_polylines_intersection(polylines1, polylines2, OutputIterator(), K()); + if(polyline.size() < 2) continue; + + auto pit = std::begin(polyline); + auto prev = pit++; + for(; pit != std::end(polyline); ++pit, ++prev) + if (do_overlap(bb, prev->bbox()+pit->bbox())) + segments1.emplace_back(*prev, *pit); } - catch( internal::Throw_at_first_output::Throw_at_first_output_exception& ) - { return true; } + std::vector segments2; + for (const auto& polyline : polylines2) + { + if(polyline.size() < 2) continue; - return false; + auto pit = std::begin(polyline); + auto prev = pit++; + for(; pit != std::end(polyline); ++pit, ++prev) + if (do_overlap(bb, prev->bbox()+pit->bbox())) + segments2.emplace_back(*prev, *pit); + } + + Segment_tree tree1(segments1.begin(), segments1.end()); + Segment_tree tree2(segments2.begin(), segments2.end()); + + return AABB_trees::do_intersect(tree1, tree2, parameters::concurrency_tag(Concurrency_tag())); } /** @@ -1185,14 +356,26 @@ bool do_intersect(const PolylineRange& polylines1, * \tparam Polyline a `RandomAccessRange` of points. * The point type must be from a 3D point type from \cgal Kernel. * \cgalDescribePolylineType + * \tparam NamedParameters a sequence of \ref bgl_namedparameters "Named Parameters" for the algorithm * * @param polyline1 the first polyline to check for intersections. * @param polyline2 the second polyline to check for intersections. + * @param np an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below + * + * \cgalNamedParamsBegin + * \cgalParamNBegin{concurrency_tag} + * \cgalParamDescription{a tag indicating if the task should be done using one or several threads.} + * \cgalParamType{Either `CGAL::Sequential_tag`, or `CGAL::Parallel_tag`, or `CGAL::Parallel_if_available_tag`} + * \cgalParamDefault{`CGAL::Sequential_tag`} + * \cgalParamExtra{`np1` only} + * \cgalParamNEnd + * \cgalNamedParamsEnd * */ -template +template bool do_intersect(const Polyline& polyline1, - const Polyline& polyline2 + const Polyline& polyline2, + const NamedParameters& np = parameters::default_values() #ifndef DOXYGEN_RUNNING , const std::enable_if_t< boost::has_range_const_iterator::value @@ -1209,17 +392,10 @@ bool do_intersect(const Polyline& polyline1, #endif ) { - typedef typename boost::range_value::type Point; - typedef typename CGAL::Kernel_traits::Kernel K; - try - { - typedef boost::function_output_iterator OutputIterator; - internal::compute_polyline_polyline_intersection(polyline1, polyline2, OutputIterator(), K()); - } - catch( internal::Throw_at_first_output::Throw_at_first_output_exception& ) - { return true; } + auto polylines1 = make_range(&polyline1,&polyline1+1); + auto polylines2 = make_range(&polyline2,&polyline2+1); - return false; + return do_intersect(polylines1, polylines2, np); } /** @@ -1247,6 +423,12 @@ bool do_intersect(const Polyline& polyline1, * @param np2 an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below * * \cgalNamedParamsBegin + * \cgalParamNBegin{concurrency_tag} + * \cgalParamDescription{a tag indicating if the task should be done using one or several threads.} + * \cgalParamType{Either `CGAL::Sequential_tag`, or `CGAL::Parallel_tag`, or `CGAL::Parallel_if_available_tag`} + * \cgalParamDefault{`CGAL::Sequential_tag`} + * \cgalParamExtra{`np1` only} + * \cgalParamNEnd * \cgalParamNBegin{vertex_point_map} * \cgalParamDescription{a property map associating points to the vertices of `tm1` (`tm2`)} * \cgalParamType{a class model of `ReadablePropertyMap` with `boost::graph_traits::%vertex_descriptor` @@ -1256,7 +438,6 @@ bool do_intersect(const Polyline& polyline1, * should be available for the vertices of `tm1` (`tm2`)} * \cgalParamExtra{Both vertex point maps must have the same value type} * \cgalParamNEnd - * * \cgalParamNBegin{geom_traits} * \cgalParamDescription{an instance of a geometric traits class} * \cgalParamType{a class model of `PMPSelfIntersectionTraits`} @@ -1264,7 +445,6 @@ bool do_intersect(const Polyline& polyline1, * \cgalParamExtra{The geometric traits class must be compatible with the vertex point type.} * \cgalParamExtra{np1 only} * \cgalParamNEnd - * * \cgalParamNBegin{do_overlap_test_of_bounded_sides} * \cgalParamDescription{If `true`, also tests the overlap of the bounded sides of `tm1` and `tm2`. * If `false`, only the intersection of surface triangles is tested.} @@ -1289,24 +469,77 @@ bool do_intersect(const TriangleMesh& tm1, #endif ) { + CGAL_precondition(CGAL::is_triangle_mesh(tm1)); + CGAL_precondition(CGAL::is_triangle_mesh(tm2)); + using parameters::choose_parameter; using parameters::get_parameter; bool test_overlap = choose_parameter(get_parameter(np1, internal_np::overlap_test),false) || choose_parameter(get_parameter(np2, internal_np::overlap_test),false); - - CGAL_precondition(CGAL::is_triangle_mesh(tm1)); - CGAL_precondition(CGAL::is_triangle_mesh(tm2)); CGAL_precondition(!test_overlap || CGAL::is_closed(tm1)); CGAL_precondition(!test_overlap || CGAL::is_closed(tm2)); - try - { - typedef boost::function_output_iterator OutputIterator; - internal::compute_face_face_intersection(tm1,tm2, OutputIterator(), np1, np2); - } - catch( internal::Throw_at_first_output::Throw_at_first_output_exception& ) - { return true; } + using Concurrency_tag = typename internal_np::Lookup_named_param_def < + internal_np::concurrency_tag_t, + CGAL_NP_CLASS_1, + Sequential_tag + > ::type; + + using GT = typename GetGeomTraits::type; + + using VPM1 = typename GetVertexPointMap::const_type; + using VPM2 = typename GetVertexPointMap::const_type; + + using face_descriptor = typename boost::graph_traits::face_descriptor; + + using AABB_tree_helper_1 = internal::AABB_tree_graph_helper; + using AABB_tree_helper_2 = internal::AABB_tree_graph_helper; + using Tree_1 = typename AABB_tree_helper_1::Tree; + using Tree_2 = typename AABB_tree_helper_2::Tree; + AABB_tree_helper_1 helper_1; + AABB_tree_helper_2 helper_2; + + // compute intersections filtered out by boxes + CGAL::Bbox_3 b1 = CGAL::Polygon_mesh_processing::bbox(tm1, np1), + b2 = CGAL::Polygon_mesh_processing::bbox(tm2, np2); + + if(!CGAL::do_overlap(b1, b2)) + return false; + + Bbox_3 bb((std::max)(b1.xmin(),b2.xmin()), (std::max)(b1.ymin(),b2.ymin()), (std::max)(b1.zmin(),b2.zmin()), + (std::min)(b1.xmax(),b2.xmax()), (std::min)(b1.ymax(),b2.ymax()), (std::min)(b1.zmax(),b2.zmax())); + + VPM1 vpm1 = choose_parameter(get_parameter(np1, internal_np::vertex_point), + get_const_property_map(boost::vertex_point, tm1)); + VPM2 vpm2 = choose_parameter(get_parameter(np2, internal_np::vertex_point), + get_const_property_map(boost::vertex_point, tm2)); + static_assert( + (std::is_same< + typename boost::property_traits::value_type, + typename boost::property_traits::value_type + >::value) ); + +// TODO: can be done in parallel + std::vector faces_to_test1; + std::vector faces_to_test2; + + for(face_descriptor f : faces(tm1)) + if(do_overlap(Polygon_mesh_processing::face_bbox(f, tm1, parameters::vertex_point_map(vpm1)), bb)) + faces_to_test1.emplace_back(f); + for(face_descriptor f : faces(tm2) ) + if(do_overlap(Polygon_mesh_processing::face_bbox(f, tm2, parameters::vertex_point_map(vpm2)), bb)) + faces_to_test2.emplace_back(f); +//--- + + Tree_1 tree1; + Tree_2 tree2; + helper_1.template build(faces_to_test1, tree1, tm1, vpm1); + helper_2.template build(faces_to_test2, tree2, tm2, vpm2); + + bool inter = AABB_trees::do_intersect(tree1, tree2, parameters::concurrency_tag(Concurrency_tag())); + + if (inter) return true; if (test_overlap) { @@ -1325,6 +558,154 @@ bool do_intersect(const TriangleMesh& tm1, return false; } +#ifndef DOXYEGN_RUNNING // Not documented yet, used by Lab +/** + * \ingroup PMP_intersection_grp + * + * detects and reports all intersections between a face of `tm` and a segment of a polyline of `polylines`. + * + * @pre \link CGAL::is_triangle_mesh `CGAL::is_triangle_mesh(tm)` \endlink + * + * \tparam TriangleMesh a model of `FaceListGraph` + * \tparam PolylineRange a `RandomAccessRange` of `RandomAccessRange` of points. The point type of the range must be the + * same as the value type of the vertex point map. + * \cgalDescribePolylineType + * \tparam NamedParameters a sequence of \ref bgl_namedparameters + * + * @param tm the triangulated surface mesh to check for intersections + * @param polylines the range of polylines to check for intersections. + * @param out output iterator receiving pairs consisting of an intersecting face descriptor and a pair containing the + * index of the polyline and the index of the first point of the intersecting segment in that polyline + * @param np an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below + * + * \cgalNamedParamsBegin + * \cgalParamNBegin{concurrency_tag} + * \cgalParamDescription{a tag indicating if the task should be done using one or several threads.} + * \cgalParamType{Either `CGAL::Sequential_tag`, or `CGAL::Parallel_tag`, or `CGAL::Parallel_if_available_tag`} + * \cgalParamDefault{`CGAL::Sequential_tag`} + * \cgalParamExtra{`np1` only} + * \cgalParamNEnd + * \cgalParamNBegin{vertex_point_map} + * \cgalParamDescription{a property map associating points to the vertices of `tm`} + * \cgalParamType{a class model of `ReadWritePropertyMap` with `boost::graph_traits::%vertex_descriptor` as key type and `%Point_3` as value type} + * \cgalParamDefault{`boost::get(CGAL::vertex_point, tm)`} + * \cgalParamExtra{If this parameter is omitted, an internal property map for `CGAL::vertex_point_t` + * should be available for the vertices of `tm`.} + * \cgalParamNEnd + * \cgalParamNBegin{geom_traits} + * \cgalParamDescription{an instance of a geometric traits class} + * \cgalParamType{a class model of `PMPSelfIntersectionTraits`} + * \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 + * \cgalNamedParamsEnd + * + */ +template +OutputIterator intersections(const TriangleMesh& tm, + const PolylineRange& polylines, + OutputIterator out, + const NamedParameters& np = parameters::default_values() +#ifndef DOXYGEN_RUNNING + , const std::enable_if_t< + boost::has_range_iterator< + typename boost::mpl::eval_if< + boost::has_range_iterator, + boost::range_value, + std::false_type + >::type + >::value + >* = 0//end enable_if +#endif + ) +{ + if (faces(tm).size()==0 || polylines.empty()) + return out; + + using parameters::get_parameter; + using parameters::choose_parameter; + + CGAL_precondition(CGAL::is_triangle_mesh(tm)); + + using Concurrency_tag = typename internal_np::Lookup_named_param_def < + internal_np::concurrency_tag_t, + NamedParameters, + Sequential_tag + >::type; + + using GT = typename GetGeomTraits::type; + + using VPM = typename GetVertexPointMap::const_type; + using face_descriptor = typename boost::graph_traits::face_descriptor; + using Segment_3 = typename GT::Segment_3; + + using AABB_tree_helper = internal::AABB_tree_graph_helper; + using Face_tree = typename AABB_tree_helper::Tree; + + using Segment_primitive = CGAL::AABB_segment_primitive_3::const_iterator>; + using Segment_traits = CGAL::AABB_traits_3; + using Segment_tree = CGAL::AABB_tree; + + VPM vpm = choose_parameter(get_parameter(np, internal_np::vertex_point), + get_const_property_map(boost::vertex_point, tm)); + + Bbox_3 b1; + for (face_descriptor f : faces(tm)) + b1 += Polygon_mesh_processing::face_bbox(f, tm, np); + Bbox_3 b2; + for(const auto& polyline : polylines) + b2 += bbox_3(polyline.begin(), polyline.end()); + + if(!CGAL::do_overlap(b1, b2)) + return out; + + Bbox_3 bb((std::max)(b1.xmin(),b2.xmin()), (std::max)(b1.ymin(),b2.ymin()), (std::max)(b1.zmin(),b2.zmin()), + (std::min)(b1.xmax(),b2.xmax()), (std::min)(b1.ymax(),b2.ymax()), (std::min)(b1.zmax(),b2.zmax())); + + // Store filtered segments and their original indices. + std::vector segments; + std::vector > segment_indices; + std::size_t polyline_index = 0; + for (const auto& polyline : polylines) + { + if(polyline.size() >= 2) + { + auto pit = std::begin(polyline); + auto prev = pit++; + for(; pit != std::end(polyline); ++pit, ++prev) + if (do_overlap(bb, prev->bbox()+pit->bbox())) + { + segments.emplace_back(*prev, *pit); + segment_indices.emplace_back(polyline_index, std::size_t(std::begin(polyline) - prev)); + } + } + ++polyline_index; + } + + std::vector faces_to_test; + for(face_descriptor f : faces(tm)) + if(do_overlap(Polygon_mesh_processing::face_bbox(f, tm, parameters::vertex_point_map(vpm)), bb)) + faces_to_test.emplace_back(f); + + AABB_tree_helper helper; + Face_tree face_tree; + + helper.template build(faces_to_test, face_tree, tm, vpm); + Segment_tree segment_tree(segments.begin(), segments.end()); + + auto output = boost::make_function_output_iterator( + [&](const auto& ids) + { + *out++ = std::make_pair(ids.first, segment_indices[std::size_t(ids.second - segments.cbegin())]); + }); + CGAL::AABB_trees::all_pairs_of_intersecting_primitives(face_tree, segment_tree, output, parameters::concurrency_tag(Concurrency_tag())); + return out; +} +#endif + /** * \ingroup PMP_intersection_grp * @@ -1346,6 +727,12 @@ bool do_intersect(const TriangleMesh& tm1, * @param np an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below * * \cgalNamedParamsBegin + * \cgalParamNBegin{concurrency_tag} + * \cgalParamDescription{a tag indicating if the task should be done using one or several threads.} + * \cgalParamType{Either `CGAL::Sequential_tag`, or `CGAL::Parallel_tag`, or `CGAL::Parallel_if_available_tag`} + * \cgalParamDefault{`CGAL::Sequential_tag`} + * \cgalParamExtra{`np1` only} + * \cgalParamNEnd * \cgalParamNBegin{vertex_point_map} * \cgalParamDescription{a property map associating points to the vertices of `tm`} * \cgalParamType{a class model of `ReadWritePropertyMap` with `boost::graph_traits::%vertex_descriptor` as key type and `%Point_3` as value type} @@ -1353,7 +740,6 @@ bool do_intersect(const TriangleMesh& tm1, * \cgalParamExtra{If this parameter is omitted, an internal property map for `CGAL::vertex_point_t` * should be available for the vertices of `tm`.} * \cgalParamNEnd - * * \cgalParamNBegin{geom_traits} * \cgalParamDescription{an instance of a geometric traits class} * \cgalParamType{a class model of `PMPSelfIntersectionTraits`} @@ -1382,16 +768,74 @@ bool do_intersect(const TriangleMesh& tm, #endif ) { + if (faces(tm).size()==0 || polylines.empty()) + return false; + + using parameters::get_parameter; + using parameters::choose_parameter; + CGAL_precondition(CGAL::is_triangle_mesh(tm)); - try + + using Concurrency_tag = typename internal_np::Lookup_named_param_def < + internal_np::concurrency_tag_t, + NamedParameters, + Sequential_tag + >::type; + + using GT = typename GetGeomTraits::type; + + using VPM = typename GetVertexPointMap::const_type; + using face_descriptor = typename boost::graph_traits::face_descriptor; + using Segment_3 = typename GT::Segment_3; + + using AABB_tree_helper = internal::AABB_tree_graph_helper; + using Face_tree = typename AABB_tree_helper::Tree; + + using Segment_primitive = CGAL::AABB_segment_primitive_3::const_iterator>; + using Segment_traits = CGAL::AABB_traits_3; + using Segment_tree = CGAL::AABB_tree; + + VPM vpm = choose_parameter(get_parameter(np, internal_np::vertex_point), + get_const_property_map(boost::vertex_point, tm)); + + Bbox_3 b1; + for (face_descriptor f : faces(tm)) + b1 += Polygon_mesh_processing::face_bbox(f, tm, np); + Bbox_3 b2; + for(const auto& polyline : polylines) + b2 += bbox_3(polyline.begin(), polyline.end()); + + if(!CGAL::do_overlap(b1, b2)) + return false; + + Bbox_3 bb((std::max)(b1.xmin(),b2.xmin()), (std::max)(b1.ymin(),b2.ymin()), (std::max)(b1.zmin(),b2.zmin()), + (std::min)(b1.xmax(),b2.xmax()), (std::min)(b1.ymax(),b2.ymax()), (std::min)(b1.zmax(),b2.zmax())); + + // We store all polylines in one filtered range + std::vector segments; + for (const auto& polyline : polylines) { - typedef boost::function_output_iterator OutputIterator; - internal::compute_face_polylines_intersection(faces(tm), polylines, tm, OutputIterator(), np); + if(polyline.size() < 2) continue; + + auto pit = std::begin(polyline); + auto prev = pit++; + for(; pit != std::end(polyline); ++pit, ++prev) + if (do_overlap(bb, prev->bbox()+pit->bbox())) + segments.emplace_back(*prev, *pit); } - catch( internal::Throw_at_first_output::Throw_at_first_output_exception& ) - { return true; } - return false; + std::vector faces_to_test; + for(face_descriptor f : faces(tm)) + if(do_overlap(Polygon_mesh_processing::face_bbox(f, tm, parameters::vertex_point_map(vpm)), bb)) + faces_to_test.emplace_back(f); + + AABB_tree_helper helper; + Face_tree face_tree; + + helper.template build(faces_to_test, face_tree, tm, vpm); + Segment_tree segment_tree(segments.begin(), segments.end()); + + return CGAL::AABB_trees::do_intersect(face_tree, segment_tree, parameters::concurrency_tag(Concurrency_tag())); } /** @@ -1414,6 +858,12 @@ bool do_intersect(const TriangleMesh& tm, * @param np an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below * * \cgalNamedParamsBegin + * \cgalParamNBegin{concurrency_tag} + * \cgalParamDescription{a tag indicating if the task should be done using one or several threads.} + * \cgalParamType{Either `CGAL::Sequential_tag`, or `CGAL::Parallel_tag`, or `CGAL::Parallel_if_available_tag`} + * \cgalParamDefault{`CGAL::Sequential_tag`} + * \cgalParamExtra{`np1` only} + * \cgalParamNEnd * \cgalParamNBegin{vertex_point_map} * \cgalParamDescription{a property map associating points to the vertices of `tm`} * \cgalParamType{a class model of `ReadWritePropertyMap` with `boost::graph_traits::%vertex_descriptor` as key type and `%Point_3` as value type} @@ -1421,7 +871,6 @@ bool do_intersect(const TriangleMesh& tm, * \cgalParamExtra{If this parameter is omitted, an internal property map for `CGAL::vertex_point_t` * should be available for the vertices of `tm`.} * \cgalParamNEnd - * * \cgalParamNBegin{geom_traits} * \cgalParamDescription{an instance of a geometric traits class} * \cgalParamType{a class model of `PMPSelfIntersectionTraits`} @@ -1452,133 +901,10 @@ bool do_intersect(const TriangleMesh& tm, #endif ) { - CGAL_precondition(CGAL::is_triangle_mesh(tm)); - try - { - typedef boost::function_output_iterator OutputIterator; - internal::compute_face_polyline_intersection(tm,polyline, OutputIterator(), np); - } - catch( internal::Throw_at_first_output::Throw_at_first_output_exception& ) - { return true; } - - return false; + auto polylines = make_range(&polyline,&polyline+1); + return do_intersect(tm, polylines, np); } -namespace internal { - -template -struct Mesh_callback -{ - typedef typename boost::range_value::type TriangleMesh; - typedef typename boost::range_value::type NamedParameters; - typedef typename GetVertexPointMap::const_type VPM; - typedef CGAL::AABB_face_graph_triangle_primitive Primitive; - typedef CGAL::AABB_traits_3 Traits; - typedef CGAL::AABB_tree AABBTree; - typedef typename boost::graph_traits::face_descriptor face_descriptor; - - // fill them in the operator and test for inclusion with - // Side_of_triangle_mesh. - const TriangleMeshRange& meshes; - OutputIterator m_iterator; - const bool report_overlap; - const NamedParametersRange& nps; - std::vector trees; - GT gt; - - std::vector > > points_of_interest; - - Mesh_callback(const TriangleMeshRange& meshes, - OutputIterator iterator, - const bool report_overlap, - const GT& gt, - const NamedParametersRange& nps) - : meshes(meshes), m_iterator(iterator), - report_overlap(report_overlap), nps(nps), gt(gt) - { - std::size_t size = std::distance(meshes.begin(), meshes.end()); - trees = std::vector(size, nullptr); - points_of_interest.resize(size); - } - - ~Mesh_callback() - { - for(AABBTree* tree : trees) - { - delete tree; - } - } - - template - bool is_mesh2_in_mesh1(const TriangleMesh& tm1, - const TriangleMesh& tm2, - const std::size_t mesh_id_1, - const std::size_t mesh_id_2, - const VPM& vpm1, - const VPM& vpm2) - { - //test if tm2 is included in tm1 - - //get AABB_tree for tm1 - if(!trees[mesh_id_1]) - { - trees[mesh_id_1] = new AABBTree(faces(tm1).begin(), - faces(tm1).end(), - tm1, vpm1); - } - //get a face-index map for tm2 - if(points_of_interest[mesh_id_2].size() == 0) - get_one_point_per_cc(tm2, vpm2, points_of_interest[mesh_id_2]); - - //test if tm2 is included in tm1: - return is_mesh2_in_mesh1_impl( - *trees[mesh_id_1], points_of_interest[mesh_id_2], gt); - } - - template - void operator()(const Mesh_box* b1, const Mesh_box* b2) - { - using parameters::choose_parameter; - using parameters::get_parameter; - - std::size_t mesh_id_1 = std::distance(meshes.begin(), b1->info()); - std::size_t mesh_id_2 = std::distance(meshes.begin(), b2->info()); - - - VPM vpm1 = choose_parameter(get_parameter(*(nps.begin() + mesh_id_1), internal_np::vertex_point), - get_const_property_map(CGAL::vertex_point, *b1->info())); - - VPM vpm2 = choose_parameter(get_parameter(*(nps.begin() + mesh_id_2), internal_np::vertex_point), - get_const_property_map(CGAL::vertex_point, *b2->info())); - - //surfacic test - if(Polygon_mesh_processing::do_intersect(*b1->info(), - *b2->info(), - parameters::vertex_point_map(vpm1) - .geom_traits(gt), - parameters::vertex_point_map(vpm2) - .geom_traits(gt))) - { - *m_iterator++ = std::make_pair(mesh_id_1, mesh_id_2); - } - //volumic test - else if(report_overlap) - { - if(!CGAL::do_overlap(b1->bbox(), b2->bbox())) - return; - if(is_mesh2_in_mesh1(*b1->info(), *b2->info(), mesh_id_1, mesh_id_2, vpm1, vpm2)) - *m_iterator++ = std::make_pair(mesh_id_1, mesh_id_2); - else if(is_mesh2_in_mesh1(*b2->info(), *b1->info(), mesh_id_2, mesh_id_1, vpm2, vpm1)) - *m_iterator++ = std::make_pair(mesh_id_2, mesh_id_1); - } - } -}; -}//end internal - /*! * \ingroup PMP_intersection_grp * @@ -1605,7 +931,12 @@ struct Mesh_callback * \cgalParamDefault{a \cgal Kernel deduced from the point type, using `CGAL::Kernel_traits`, * where `Point` is the value type of the vertex point map of the meshes} * \cgalParamNEnd - * + * \cgalParamNBegin{concurrency_tag} + * \cgalParamDescription{a tag indicating if the task should be done using one or several threads.} + * \cgalParamType{Either `CGAL::Sequential_tag`, or `CGAL::Parallel_tag`, or `CGAL::Parallel_if_available_tag`} + * \cgalParamDefault{`CGAL::Sequential_tag`} + * \cgalParamExtra{`np1` only} + * \cgalParamNEnd * \cgalParamNBegin{do_overlap_test_of_bounded_sides} * \cgalParamDescription{If `true`, reports also overlap of bounded sides of meshes. * If `false`, only the intersection of surface triangles are tested.} @@ -1634,42 +965,98 @@ template -OutputIterator intersecting_meshes(const TriangleMeshRange& range, - OutputIterator out, - const NamedParameters& np, - const NamedParametersRange& nps) +OutputIterator +intersecting_meshes(const TriangleMeshRange& range, + OutputIterator out, + const NamedParameters& np, + const NamedParametersRange& nps) { using parameters::choose_parameter; using parameters::get_parameter; - typedef typename TriangleMeshRange::const_iterator TriangleMeshIterator; + using Concurrency_tag = typename internal_np::Lookup_named_param_def < + internal_np::concurrency_tag_t, + NamedParameters, + Sequential_tag + > ::type; + + bool report_overlap = choose_parameter(get_parameter(np, internal_np::overlap_test),false); + + using TriangleMeshIterator = typename TriangleMeshRange::const_iterator; + using TriangleMesh = typename std::iterator_traits::value_type; + using GT = typename GetGeomTraits::type; - bool report_overlap = choose_parameter(get_parameter(np, internal_np::overlap_test),false); + struct Indexed_bbox + { + Bbox_3 bbox; + std::size_t index; + }; - typedef CGAL::Box_intersection_d::ID_FROM_BOX_ADDRESS Box_policy; - typedef CGAL::Box_intersection_d::Box_with_info_d Mesh_box; + std::vector indexed_bboxes; + indexed_bboxes.reserve(range.size()); + for(std::size_t i = 0; i < range.size(); ++i) + indexed_bboxes.push_back({ Polygon_mesh_processing::bbox(range[i], nps[i]), i }); - std::vector boxes; - boxes.reserve(std::distance(range.begin(), range.end())); + if(indexed_bboxes.empty()) + return out; - for(TriangleMeshIterator it = range.begin(); it != range.end(); ++it) + // The primitive ID is the index of the mesh. + struct AABB_indexed_bbox_primitive { - boxes.push_back( Mesh_box(Polygon_mesh_processing::bbox(*it), it) ); - } + using Id = std::size_t; + struct Datum : public Bbox_3 + { + Datum() = default; + Datum(const Bbox_3& bbox) : Bbox_3(bbox) {} + + const Datum& bbox() const { return *this; } + }; + using Point = typename GT::Point_3; + + AABB_indexed_bbox_primitive() = default; + AABB_indexed_bbox_primitive(typename std::vector::const_iterator it) + : m_it(it) + {} + + Id id() const { return m_it->index; } + Datum datum() const { return Datum(m_it->bbox); } + Point reference_point() const { + const Bbox_3& b = m_it->bbox; + return Point(b.xmin(), b.ymin(), b.zmin()); + } + + private: + typename std::vector::const_iterator m_it; + }; + + using Primitive = AABB_indexed_bbox_primitive; + using Traits = CGAL::AABB_traits_3; + using Tree = CGAL::AABB_tree; + + Tree tree(indexed_bboxes.begin(), indexed_bboxes.end()); - std::vector boxes_ptr(boost::make_counting_iterator(&boxes[0]), - boost::make_counting_iterator(&boxes[0]+boxes.size())); +#ifdef CGAL_LINKED_WITH_TBB + std::conditional_t>, + std::vector>> candidates; +#else + std::vector> candidates; +#endif + + CGAL::AABB_trees::all_pairs_of_intersecting_primitives(tree, std::back_inserter(candidates)); - typedef typename boost::range_value::type NP_rng; - typedef typename boost::range_value::type TriangleMesh; - typedef typename GetGeomTraits::type GT; - GT gt = choose_parameter(get_parameter(np, internal_np::geom_traits)); + // TODO: we could also do that in parallel, depending on candidates.size() + // TODO: tree caching could be added + for(const auto& p : candidates) + { + const TriangleMesh &mesh1 = range[p.first]; + const TriangleMesh &mesh2 = range[p.second]; - //get all the pairs of meshes intersecting (no strict inclusion test) - std::ptrdiff_t cutoff = 2000; - internal::Mesh_callback callback(range, out, report_overlap, gt, nps); - CGAL::box_self_intersection_d(boxes_ptr.begin(), boxes_ptr.end(), callback, cutoff); - return callback.m_iterator; + if(CGAL::Polygon_mesh_processing::do_intersect(mesh1, mesh2, nps[p.first].do_overlap_test_of_bounded_sides(report_overlap), + nps[p.second].do_overlap_test_of_bounded_sides(report_overlap))) + *out++ = p; + } + return out; } template diff --git a/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/self_intersections.h b/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/self_intersections.h index e0e625ab2c92..cb02bc224636 100644 --- a/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/self_intersections.h +++ b/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/self_intersections.h @@ -28,7 +28,6 @@ #include #include #include -#include #include #include #include @@ -51,16 +50,38 @@ #include #include +#include + +#include +#include +#include +#include + namespace CGAL { namespace Polygon_mesh_processing { namespace internal { -template +template struct Triangle_mesh_and_triangle_soup_wrapper { - typedef typename boost::graph_traits::face_descriptor face_descriptor; - typedef typename boost::graph_traits::vertex_descriptor vertex_descriptor; - typedef typename boost::graph_traits::halfedge_descriptor halfedge_descriptor; // private + using face_descriptor = typename boost::graph_traits::face_descriptor; + using vertex_descriptor = typename boost::graph_traits::vertex_descriptor; + using halfedge_descriptor = typename boost::graph_traits::halfedge_descriptor; // private + + using Tree_helper = AABB_tree_graph_helper; + using Tree = typename Tree_helper::Tree; + + template + static void build_tree(const FaceRange& faces, Tree& tree, const TM &tm, VPM vpm) + { + Tree_helper().template build(faces, tree, tm, vpm); + } + + template + static void build_tree(Tree& tree, const TM &tm, VPM vpm) + { + Tree_helper().template build(tree, tm, vpm); + } static void get_face_vertices(face_descriptor fd, std::array& vh, const TM& tm) { @@ -103,15 +124,26 @@ struct Triangle_mesh_and_triangle_soup_wrapper } }; -template -struct Triangle_mesh_and_triangle_soup_wrapper< - std::pair> +template +struct Triangle_mesh_and_triangle_soup_wrapper< std::pair, GT, VPM> { - typedef std::size_t face_descriptor; - typedef std::size_t vertex_descriptor; + using face_descriptor = std::size_t; + using vertex_descriptor = std::size_t; - typedef std::pair Soup; + using Soup = std::pair; + + using Tree_helper = AABB_tree_soup_helper; + using Tree = typename Tree_helper::Tree; + + template + static void build_tree(const FaceRange &faces, Tree& tree, const Soup& soup, VPM vpm){ + Tree_helper().template build(faces, tree, soup.first, soup.second, vpm); + } + + template + static void build_tree(Tree& tree, const Soup& soup, VPM vpm){ + Tree_helper().template build( tree, soup.first, soup.second, vpm); + } static void get_face_vertices(face_descriptor fd, std::array& vh, const Soup& soup) { @@ -186,48 +218,53 @@ struct Triangle_mesh_and_triangle_soup_wrapper< } }; -template -struct Throw_at_count_reached_functor { - - std::atomic& counter; - const unsigned int& maxval; - - Output_iterator out; - - Throw_at_count_reached_functor(std::atomic& counter, - const unsigned int& maxval, - Output_iterator out) - : counter(counter), maxval(maxval), out(out) +template +struct Throw_at_count_reached_output_iterator +{ + using Self = Throw_at_count_reached_output_iterator; + std::atomic &counter; + std::atomic &stop; + const unsigned int &maxval; + OutputIterator out; + + using iterator_category = std::output_iterator_tag; + Throw_at_count_reached_output_iterator(std::atomic &counter, + std::atomic &stop, + const unsigned int &maxval, + OutputIterator out) + : counter(counter), stop(stop), maxval(maxval), out(out) {} template - void operator()(const T& t ) + Self& operator=(const T& t) { *out++ = t; ++counter; - if(counter >= maxval) - { - throw CGAL::internal::Throw_at_output_exception(); - } + if(counter >= maxval && !stop.exchange(true, std::memory_order_relaxed)) + throw CGAL::internal::Throw_at_output_exception(); + return *this; } + + Self& operator*(){ return *this; } + Self& operator++(){ return *this; } + Self& operator++(int){ return *this; } }; // Checks for 'real' intersections, i.e. not simply a shared vertex or edge template -bool do_faces_intersect(typename Triangle_mesh_and_triangle_soup_wrapper::face_descriptor fh, - typename Triangle_mesh_and_triangle_soup_wrapper::face_descriptor fg, +bool do_faces_intersect(typename Triangle_mesh_and_triangle_soup_wrapper::face_descriptor fh, + typename Triangle_mesh_and_triangle_soup_wrapper::face_descriptor fg, const TM& tmesh, const VPM vpmap, const typename GT::Construct_segment_3 construct_segment, const typename GT::Construct_triangle_3 construct_triangle, const typename GT::Do_intersect_3 do_intersect) { - typedef Triangle_mesh_and_triangle_soup_wrapper Wrapper; - typedef typename Wrapper::vertex_descriptor vertex_descriptor; - - typedef typename GT::Segment_3 Segment; - typedef typename GT::Triangle_3 Triangle; + using Wrapper = Triangle_mesh_and_triangle_soup_wrapper; + using vertex_descriptor = typename Wrapper::vertex_descriptor; + using Segment = typename GT::Segment_3; + using Triangle = typename GT::Triangle_3; std::array hv, gv; Wrapper::get_face_vertices(fh, hv, tmesh); @@ -306,32 +343,102 @@ bool do_faces_intersect(typename Triangle_mesh_and_triangle_soup_wrapper::fa return false; } -template -struct Strict_intersect_faces // "strict" as in "not sharing a subface" +template +class Listing_self_intersecting_faces_traversal_traits { - mutable OutputIterator m_iterator; - const TM& m_tmesh; - const VPM m_vpmap; - typename GT::Construct_segment_3 m_construct_segment; - typename GT::Construct_triangle_3 m_construct_triangle; - typename GT::Do_intersect_3 m_do_intersect; - - Strict_intersect_faces(const TM& tmesh, VPM vpmap, const GT& gt, OutputIterator it) - : - m_iterator(it), - m_tmesh(tmesh), - m_vpmap(vpmap), - m_construct_segment(gt.construct_segment_3_object()), - m_construct_triangle(gt.construct_triangle_3_object()), - m_do_intersect(gt.do_intersect_3_object()) - {} + using FT = typename AABBTraits::FT; + using Point = typename AABBTraits::Point; + using Primitive = typename AABBTraits::Primitive; + using Bounding_box = typename AABBTraits::Bounding_box; + using Primitive_id = typename AABBTraits::Primitive::Id; + using Point_and_primitive_id = typename AABBTraits::Point_and_primitive_id; + using Object_and_primitive_id = typename AABBTraits::Object_and_primitive_id; + using Node = ::CGAL::AABB_node; + +public: + Listing_self_intersecting_faces_traversal_traits(OutputIterator& out_it, const GT& gt, const AABBTraits& traits, const TriangleMesh &tm, const VertexPointMap &vpm) + : m_out_it(out_it), m_gt(gt), m_traits(traits), m_tm(tm), m_vpm(vpm) {} + + constexpr bool go_further() const { return true; } + void intersection(const Primitive& query, const Primitive& primitive) + { + if(do_faces_intersect(query.id(), primitive.id(), m_tm, m_vpm, + m_gt.construct_segment_3_object(), + m_gt.construct_triangle_3_object(), + m_gt.do_intersect_3_object())) + { + *m_out_it++ = std::make_pair(query.id(), primitive.id()); + } + } + + bool do_intersect(const Primitive& query, const Node& node) const + { + return m_traits.do_intersect_object()(CGAL::internal::Primitive_helper::get_datum(query, m_traits).bbox(), node.bbox()); + } + +private: + OutputIterator& m_out_it; + const GT& m_gt; + const AABBTraits& m_traits; + const TriangleMesh& m_tm; + const VertexPointMap& m_vpm; +}; + +template +class Listing_self_intersecting_faces_one_tree_traversal_traits +{ + using Primitive = typename AABBTraits::Primitive; + using Node = ::CGAL::AABB_node; + +public: + Listing_self_intersecting_faces_one_tree_traversal_traits(const AABBTraits& traits, + const GT& gt, + OutputIterator& out_, + const TriangleMesh& tm, + const VertexPointMap& vpm) + : m_traits(traits), m_gt(gt), out(out_), m_tm(tm), m_vpm(vpm) {} + + constexpr bool go_further() const { return true; } + + template + bool prefer_A_for_next_step(const Node_A&, const Node_B&, const std::size_t&, const std::size_t&) const { + return false; + } + + void intersection(const Primitive& primitive1, const Primitive& primitive2) + { + if(do_faces_intersect(primitive1.id(), primitive2.id(), m_tm, m_vpm, + m_gt.construct_segment_3_object(), + m_gt.construct_triangle_3_object(), + m_gt.do_intersect_3_object())) + { + *out++ = std::make_pair(primitive1.id(), primitive2.id()); + } + } + + void intersection(const Primitive& primitive1, const Node& node2, std::size_t nb_primitives_2) + { + Listing_self_intersecting_faces_traversal_traits traits(out, m_gt, m_traits, m_tm, m_vpm); + node2.traversal( primitive1, traits, nb_primitives_2); + } + + void intersection(const Node& node1, std::size_t nb_primitives_1, const Primitive& primitive2) + { + Listing_self_intersecting_faces_traversal_traits traits(out, m_gt, m_traits, m_tm, m_vpm); + node1.traversal( primitive2, traits, nb_primitives_1); + } - void operator()(const Box* b, const Box* c) const + bool do_intersect(const Node& node1, const Node& node2) const { - if(do_faces_intersect(b->info(), c->info(), m_tmesh, m_vpmap, m_construct_segment, m_construct_triangle, m_do_intersect)) - *m_iterator++ = std::make_pair(b->info(), c->info()); + return do_overlap(node1.bbox(), node2.bbox()); } + +private: + const AABBTraits& m_traits; + const GT& m_gt; + OutputIterator& out; + const TriangleMesh& m_tm; + const VertexPointMap& m_vpm; }; template Wrapper; - - CGAL_precondition(Wrapper::is_pure_triangle(tmesh)); - using CGAL::parameters::choose_parameter; using CGAL::parameters::get_parameter; using CGAL::parameters::is_default_parameter; - typedef typename Wrapper::face_descriptor face_descriptor; - typedef typename Wrapper::vertex_descriptor vertex_descriptor; - - typedef CGAL::Box_intersection_d::ID_FROM_BOX_ADDRESS Box_policy; - typedef CGAL::Box_intersection_d::Box_with_info_d Box; - - typedef typename GetGeomTraits::type GT; + using TM = TriangleMesh; + using GT = typename GetGeomTraits::type; GT gt = choose_parameter(get_parameter(np, internal_np::geom_traits)); - typedef GetVertexPointMap VPM_helper; - typedef typename VPM_helper::const_type VPM; + using VPM_helper = GetVertexPointMap; + using VPM = typename VPM_helper::const_type; VPM vpmap = VPM_helper::get_const_map(np, tmesh); const bool do_limit = !(is_default_parameter::value); @@ -375,16 +472,18 @@ self_intersections_impl(const FaceRange& face_range, return out; } unsigned int counter = 0; - const unsigned int seed = choose_parameter(get_parameter(np, internal_np::random_seed), 0); - CGAL_USE(seed); // used in the random shuffle of the range, which is only done to balance tasks in parallel - const std::ptrdiff_t cutoff = 2000; + using Wrapper = Triangle_mesh_and_triangle_soup_wrapper; + using face_descriptor = typename Wrapper::face_descriptor; + using vertex_descriptor = typename Wrapper::vertex_descriptor; - // make one box per face - std::vector boxes; - boxes.reserve(std::distance(std::begin(face_range), std::end(face_range))); + using AABB_tree = typename Wrapper::Tree; + + CGAL_precondition(Wrapper::is_pure_triangle(tmesh)); // This loop is very cheap, so there is hardly anything to gain from parallelizing it + std::vector faces_not_degenerated; + faces_not_degenerated.reserve(face_range.size()); for(face_descriptor f : face_range) { std::array vh; @@ -397,8 +496,7 @@ self_intersections_impl(const FaceRange& face_range, // tiny fixme: if f is degenerate, we might still have a real intersection between f // and another face f', but right now we are not creating a box for f and thus not returning those - if(collinear(p, q, r)) - { + if(collinear(p, q, r)){ if(throw_on_SI) throw CGAL::internal::Throw_at_output_exception(); else @@ -406,31 +504,30 @@ self_intersections_impl(const FaceRange& face_range, *out++= std::make_pair(f, f); ++counter; if(do_limit && counter == maximum_number) - { return out; - } } - } - else - { - boxes.push_back(Box(p.bbox() + q.bbox() + r.bbox(), f)); + } else { + faces_not_degenerated.push_back(f); } } - // generate box pointers - std::vector box_ptr; - box_ptr.reserve(boxes.size()); - - for(Box& b : boxes) - box_ptr.push_back(&b); + // If no faces to test, no intersection + if(faces_not_degenerated.empty()) + return out; // In case we are throwing, like in `does_self_intersect()`, we keep the geometric test to throw ASAP. // This is obviously not optimal if there are no or few self-intersections: it would be a greater speed-up // to do the same as for `self_intersections()`. However, doing like `self_intersections()` would // be a major slow-down over sequential code if there are a lot of self-intersections... - typedef boost::function_output_iterator Throwing_output_iterator; - typedef internal::Strict_intersect_faces Throwing_filter; - Throwing_filter throwing_filter(tmesh, vpmap, gt, Throwing_output_iterator()); +#if !defined(CGAL_LINKED_WITH_TBB) + using Throwing_output_iterator = boost::function_output_iterator; +#else + using Throwing_output_iterator = boost::function_output_iterator; +#endif + Throwing_output_iterator throwing_filter; + + AABB_tree tree; + Wrapper::template build_tree(faces_not_degenerated, tree, tmesh, vpmap); #if !defined(CGAL_LINKED_WITH_TBB) static_assert (!(std::is_convertible::value), @@ -438,65 +535,60 @@ self_intersections_impl(const FaceRange& face_range, #else if(std::is_convertible::value) { - // We are going to split the range into a number of smaller ranges. To handle - // smaller trees of roughly the same size, we first apply a random shuffle to the range - CGAL::Random rng(seed); - CGAL::cpp98::random_shuffle(box_ptr.begin(), box_ptr.end(), rng); - // Write in a concurrent vector all pairs that intersect - typedef tbb::concurrent_vector > Face_pairs; - typedef std::back_insert_iterator Face_pairs_back_inserter; - typedef internal::Strict_intersect_faces Intersecting_faces_filter; + using Face_pairs = tbb::concurrent_vector >; + using Face_pairs_inserter = std::back_insert_iterator; //for maximum_number - typedef internal::Throw_at_count_reached_functor Throw_functor; - typedef boost::function_output_iterator Throwing_after_count_output_iterator; - typedef internal::Strict_intersect_faces Filtered_intersecting_faces_filter; + using Throw_iterator = internal::Throw_at_count_reached_output_iterator; Face_pairs face_pairs; if(throw_on_SI) - CGAL::box_self_intersection_d(box_ptr.begin(), box_ptr.end(), throwing_filter, cutoff); + { + Listing_self_intersecting_faces_one_tree_traversal_traits traversal_traits(tree.traits(), gt, throwing_filter, tmesh, vpmap); + CGAL::internal::AABB_tree::one_tree_traversal(tree, traversal_traits); + } else if(do_limit) { try { std::atomic atomic_counter(counter); - Throw_functor throwing_count_functor(atomic_counter, maximum_number, std::back_inserter(face_pairs)); - Throwing_after_count_output_iterator count_filter(throwing_count_functor); - Filtered_intersecting_faces_filter limited_callback(tmesh, vpmap, gt, count_filter); - CGAL::box_self_intersection_d(box_ptr.begin(), box_ptr.end(), limited_callback, cutoff); + std::atomic atomic_flag(false); + Throw_iterator count_filter(atomic_counter, atomic_flag, maximum_number, std::back_inserter(face_pairs)); + Listing_self_intersecting_faces_one_tree_traversal_traits traversal_traits(tree.traits(), gt, count_filter, tmesh, vpmap); + CGAL::internal::AABB_tree::one_tree_traversal(tree, traversal_traits); } catch(const CGAL::internal::Throw_at_output_exception&) { // Sequentially write into the output iterator - std::copy(face_pairs.begin(), face_pairs.end(), out); + for(std::size_t i=0; i(box_ptr.begin(), box_ptr.end(), callback, cutoff); + auto l_out = std::back_inserter(face_pairs); + Listing_self_intersecting_faces_one_tree_traversal_traits traversal_traits(tree.traits(), gt, l_out, tmesh, vpmap); + CGAL::internal::AABB_tree::one_tree_traversal(tree, traversal_traits); } // Sequentially write into the output iterator for(std::size_t i=0; i Intersecting_faces_filter; - Intersecting_faces_filter intersect_faces(tmesh, vpmap, gt, out); - if(throw_on_SI) - CGAL::box_self_intersection_d(box_ptr.begin(), box_ptr.end(), throwing_filter, cutoff); + { + Listing_self_intersecting_faces_one_tree_traversal_traits traversal_traits(tree.traits(), gt, throwing_filter, tmesh, vpmap); + CGAL::internal::AABB_tree::one_tree_traversal(tree, traversal_traits); + } else if(do_limit) { - typedef std::function&) > Count_and_throw_filter; + using Count_and_throw_filter = std::function&) >; std::size_t nbi=0; Count_and_throw_filter max_inter_counter = [&nbi, maximum_number, &out](const std::pair& f_pair) { @@ -504,12 +596,12 @@ self_intersections_impl(const FaceRange& face_range, if (++nbi == maximum_number) throw CGAL::internal::Throw_at_output_exception(); }; - typedef internal::Strict_intersect_faces > Intersecting_faces_limited_filter; - Intersecting_faces_limited_filter limited_intersect_faces(tmesh, vpmap, gt, - boost::make_function_output_iterator(max_inter_counter)); + try { - CGAL::box_self_intersection_d(box_ptr.begin(), box_ptr.end(), limited_intersect_faces, cutoff); + auto l_out = boost::make_function_output_iterator(max_inter_counter); + Listing_self_intersecting_faces_one_tree_traversal_traits traversal_traits(tree.traits(), gt, l_out, tmesh, vpmap); + CGAL::internal::AABB_tree::one_tree_traversal(tree, traversal_traits); } catch (const CGAL::internal::Throw_at_output_exception&) { @@ -517,9 +609,11 @@ self_intersections_impl(const FaceRange& face_range, } } else - CGAL::box_self_intersection_d(box_ptr.begin(), box_ptr.end(), intersect_faces, cutoff); - - return intersect_faces.m_iterator; + { + Listing_self_intersecting_faces_one_tree_traversal_traits traversal_traits(tree.traits(), gt, out, tmesh, vpmap); + CGAL::internal::AABB_tree::one_tree_traversal(tree, traversal_traits); + } + return out; } } // namespace internal @@ -777,33 +871,6 @@ bool does_self_intersect(const TriangleMesh& tmesh, return does_self_intersect(faces(tmesh), tmesh, np); } - -#ifndef DOXYGEN_RUNNING -template -struct Property_map_for_soup -{ - typedef std::size_t key_type; - typedef typename boost::property_traits::value_type value_type; - //typedef typename boost::property_traits::category category; - typedef boost::readable_property_map_tag category; - typedef typename boost::property_traits::reference reference; - - const PointRange& points; - VPM vpm; - - Property_map_for_soup(const PointRange& points, VPM vpm) - : points(points) - , vpm(vpm) - {} - - inline friend - reference get(const Property_map_for_soup& map, key_type k) - { - return get(map.vpm, map.points[k]); - } -}; -#endif - /** * \ingroup PMP_intersection_grp * @@ -877,10 +944,10 @@ triangle_soup_self_intersections(const PointRange& points, using parameters::get_parameter; using parameters::is_default_parameter; - typedef typename CGAL::GetPointMap::const_type Point_map_base; + using Point_map_base = typename CGAL::GetPointMap::const_type; Point_map_base pm_base = choose_parameter(get_parameter(np, internal_np::point_map)); - typedef Property_map_for_soup Point_map; - typedef typename GetPolygonSoupGeomTraits::type GT; + using Point_map = internal::Property_map_for_soup; + using GT = typename GetPolygonSoupGeomTraits::type; GT gt = choose_parameter(get_parameter(np, internal_np::geom_traits)); const bool do_limit = !(is_default_parameter::value); @@ -960,10 +1027,10 @@ bool does_triangle_soup_self_intersect(const PointRange& points, using parameters::get_parameter; CGAL::Emptyset_iterator unused_out; - typedef typename CGAL::GetPointMap::const_type Point_map_base; + using Point_map_base = typename CGAL::GetPointMap::const_type; Point_map_base pm_base = choose_parameter(get_parameter(np, internal_np::point_map)); - typedef Property_map_for_soup Point_map; - typedef typename GetPolygonSoupGeomTraits::type GT; + using Point_map = internal::Property_map_for_soup; + using GT = typename GetPolygonSoupGeomTraits::type; GT gt = choose_parameter(get_parameter(np, internal_np::geom_traits)); internal::self_intersections_impl(boost::irange(0, triangles.size()), diff --git a/Polygon_mesh_processing/include/CGAL/Side_of_triangle_mesh.h b/Polygon_mesh_processing/include/CGAL/Side_of_triangle_mesh.h index b9c444c43205..80db1d6d8785 100644 --- a/Polygon_mesh_processing/include/CGAL/Side_of_triangle_mesh.h +++ b/Polygon_mesh_processing/include/CGAL/Side_of_triangle_mesh.h @@ -264,7 +264,7 @@ class Side_of_triangle_mesh */ Bounded_side operator()(const Point& point) const { - CGAL_assertion(tm_ptr == nullptr || CGAL::is_closed(*tm_ptr)); + CGAL_expensive_assertion(tm_ptr == nullptr || CGAL::is_closed(*tm_ptr)); if(point.x() < box.xmin() || point.x() > box.xmax() diff --git a/Polygon_mesh_processing/test/Polygon_mesh_processing/CMakeLists.txt b/Polygon_mesh_processing/test/Polygon_mesh_processing/CMakeLists.txt index cc2549482590..8067726fa069 100644 --- a/Polygon_mesh_processing/test/Polygon_mesh_processing/CMakeLists.txt +++ b/Polygon_mesh_processing/test/Polygon_mesh_processing/CMakeLists.txt @@ -57,6 +57,7 @@ if(TARGET CGAL::TBB_support) target_link_libraries(test_hausdorff_bounded_error_distance PRIVATE CGAL::TBB_support) target_link_libraries(test_pmp_distance PRIVATE CGAL::TBB_support) target_link_libraries(self_intersection_surface_mesh_test PRIVATE CGAL::TBB_support) + target_link_libraries(pmp_do_intersect_test PRIVATE CGAL::TBB_support) else() message(STATUS "NOTICE: Intel TBB was not found. Tests will use sequential code.") endif() diff --git a/Polygon_mesh_processing/test/Polygon_mesh_processing/pmp_do_intersect_test.cpp b/Polygon_mesh_processing/test/Polygon_mesh_processing/pmp_do_intersect_test.cpp index 31391bdaa1ba..1a9bd7e25c6b 100644 --- a/Polygon_mesh_processing/test/Polygon_mesh_processing/pmp_do_intersect_test.cpp +++ b/Polygon_mesh_processing/test/Polygon_mesh_processing/pmp_do_intersect_test.cpp @@ -5,7 +5,7 @@ #include #include -#include +#include #include #include @@ -66,7 +66,6 @@ test_faces_intersections(const std::filesystem::path& filename1, const bool expected) { typedef CGAL::Surface_mesh Mesh; - typedef typename boost::graph_traits::face_descriptor face_descriptor; std::ifstream input1(filename1); std::ifstream input2(filename2); @@ -83,30 +82,16 @@ test_faces_intersections(const std::filesystem::path& filename1, std::cout << "Reading files: " << filename1 <<", "<< filename2 << std::endl; - CGAL::Timer timer; + CGAL::Real_timer timer; timer.start(); - - std::vector > intersected_tris; - CGAL::Polygon_mesh_processing::internal::compute_face_face_intersection( - m1, m2, - std::back_inserter(intersected_tris), - CGAL::parameters::default_values(), - CGAL::parameters::default_values()); - - bool intersecting_1 = !intersected_tris.empty(); - - std::cout << "intersections test took " << timer.time() << " sec." << std::endl; - std::cout << intersected_tris.size() << " pairs of triangles are intersecting." << std::endl; - - timer.reset(); - bool intersecting_2 = CGAL::Polygon_mesh_processing::do_intersect(m1, m2); + bool intersecting = CGAL::Polygon_mesh_processing::do_intersect(m1, m2); + timer.stop(); std::cout << "does_intersect test took " << timer.time() << " sec." << std::endl; - std::cout << (intersecting_2 ? "There are intersections." : - "There are no intersections.") << std::endl; + std::cout << (intersecting ? "There are intersections." : + "There are no intersections.") << std::endl; - assert(intersecting_1 == intersecting_2); - assert(intersecting_1 == expected); + assert(intersecting == expected); std::cout << filename1 << "and " < > intersected_tris; - CGAL::Polygon_mesh_processing::internal::compute_face_polyline_intersection( - m, points, - std::back_inserter(intersected_tris), - CGAL::parameters::default_values()); - - bool intersecting_1 = !intersected_tris.empty(); - - std::cout << "intersections test took " << timer.time() << " sec." << std::endl; - std::cout << intersected_tris.size() << " intersections." << std::endl; - - timer.reset(); - bool intersecting_2 = CGAL::Polygon_mesh_processing::do_intersect(m,points); + bool intersecting = CGAL::Polygon_mesh_processing::do_intersect(m,points); + timer.stop(); std::cout << "does_intersect test took " << timer.time() << " sec." << std::endl; - std::cout << (intersecting_2 ? "There are intersections." : - "There are no intersections.") << std::endl; + std::cout << (intersecting ? "There are intersections." : + "There are no intersections.") << std::endl; - assert(intersecting_1 == intersecting_2); - assert(intersecting_1 == expected); + assert(intersecting == expected); std::cout << filename1 << "and " < > > intersected_tris; - - CGAL::Polygon_mesh_processing::internal::compute_face_polylines_intersection( - faces(m), - points, - m, - std::back_inserter(intersected_tris), - CGAL::parameters::default_values()); - - bool intersecting_1 = !intersected_tris.empty(); - - std::cout << "intersections test took " << timer.time() << " sec." << std::endl; - std::cout << intersected_tris.size() << " intersections." << std::endl; - - timer.reset(); - bool intersecting_2 = CGAL::Polygon_mesh_processing::do_intersect(m,points); + bool intersecting = CGAL::Polygon_mesh_processing::do_intersect(m,points); + timer.stop(); std::cout << "does_intersect test took " << timer.time() << " sec." << std::endl; - std::cout << (intersecting_2 ? "There are intersections." : - "There are no intersections.") << std::endl; + std::cout << (intersecting ? "There are intersections." : + "There are no intersections.") << std::endl; - assert(intersecting_1 == intersecting_2); - assert(intersecting_1 == expected); + assert(intersecting == expected); std::cout << filename1 << "and " <, - std::pair - > - > intersected_segs; - - CGAL::Polygon_mesh_processing::internal::compute_polylines_polylines_intersection( - polys1, - polys2, - std::back_inserter(intersected_segs), - K()); - - bool intersecting_1 = !intersected_segs.empty(); - - std::cout << "intersections test took " << timer.time() << " sec." << std::endl; - std::cout << intersected_segs.size() << " intersections." << std::endl; - - timer.reset(); - bool intersecting_2 = CGAL::Polygon_mesh_processing::do_intersect(polys1, polys2); + bool intersecting = CGAL::Polygon_mesh_processing::do_intersect(polys1, polys2); + timer.stop(); std::cout << "does_intersect test took " << timer.time() << " sec." << std::endl; - std::cout << (intersecting_2 ? "There are intersections." : - "There are no intersections.") << std::endl; + std::cout << (intersecting ? "There are intersections." : + "There are no intersections.") << std::endl; - assert(intersecting_1 == intersecting_2); - assert(intersecting_1 == expected); + assert(intersecting == expected); std::cout << filename1 << "and " < > intersected_polys; - CGAL::Polygon_mesh_processing::internal::compute_polyline_polyline_intersection( - points1, points2, - std::back_inserter(intersected_polys), - K()); - - bool intersecting_1 = !intersected_polys.empty(); - - std::cout << "intersections test took " << timer.time() << " sec." << std::endl; - std::cout << intersected_polys.size() << " intersections." << std::endl; - - timer.reset(); - - bool intersecting_2 = CGAL::Polygon_mesh_processing::do_intersect(points1, points2); + bool intersecting = CGAL::Polygon_mesh_processing::do_intersect(points1, points2); + timer.stop(); std::cout << "does_intersect test took " << timer.time() << " sec." << std::endl; - std::cout << (intersecting_2 ? "There are intersections." : - "There are no intersections.") << std::endl; + std::cout << (intersecting ? "There are intersections." : + "There are no intersections.") << std::endl; - assert(intersecting_1 == intersecting_2); - assert(intersecting_1 == expected); + assert(intersecting == expected); std::cout << filename1 << "and " <& filenames, std std::cout << output.size() <<" pairs."<(filename); // extra hand written tests + { + // Empty test + std::vector points; + std::vector< std::array > triangles; + assert(!PMP::does_triangle_soup_self_intersect(points, triangles)); + } + { + // Singleton + typedef EPICK::Point_3 Point_3; + std::vector points = {Point_3(0,0,0), Point_3(1,0,0), Point_3(0,1,0)}; + std::vector< std::array > triangles={{0,1,2}}; + assert(!PMP::does_triangle_soup_self_intersect(points, triangles)); + } { // shared edge with same point: no self-intersection typedef EPICK::Point_3 Point_3; diff --git a/STL_Extension/include/CGAL/exceptions.h b/STL_Extension/include/CGAL/exceptions.h index 7141ab71dcd4..8df4f1947b62 100644 --- a/STL_Extension/include/CGAL/exceptions.h +++ b/STL_Extension/include/CGAL/exceptions.h @@ -17,6 +17,8 @@ #include #include #include +#include +#include namespace CGAL { @@ -183,6 +185,19 @@ struct Throw_at_output void operator()(const T& /* t */) const { throw Throw_at_output_exception(); } }; +struct Concurrent_throw_at_output +{ + std::shared_ptr> called = std::make_shared>(false); + + template + void operator()(const T& /* t */) const + { + if(!called->exchange(true, std::memory_order_relaxed)) + throw Throw_at_output_exception(); + } +}; + + } // namespace internal } //namespace CGAL diff --git a/Surface_mesh/include/CGAL/Surface_mesh/print_surface_mesh.h b/Surface_mesh/include/CGAL/Surface_mesh/print_surface_mesh.h new file mode 100644 index 000000000000..bdc18c514792 --- /dev/null +++ b/Surface_mesh/include/CGAL/Surface_mesh/print_surface_mesh.h @@ -0,0 +1,61 @@ +// Copyright (c) 2026 GeometryFactory (France) +// All rights reserved. +// +// This file is part of CGAL (www.cgal.org). +// +// $URL$ +// $Id$ +// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial +// +// Author(s) : Leo Valque +#ifndef CGAL_DEBUG_PRINT_SURFACE_MESH_H +#define CGAL_DEBUG_PRINT_SURFACE_MESH_H + +#include + +#include +#include +#include + +#ifndef DOXYGEN_RUNNING + +namespace CGAL { + +/// Print all mesh elements and their connectivity to an output stream. +template +void print_surface_mesh(const Surface_mesh

& mesh, + std::ostream& out = std::cout) +{ + typedef Surface_mesh

Mesh; + typedef typename Mesh::Vertex_index Vertex_index; + typedef typename Mesh::Halfedge_index Halfedge_index; + typedef typename Mesh::Face_index Face_index; + + out << "Points:\n"; + for (Vertex_index v : mesh.vertices()) + out << " " << v << ": point=" << mesh.point(v) << '\n'; + + out << "Vertices:\n"; + for (Vertex_index v : mesh.vertices()) + out << " " << v << ": halfedge=" << mesh.halfedge(v) << '\n'; + + out << "Halfedges:\n"; + for (Halfedge_index h : mesh.halfedges()) + { + out << " " << h << ": target=" << mesh.target(h) + << " face=" << mesh.face(h) + << " next=" << mesh.next(h) + << " prev=" << mesh.prev(h) << '\n'; + } + + out << "Faces:\n"; + for (Face_index f : mesh.faces()) + { + out << " " << f << ": halfedge=" << mesh.halfedge(f) << '\n'; + } +} + +} // namespace CGAL +#endif + +#endif /* CGAL_DEBUG_PRINT_SURFACE_MESH_H */