1 // Copyright (C) 2007-2022 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : SMESH_MeshAlgos.hxx
23 // Created : Tue Apr 30 18:00:36 2013
24 // Author : Edward AGAPOV (eap)
26 // Initially this file held some low level algorithms extracted from SMESH_MeshEditor
27 // to make them accessible from Controls package
29 #include "SMESH_MeshAlgos.hxx"
31 #include "ObjectPool.hxx"
32 #include "SMDS_FaceOfNodes.hxx"
33 #include "SMDS_LinearEdge.hxx"
34 #include "SMDS_Mesh.hxx"
35 #include "SMDS_PolygonalFaceOfNodes.hxx"
36 #include "SMDS_VolumeTool.hxx"
37 #include "SMESH_OctreeNode.hxx"
39 #include <Utils_SALOME_Exception.hxx>
41 #include <GC_MakeSegment.hxx>
42 #include <GeomAPI_ExtremaCurveCurve.hxx>
43 #include <Geom_Line.hxx>
44 #include <IntAna_IntConicQuad.hxx>
45 #include <IntAna_Quadric.hxx>
48 #include <NCollection_DataMap.hxx>
53 #include <boost/container/flat_set.hpp>
55 //=======================================================================
57 * \brief Implementation of search for the node closest to point
59 //=======================================================================
61 struct SMESH_NodeSearcherImpl: public SMESH_NodeSearcher
63 //---------------------------------------------------------------------
67 SMESH_NodeSearcherImpl( const SMDS_Mesh* theMesh = 0,
68 SMDS_ElemIteratorPtr theElemIt = SMDS_ElemIteratorPtr() )
70 myMesh = ( SMDS_Mesh* ) theMesh;
72 TIDSortedNodeSet nodes;
74 SMDS_NodeIteratorPtr nIt = theMesh->nodesIterator();
76 nodes.insert( nodes.end(), nIt->next() );
80 while ( theElemIt->more() )
82 const SMDS_MeshElement* e = theElemIt->next();
83 nodes.insert( e->begin_nodes(), e->end_nodes() );
86 myOctreeNode = new SMESH_OctreeNode(nodes) ;
88 // get max size of a leaf box
89 SMESH_OctreeNode* tree = myOctreeNode;
90 while ( !tree->isLeaf() )
92 SMESH_OctreeNodeIteratorPtr cIt = tree->GetChildrenIterator();
96 myHalfLeafSize = tree->maxSize() / 2.;
99 //---------------------------------------------------------------------
101 * \brief Move node and update myOctreeNode accordingly
103 void MoveNode( const SMDS_MeshNode* node, const gp_Pnt& toPnt )
105 myOctreeNode->UpdateByMoveNode( node, toPnt );
106 myMesh->MoveNode( node, toPnt.X(), toPnt.Y(), toPnt.Z() );
109 //---------------------------------------------------------------------
113 const SMDS_MeshNode* FindClosestTo( const gp_Pnt& thePnt )
115 std::map<double, const SMDS_MeshNode*> dist2Nodes;
116 myOctreeNode->NodesAround( thePnt.Coord(), dist2Nodes, myHalfLeafSize );
117 if ( !dist2Nodes.empty() )
118 return dist2Nodes.begin()->second;
120 std::vector<const SMDS_MeshNode*> nodes;
121 //myOctreeNode->NodesAround( &tgtNode, &nodes, myHalfLeafSize );
123 double minSqDist = DBL_MAX;
124 if ( nodes.empty() ) // get all nodes of OctreeNode's closest to thePnt
126 // sort leafs by their distance from thePnt
127 typedef std::multimap< double, SMESH_OctreeNode* > TDistTreeMap;
128 TDistTreeMap treeMap;
129 std::list< SMESH_OctreeNode* > treeList;
130 std::list< SMESH_OctreeNode* >::iterator trIt;
131 treeList.push_back( myOctreeNode );
133 gp_XYZ pointNode( thePnt.X(), thePnt.Y(), thePnt.Z() );
134 bool pointInside = myOctreeNode->isInside( pointNode, myHalfLeafSize );
135 for ( trIt = treeList.begin(); trIt != treeList.end(); ++trIt)
137 SMESH_OctreeNode* tree = *trIt;
138 if ( !tree->isLeaf() ) // put children to the queue
140 if ( pointInside && !tree->isInside( pointNode, myHalfLeafSize )) continue;
141 SMESH_OctreeNodeIteratorPtr cIt = tree->GetChildrenIterator();
142 while ( cIt->more() )
143 treeList.push_back( cIt->next() );
145 else if ( tree->NbNodes() ) // put a tree to the treeMap
147 const Bnd_B3d& box = *tree->getBox();
148 double sqDist = thePnt.SquareDistance( 0.5 * ( box.CornerMin() + box.CornerMax() ));
149 treeMap.insert( std::make_pair( sqDist, tree ));
152 // find distance after which there is no sense to check tree's
153 double sqLimit = DBL_MAX;
154 TDistTreeMap::iterator sqDist_tree = treeMap.begin();
155 if ( treeMap.size() > 5 ) {
156 SMESH_OctreeNode* closestTree = sqDist_tree->second;
157 const Bnd_B3d& box = *closestTree->getBox();
158 double limit = sqrt( sqDist_tree->first ) + sqrt ( box.SquareExtent() );
159 sqLimit = limit * limit;
161 // get all nodes from trees
162 for ( ; sqDist_tree != treeMap.end(); ++sqDist_tree) {
163 if ( sqDist_tree->first > sqLimit )
165 SMESH_OctreeNode* tree = sqDist_tree->second;
166 tree->AllNodesAround( tree->GetNodeIterator()->next(), &nodes );
169 // find closest among nodes
171 const SMDS_MeshNode* closestNode = 0;
172 for ( size_t i = 0; i < nodes.size(); ++i )
174 double sqDist = thePnt.SquareDistance( SMESH_NodeXYZ( nodes[ i ]));
175 if ( minSqDist > sqDist ) {
176 closestNode = nodes[ i ];
183 //---------------------------------------------------------------------
185 * \brief Finds nodes located within a tolerance near a point
187 int FindNearPoint(const gp_Pnt& point,
188 const double tolerance,
189 std::vector< const SMDS_MeshNode* >& foundNodes)
191 myOctreeNode->NodesAround( point.Coord(), foundNodes, tolerance );
192 return foundNodes.size();
195 //---------------------------------------------------------------------
199 ~SMESH_NodeSearcherImpl() { delete myOctreeNode; }
201 //---------------------------------------------------------------------
203 * \brief Return the node tree
205 const SMESH_OctreeNode* getTree() const { return myOctreeNode; }
208 SMESH_OctreeNode* myOctreeNode;
210 double myHalfLeafSize; // max size of a leaf box
213 // ========================================================================
214 namespace // Utils used in SMESH_ElementSearcherImpl::FindElementsByPoint()
216 const int MaxNbElemsInLeaf = 10; // maximal number of elements in a leaf of tree
217 const int MaxLevel = 7; // maximal tree height -> nb terminal boxes: 8^7 = 2097152
218 const double NodeRadius = 1e-9; // to enlarge bnd box of element
220 //=======================================================================
222 * \brief Octal tree of bounding boxes of elements
224 //=======================================================================
226 class ElementBndBoxTree : public SMESH_Octree
230 typedef boost::container::flat_set< const SMDS_MeshElement*, TIDCompare > TElemSeq;
232 ElementBndBoxTree(const SMDS_Mesh& mesh,
233 SMDSAbs_ElementType elemType,
234 SMDS_ElemIteratorPtr theElemIt = SMDS_ElemIteratorPtr(),
235 double tolerance = NodeRadius );
236 void getElementsNearPoint( const gp_Pnt& point, TElemSeq& foundElems );
237 void getElementsNearLine ( const gp_Ax1& line, TElemSeq& foundElems );
238 void getElementsInBox ( const Bnd_B3d& box, TElemSeq& foundElems );
239 void getElementsInSphere ( const gp_XYZ& center, const double radius, TElemSeq& foundElems );
240 ElementBndBoxTree* getLeafAtPoint( const gp_XYZ& point );
244 ElementBndBoxTree() {}
245 SMESH_Octree* newChild() const { return new ElementBndBoxTree; }
246 void buildChildrenData();
247 Bnd_B3d* buildRootBox();
249 //!< Bounding box of element
250 struct ElementBox : public Bnd_B3d
252 const SMDS_MeshElement* _element;
253 void init(const SMDS_MeshElement* elem, double tolerance);
255 std::vector< ElementBox* > _elements;
257 typedef ObjectPool< ElementBox > TElementBoxPool;
259 //!< allocator of ElementBox's and SMESH_TreeLimit
260 struct LimitAndPool : public SMESH_TreeLimit
262 TElementBoxPool _elBoPool;
263 LimitAndPool():SMESH_TreeLimit( MaxLevel, /*minSize=*/0. ) {}
265 LimitAndPool* getLimitAndPool() const
267 SMESH_TreeLimit* limitAndPool = const_cast< SMESH_TreeLimit* >( myLimit );
268 return static_cast< LimitAndPool* >( limitAndPool );
272 //================================================================================
274 * \brief ElementBndBoxTree creation
276 //================================================================================
278 ElementBndBoxTree::ElementBndBoxTree(const SMDS_Mesh& mesh,
279 SMDSAbs_ElementType elemType,
280 SMDS_ElemIteratorPtr theElemIt,
282 :SMESH_Octree( new LimitAndPool() )
284 smIdType nbElems = mesh.GetMeshInfo().NbElements( elemType );
285 _elements.reserve( nbElems );
287 TElementBoxPool& elBoPool = getLimitAndPool()->_elBoPool;
289 if (SALOME::VerbosityActivated() && theElemIt && !theElemIt->more() )
290 std::cout << "WARNING: ElementBndBoxTree constructed on empty iterator!" << std::endl;
292 SMDS_ElemIteratorPtr elemIt = theElemIt ? theElemIt : mesh.elementsIterator( elemType );
293 while ( elemIt->more() )
295 ElementBox* eb = elBoPool.getNew();
296 eb->init( elemIt->next(), tolerance );
297 _elements.push_back( eb );
302 //================================================================================
304 * \brief Return the maximal box
306 //================================================================================
308 Bnd_B3d* ElementBndBoxTree::buildRootBox()
310 Bnd_B3d* box = new Bnd_B3d;
311 for ( size_t i = 0; i < _elements.size(); ++i )
312 box->Add( *_elements[i] );
316 //================================================================================
318 * \brief Redistribute element boxes among children
320 //================================================================================
322 void ElementBndBoxTree::buildChildrenData()
324 for ( size_t i = 0; i < _elements.size(); ++i )
326 for (int j = 0; j < 8; j++)
328 if ( !_elements[i]->IsOut( *myChildren[j]->getBox() ))
329 ((ElementBndBoxTree*)myChildren[j])->_elements.push_back( _elements[i]);
332 //_size = _elements.size();
333 SMESHUtils::FreeVector( _elements ); // = _elements.clear() + free memory
335 for (int j = 0; j < 8; j++)
337 ElementBndBoxTree* child = static_cast<ElementBndBoxTree*>( myChildren[j]);
338 if ((int) child->_elements.size() <= MaxNbElemsInLeaf )
339 child->myIsLeaf = true;
341 if ( child->isLeaf() && child->_elements.capacity() > child->_elements.size() )
342 SMESHUtils::CompactVector( child->_elements );
346 //================================================================================
348 * \brief Return elements which can include the point
350 //================================================================================
352 void ElementBndBoxTree::getElementsNearPoint( const gp_Pnt& point, TElemSeq& foundElems)
354 if ( getBox()->IsOut( point.XYZ() ))
359 for ( size_t i = 0; i < _elements.size(); ++i )
360 if ( !_elements[i]->IsOut( point.XYZ() ))
361 foundElems.insert( _elements[i]->_element );
365 for (int i = 0; i < 8; i++)
366 ((ElementBndBoxTree*) myChildren[i])->getElementsNearPoint( point, foundElems );
370 //================================================================================
372 * \brief Return elements which can be intersected by the line
374 //================================================================================
376 void ElementBndBoxTree::getElementsNearLine( const gp_Ax1& line, TElemSeq& foundElems )
378 if ( getBox()->IsOut( line ))
383 for ( size_t i = 0; i < _elements.size(); ++i )
384 if ( !_elements[i]->IsOut( line ) )
385 foundElems.insert( _elements[i]->_element );
389 for (int i = 0; i < 8; i++)
390 ((ElementBndBoxTree*) myChildren[i])->getElementsNearLine( line, foundElems );
394 //================================================================================
396 * \brief Return elements from leaves intersecting the sphere
398 //================================================================================
400 void ElementBndBoxTree::getElementsInSphere ( const gp_XYZ& center,
402 TElemSeq& foundElems)
404 if ( getBox()->IsOut( center, radius ))
409 for ( size_t i = 0; i < _elements.size(); ++i )
410 if ( !_elements[i]->IsOut( center, radius ))
411 foundElems.insert( _elements[i]->_element );
415 for (int i = 0; i < 8; i++)
416 ((ElementBndBoxTree*) myChildren[i])->getElementsInSphere( center, radius, foundElems );
420 //================================================================================
422 * \brief Return elements from leaves intersecting the box
424 //================================================================================
426 void ElementBndBoxTree::getElementsInBox( const Bnd_B3d& box, TElemSeq& foundElems )
428 if ( getBox()->IsOut( box ))
433 for ( size_t i = 0; i < _elements.size(); ++i )
434 if ( !_elements[i]->IsOut( box ))
435 foundElems.insert( _elements[i]->_element );
439 for (int i = 0; i < 8; i++)
440 ((ElementBndBoxTree*) myChildren[i])->getElementsInBox( box, foundElems );
444 //================================================================================
446 * \brief Return a leaf including a point
448 //================================================================================
450 ElementBndBoxTree* ElementBndBoxTree::getLeafAtPoint( const gp_XYZ& point )
452 if ( getBox()->IsOut( point ))
461 for (int i = 0; i < 8; i++)
462 if ( ElementBndBoxTree* l = ((ElementBndBoxTree*) myChildren[i])->getLeafAtPoint( point ))
468 //================================================================================
470 * \brief Return number of elements
472 //================================================================================
474 int ElementBndBoxTree::getNbElements()
479 nb = _elements.size();
483 for (int i = 0; i < 8; i++)
484 nb += ((ElementBndBoxTree*) myChildren[i])->getNbElements();
489 //================================================================================
491 * \brief Construct the element box
493 //================================================================================
495 void ElementBndBoxTree::ElementBox::init(const SMDS_MeshElement* elem, double tolerance)
498 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
499 while ( nIt->more() )
500 Add( SMESH_NodeXYZ( nIt->next() ));
501 Enlarge( tolerance );
506 //=======================================================================
508 * \brief Implementation of search for the elements by point and
509 * of classification of point in 2D mesh
511 //=======================================================================
513 SMESH_ElementSearcher::~SMESH_ElementSearcher()
517 struct SMESH_ElementSearcherImpl: public SMESH_ElementSearcher
520 SMDS_ElemIteratorPtr _meshPartIt;
521 ElementBndBoxTree* _ebbTree [SMDSAbs_NbElementTypes];
522 int _ebbTreeHeight[SMDSAbs_NbElementTypes];
523 SMESH_NodeSearcherImpl* _nodeSearcher;
524 SMDSAbs_ElementType _elementType;
526 bool _outerFacesFound;
527 std::set<const SMDS_MeshElement*> _outerFaces; // empty means "no internal faces at all"
529 SMESH_ElementSearcherImpl( SMDS_Mesh& mesh,
531 SMDS_ElemIteratorPtr elemIt=SMDS_ElemIteratorPtr())
532 : _mesh(&mesh),_meshPartIt(elemIt),_nodeSearcher(0),_tolerance(tol),_outerFacesFound(false)
534 for ( int i = 0; i < SMDSAbs_NbElementTypes; ++i )
537 _ebbTreeHeight[i] = -1;
539 _elementType = SMDSAbs_All;
541 virtual ~SMESH_ElementSearcherImpl()
543 for ( int i = 0; i < SMDSAbs_NbElementTypes; ++i )
545 delete _ebbTree[i]; _ebbTree[i] = NULL;
547 if ( _nodeSearcher ) delete _nodeSearcher;
550 virtual int FindElementsByPoint(const gp_Pnt& point,
551 SMDSAbs_ElementType type,
552 std::vector< const SMDS_MeshElement* >& foundElements);
553 virtual TopAbs_State GetPointState(const gp_Pnt& point);
554 virtual const SMDS_MeshElement* FindClosestTo( const gp_Pnt& point,
555 SMDSAbs_ElementType type );
557 virtual void GetElementsNearLine( const gp_Ax1& line,
558 SMDSAbs_ElementType type,
559 std::vector< const SMDS_MeshElement* >& foundElems);
560 virtual void GetElementsInSphere( const gp_XYZ& center,
562 SMDSAbs_ElementType type,
563 std::vector< const SMDS_MeshElement* >& foundElems);
564 virtual void GetElementsInBox( const Bnd_B3d& box,
565 SMDSAbs_ElementType type,
566 std::vector< const SMDS_MeshElement* >& foundElems);
567 virtual gp_XYZ Project(const gp_Pnt& point,
568 SMDSAbs_ElementType type,
569 const SMDS_MeshElement** closestElem);
570 double getTolerance();
571 bool getIntersParamOnLine(const gp_Lin& line, const SMDS_MeshElement* face,
572 const double tolerance, double & param);
573 void findOuterBoundary(const SMDS_MeshElement* anyOuterFace);
574 bool isOuterBoundary(const SMDS_MeshElement* face) const
576 return _outerFaces.empty() || _outerFaces.count(face);
580 if ( _ebbTreeHeight[ _elementType ] < 0 )
581 _ebbTreeHeight[ _elementType ] = _ebbTree[ _elementType ]->getHeight();
582 return _ebbTreeHeight[ _elementType ];
585 struct TInters //!< data of intersection of the line and the mesh face (used in GetPointState())
587 const SMDS_MeshElement* _face;
589 bool _coincides; //!< the line lays in face plane
590 TInters(const SMDS_MeshElement* face, const gp_Vec& faceNorm, bool coinc=false)
591 : _face(face), _faceNorm( faceNorm ), _coincides( coinc ) {}
593 struct TFaceLink //!< link and faces sharing it (used in findOuterBoundary())
596 TIDSortedElemSet _faces;
597 TFaceLink( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshElement* face)
598 : _link( n1, n2 ), _faces( &face, &face + 1) {}
602 ostream& operator<< (ostream& out, const SMESH_ElementSearcherImpl::TInters& i)
604 return out << "TInters(face=" << ( i._face ? i._face->GetID() : 0)
605 << ", _coincides="<<i._coincides << ")";
608 //=======================================================================
610 * \brief define tolerance for search
612 //=======================================================================
614 double SMESH_ElementSearcherImpl::getTolerance()
616 if ( _tolerance < 0 )
618 const SMDS_MeshInfo& meshInfo = _mesh->GetMeshInfo();
621 if ( _nodeSearcher && meshInfo.NbNodes() > 1 )
623 double boxSize = _nodeSearcher->getTree()->maxSize();
624 _tolerance = 1e-8 * boxSize/* / meshInfo.NbNodes()*/;
626 else if ( _ebbTree[_elementType] && meshInfo.NbElements() > 0 )
628 double boxSize = _ebbTree[_elementType]->maxSize();
629 _tolerance = 1e-8 * boxSize/* / meshInfo.NbElements()*/;
631 if ( _tolerance == 0 )
633 // define tolerance by size of a most complex element
634 int complexType = SMDSAbs_Volume;
635 while ( complexType > SMDSAbs_All &&
636 meshInfo.NbElements( SMDSAbs_ElementType( complexType )) < 1 )
638 if ( complexType == SMDSAbs_All ) return 0; // empty mesh
640 if ( complexType == int( SMDSAbs_Node ))
642 SMDS_NodeIteratorPtr nodeIt = _mesh->nodesIterator();
644 if ( meshInfo.NbNodes() > 2 )
645 elemSize = SMESH_TNodeXYZ( nodeIt->next() ).Distance( nodeIt->next() );
649 SMDS_ElemIteratorPtr elemIt = _mesh->elementsIterator( SMDSAbs_ElementType( complexType ));
650 const SMDS_MeshElement* elem = elemIt->next();
651 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
652 SMESH_TNodeXYZ n1( nodeIt->next() );
654 while ( nodeIt->more() )
656 double dist = n1.Distance( static_cast<const SMDS_MeshNode*>( nodeIt->next() ));
657 elemSize = std::max( dist, elemSize );
660 _tolerance = 1e-4 * elemSize;
666 //================================================================================
668 * \brief Find intersection of the line and an edge of face and return parameter on line
670 //================================================================================
672 bool SMESH_ElementSearcherImpl::getIntersParamOnLine(const gp_Lin& line,
673 const SMDS_MeshElement* face,
680 GeomAPI_ExtremaCurveCurve anExtCC;
681 Handle(Geom_Curve) lineCurve = new Geom_Line( line );
683 int nbNodes = face->IsQuadratic() ? face->NbNodes()/2 : face->NbNodes();
684 for ( int i = 0; i < nbNodes && nbInts < 2; ++i )
686 GC_MakeSegment edge( SMESH_TNodeXYZ( face->GetNode( i )),
687 SMESH_TNodeXYZ( face->GetNode( (i+1)%nbNodes) ));
688 anExtCC.Init( lineCurve, edge.Value() );
689 if ( !anExtCC.Extrema().IsDone() ||
690 anExtCC.Extrema().IsParallel() )
692 if ( anExtCC.NbExtrema() > 0 && anExtCC.LowerDistance() <= tol)
694 Standard_Real pl, pe;
695 anExtCC.LowerDistanceParameters( pl, pe );
701 if ( nbInts > 0 ) param /= nbInts;
704 //================================================================================
706 * \brief Find all faces belonging to the outer boundary of mesh
708 //================================================================================
710 void SMESH_ElementSearcherImpl::findOuterBoundary(const SMDS_MeshElement* outerFace)
712 if ( _outerFacesFound ) return;
714 // Collect all outer faces by passing from one outer face to another via their links
715 // and BTW find out if there are internal faces at all.
717 // checked links and links where outer boundary meets internal one
718 std::set< SMESH_TLink > visitedLinks, seamLinks;
720 // links to treat with already visited faces sharing them
721 std::list < TFaceLink > startLinks;
723 // load startLinks with the first outerFace
724 startLinks.push_back( TFaceLink( outerFace->GetNode(0), outerFace->GetNode(1), outerFace));
725 _outerFaces.insert( outerFace );
727 TIDSortedElemSet emptySet;
728 while ( !startLinks.empty() )
730 const SMESH_TLink& link = startLinks.front()._link;
731 TIDSortedElemSet& faces = startLinks.front()._faces;
733 outerFace = *faces.begin();
734 // find other faces sharing the link
735 const SMDS_MeshElement* f;
736 while (( f = SMESH_MeshAlgos::FindFaceInSet(link.node1(), link.node2(), emptySet, faces )))
739 // select another outer face among the found
740 const SMDS_MeshElement* outerFace2 = 0;
741 if ( faces.size() == 2 )
743 outerFace2 = (outerFace == *faces.begin() ? *faces.rbegin() : *faces.begin());
745 else if ( faces.size() > 2 )
747 seamLinks.insert( link );
749 // link direction within the outerFace
750 gp_Vec n1n2( SMESH_TNodeXYZ( link.node1()),
751 SMESH_TNodeXYZ( link.node2()));
752 int i1 = outerFace->GetNodeIndex( link.node1() );
753 int i2 = outerFace->GetNodeIndex( link.node2() );
754 bool rev = ( abs(i2-i1) == 1 ? i1 > i2 : i2 > i1 );
755 if ( rev ) n1n2.Reverse();
757 gp_XYZ ofNorm, fNorm;
758 if ( SMESH_MeshAlgos::FaceNormal( outerFace, ofNorm, /*normalized=*/false ))
760 // direction from the link inside outerFace
761 gp_Vec dirInOF = gp_Vec( ofNorm ) ^ n1n2;
762 // sort all other faces by angle with the dirInOF
763 std::map< double, const SMDS_MeshElement* > angle2Face;
764 std::set< const SMDS_MeshElement*, TIDCompare >::const_iterator face = faces.begin();
765 for ( ; face != faces.end(); ++face )
767 if ( *face == outerFace ) continue;
768 if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false ))
770 gp_Vec dirInF = gp_Vec( fNorm ) ^ n1n2;
771 double angle = dirInOF.AngleWithRef( dirInF, n1n2 );
772 if ( angle < 0 ) angle += 2. * M_PI;
773 angle2Face.insert( std::make_pair( angle, *face ));
775 if ( !angle2Face.empty() )
776 outerFace2 = angle2Face.begin()->second;
779 // store the found outer face and add its links to continue searching from
782 _outerFaces.insert( outerFace2 );
783 int nbNodes = outerFace2->NbCornerNodes();
784 for ( int i = 0; i < nbNodes; ++i )
786 SMESH_TLink link2( outerFace2->GetNode(i), outerFace2->GetNode((i+1)%nbNodes));
787 if ( visitedLinks.insert( link2 ).second )
788 startLinks.push_back( TFaceLink( link2.node1(), link2.node2(), outerFace2 ));
791 startLinks.pop_front();
793 _outerFacesFound = true;
795 if ( !seamLinks.empty() )
797 // There are internal boundaries touching the outher one,
798 // find all faces of internal boundaries in order to find
799 // faces of boundaries of holes, if any.
808 //=======================================================================
810 * \brief Find elements of given type where the given point is IN or ON.
811 * Returns nb of found elements and elements them-selves.
813 * 'ALL' type means elements of any type excluding nodes, balls and 0D elements
815 //=======================================================================
817 int SMESH_ElementSearcherImpl::
818 FindElementsByPoint(const gp_Pnt& point,
819 SMDSAbs_ElementType type,
820 std::vector< const SMDS_MeshElement* >& foundElements)
822 foundElements.clear();
825 double tolerance = getTolerance();
827 // =================================================================================
828 if ( type == SMDSAbs_Node || type == SMDSAbs_0DElement || type == SMDSAbs_Ball)
830 if ( !_nodeSearcher )
833 _nodeSearcher = new SMESH_NodeSearcherImpl( 0, _meshPartIt );
835 _nodeSearcher = new SMESH_NodeSearcherImpl( _mesh );
837 std::vector< const SMDS_MeshNode* > foundNodes;
838 _nodeSearcher->FindNearPoint( point, tolerance, foundNodes );
840 if ( type == SMDSAbs_Node )
842 foundElements.assign( foundNodes.begin(), foundNodes.end() );
846 for ( size_t i = 0; i < foundNodes.size(); ++i )
848 SMDS_ElemIteratorPtr elemIt = foundNodes[i]->GetInverseElementIterator( type );
849 while ( elemIt->more() )
850 foundElements.push_back( elemIt->next() );
854 // =================================================================================
855 else // elements more complex than 0D
857 if ( !_ebbTree[type] )
859 _ebbTree[_elementType] = new ElementBndBoxTree( *_mesh, type, _meshPartIt, tolerance );
861 ElementBndBoxTree::TElemSeq suspectElems;
862 _ebbTree[ type ]->getElementsNearPoint( point, suspectElems );
863 ElementBndBoxTree::TElemSeq::iterator elem = suspectElems.begin();
864 for ( ; elem != suspectElems.end(); ++elem )
865 if ( !SMESH_MeshAlgos::IsOut( *elem, point, tolerance ))
866 foundElements.push_back( *elem );
868 return foundElements.size();
871 //=======================================================================
873 * \brief Find an element of given type most close to the given point
875 * WARNING: Only edge, face and volume search is implemented so far
877 //=======================================================================
879 const SMDS_MeshElement*
880 SMESH_ElementSearcherImpl::FindClosestTo( const gp_Pnt& point,
881 SMDSAbs_ElementType type )
883 const SMDS_MeshElement* closestElem = 0;
886 if ( type == SMDSAbs_Face ||
887 type == SMDSAbs_Volume ||
888 type == SMDSAbs_Edge )
890 ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
892 ebbTree = new ElementBndBoxTree( *_mesh, type, _meshPartIt );
894 ElementBndBoxTree::TElemSeq suspectElems;
895 ebbTree->getElementsNearPoint( point, suspectElems );
897 if ( suspectElems.empty() && ebbTree->maxSize() > 0 )
899 gp_Pnt boxCenter = 0.5 * ( ebbTree->getBox()->CornerMin() +
900 ebbTree->getBox()->CornerMax() );
902 if ( ebbTree->getBox()->IsOut( point.XYZ() ))
903 radius = point.Distance( boxCenter ) - 0.5 * ebbTree->maxSize();
905 radius = ebbTree->maxSize() / pow( 2., getTreeHeight()) / 2;
906 while ( suspectElems.empty() && radius < 1e100 )
908 ebbTree->getElementsInSphere( point.XYZ(), radius, suspectElems );
912 double minDist = std::numeric_limits<double>::max();
913 std::multimap< double, const SMDS_MeshElement* > dist2face;
914 ElementBndBoxTree::TElemSeq::iterator elem = suspectElems.begin();
915 for ( ; elem != suspectElems.end(); ++elem )
917 double dist = SMESH_MeshAlgos::GetDistance( *elem, point );
918 if ( dist < minDist + 1e-10)
921 dist2face.insert( dist2face.begin(), std::make_pair( dist, *elem ));
924 if ( !dist2face.empty() )
926 std::multimap< double, const SMDS_MeshElement* >::iterator d2f = dist2face.begin();
927 closestElem = d2f->second;
928 // if there are several elements at the same distance, select one
929 // with GC closest to the point
930 typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
931 double minDistToGC = 0;
932 for ( ++d2f; d2f != dist2face.end() && fabs( d2f->first - minDist ) < 1e-10; ++d2f )
934 if ( minDistToGC == 0 )
937 gc = accumulate( TXyzIterator(closestElem->nodesIterator()),
938 TXyzIterator(), gc ) / closestElem->NbNodes();
939 minDistToGC = point.SquareDistance( gc );
942 gc = accumulate( TXyzIterator( d2f->second->nodesIterator()),
943 TXyzIterator(), gc ) / d2f->second->NbNodes();
944 double d = point.SquareDistance( gc );
945 if ( d < minDistToGC )
948 closestElem = d2f->second;
951 // cout << "FindClosestTo( " <<point.X()<<", "<<point.Y()<<", "<<point.Z()<<" ) FACE "
952 // <<closestElem->GetID() << " DIST " << minDist << endl;
957 // NOT IMPLEMENTED SO FAR
963 //================================================================================
965 * \brief Classify the given point in the closed 2D mesh
967 //================================================================================
969 TopAbs_State SMESH_ElementSearcherImpl::GetPointState(const gp_Pnt& point)
971 _elementType = SMDSAbs_Face;
973 double tolerance = getTolerance();
975 ElementBndBoxTree*& ebbTree = _ebbTree[ SMDSAbs_Face ];
977 ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
979 // Algo: analyse transition of a line starting at the point through mesh boundary;
980 // try three lines parallel to axis of the coordinate system and perform rough
981 // analysis. If solution is not clear perform thorough analysis.
983 const int nbAxes = 3;
984 gp_Dir axisDir[ nbAxes ] = { gp::DX(), gp::DY(), gp::DZ() };
985 std::map< double, TInters > paramOnLine2TInters[ nbAxes ];
986 std::list< TInters > tangentInters[ nbAxes ]; // of faces whose plane includes the line
987 std::multimap< int, int > nbInt2Axis; // to find the simplest case
988 for ( int axis = 0; axis < nbAxes; ++axis )
990 gp_Ax1 lineAxis( point, axisDir[axis]);
991 gp_Lin line ( lineAxis );
993 ElementBndBoxTree::TElemSeq suspectFaces; // faces possibly intersecting the line
994 ebbTree->getElementsNearLine( lineAxis, suspectFaces );
996 // Intersect faces with the line
998 std::map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
999 ElementBndBoxTree::TElemSeq::iterator face = suspectFaces.begin();
1000 for ( ; face != suspectFaces.end(); ++face )
1004 if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false)) continue;
1005 gp_Pln facePlane( SMESH_TNodeXYZ( (*face)->GetNode(0)), fNorm );
1007 // perform intersection
1008 IntAna_IntConicQuad intersection( line, IntAna_Quadric( facePlane ));
1009 if ( !intersection.IsDone() )
1011 if ( intersection.IsInQuadric() )
1013 tangentInters[ axis ].push_back( TInters( *face, fNorm, true ));
1015 else if ( ! intersection.IsParallel() && intersection.NbPoints() > 0 )
1017 double tol = 1e-4 * Sqrt( fNorm.Modulus() );
1018 gp_Pnt intersectionPoint = intersection.Point(1);
1019 if ( !SMESH_MeshAlgos::IsOut( *face, intersectionPoint, tol ))
1020 u2inters.insert( std::make_pair( intersection.ParamOnConic(1), TInters( *face, fNorm )));
1023 // Analyse intersections roughly
1025 int nbInter = u2inters.size();
1029 double f = u2inters.begin()->first, l = u2inters.rbegin()->first;
1030 if ( nbInter == 1 ) // not closed mesh
1031 return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
1033 if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
1036 if ( (f<0) == (l<0) )
1039 int nbIntBeforePoint = std::distance( u2inters.begin(), u2inters.lower_bound(0));
1040 int nbIntAfterPoint = nbInter - nbIntBeforePoint;
1041 if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
1044 nbInt2Axis.insert( std::make_pair( std::min( nbIntBeforePoint, nbIntAfterPoint ), axis ));
1046 if ( _outerFacesFound ) break; // pass to thorough analysis
1048 } // three attempts - loop on CS axes
1050 // Analyse intersections thoroughly.
1051 // We make two loops maximum, on the first one we only exclude touching intersections,
1052 // on the second, if situation is still unclear, we gather and use information on
1053 // position of faces (internal or outer). If faces position is already gathered,
1054 // we make the second loop right away.
1056 for ( int hasPositionInfo = _outerFacesFound; hasPositionInfo < 2; ++hasPositionInfo )
1058 std::multimap< int, int >::const_iterator nb_axis = nbInt2Axis.begin();
1059 for ( ; nb_axis != nbInt2Axis.end(); ++nb_axis )
1061 int axis = nb_axis->second;
1062 std::map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
1064 gp_Ax1 lineAxis( point, axisDir[axis]);
1065 gp_Lin line ( lineAxis );
1067 // add tangent intersections to u2inters
1069 std::list< TInters >::const_iterator tgtInt = tangentInters[ axis ].begin();
1070 for ( ; tgtInt != tangentInters[ axis ].end(); ++tgtInt )
1071 if ( getIntersParamOnLine( line, tgtInt->_face, tolerance, param ))
1072 u2inters.insert( std::make_pair( param, *tgtInt ));
1073 tangentInters[ axis ].clear();
1075 // Count intersections before and after the point excluding touching ones.
1076 // If hasPositionInfo we count intersections of outer boundary only
1078 int nbIntBeforePoint = 0, nbIntAfterPoint = 0;
1079 double f = std::numeric_limits<double>::max(), l = -std::numeric_limits<double>::max();
1080 std::map< double, TInters >::iterator u_int1 = u2inters.begin(), u_int2 = u_int1;
1081 bool ok = ! u_int1->second._coincides;
1082 while ( ok && u_int1 != u2inters.end() )
1084 double u = u_int1->first;
1085 bool touchingInt = false;
1086 if ( ++u_int2 != u2inters.end() )
1088 // skip intersections at the same point (if the line passes through edge or node)
1090 while ( u_int2 != u2inters.end() && fabs( u_int2->first - u ) < tolerance )
1096 // skip tangent intersections
1098 if ( u_int2 != u2inters.end() )
1100 const SMDS_MeshElement* prevFace = u_int1->second._face;
1101 while ( ok && u_int2->second._coincides )
1103 if ( SMESH_MeshAlgos::NbCommonNodes(prevFace , u_int2->second._face) == 0 )
1109 ok = ( u_int2 != u2inters.end() );
1115 // skip intersections at the same point after tangent intersections
1118 double u2 = u_int2->first;
1120 while ( u_int2 != u2inters.end() && fabs( u_int2->first - u2 ) < tolerance )
1126 // decide if we skipped a touching intersection
1127 if ( nbSamePnt + nbTgt > 0 )
1129 double minDot = std::numeric_limits<double>::max(), maxDot = -minDot;
1130 std::map< double, TInters >::iterator u_int = u_int1;
1131 for ( ; u_int != u_int2; ++u_int )
1133 if ( u_int->second._coincides ) continue;
1134 double dot = u_int->second._faceNorm * line.Direction();
1135 if ( dot > maxDot ) maxDot = dot;
1136 if ( dot < minDot ) minDot = dot;
1138 touchingInt = ( minDot*maxDot < 0 );
1143 if ( !hasPositionInfo || isOuterBoundary( u_int1->second._face ))
1154 u_int1 = u_int2; // to next intersection
1156 } // loop on intersections with one line
1160 if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
1163 if ( nbIntBeforePoint == 0 || nbIntAfterPoint == 0)
1166 if ( nbIntBeforePoint + nbIntAfterPoint == 1 ) // not closed mesh
1167 return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
1169 if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
1172 if ( (f<0) == (l<0) )
1175 if ( hasPositionInfo )
1176 return nbIntBeforePoint % 2 ? TopAbs_IN : TopAbs_OUT;
1178 } // loop on intersections of the tree lines - thorough analysis
1180 if ( !hasPositionInfo )
1182 // gather info on faces position - is face in the outer boundary or not
1183 std::map< double, TInters > & u2inters = paramOnLine2TInters[ 0 ];
1184 findOuterBoundary( u2inters.begin()->second._face );
1187 } // two attempts - with and w/o faces position info in the mesh
1189 return TopAbs_UNKNOWN;
1192 //=======================================================================
1194 * \brief Return elements possibly intersecting the line
1196 //=======================================================================
1198 void SMESH_ElementSearcherImpl::
1199 GetElementsNearLine( const gp_Ax1& line,
1200 SMDSAbs_ElementType type,
1201 std::vector< const SMDS_MeshElement* >& foundElems)
1203 _elementType = type;
1204 ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
1206 ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
1208 ElementBndBoxTree::TElemSeq elems;
1209 ebbTree->getElementsNearLine( line, elems );
1211 foundElems.insert( foundElems.end(), elems.begin(), elems.end() );
1214 //=======================================================================
1216 * Return elements whose bounding box intersects a sphere
1218 //=======================================================================
1220 void SMESH_ElementSearcherImpl::
1221 GetElementsInSphere( const gp_XYZ& center,
1222 const double radius,
1223 SMDSAbs_ElementType type,
1224 std::vector< const SMDS_MeshElement* >& foundElems)
1226 _elementType = type;
1227 ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
1229 ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
1231 ElementBndBoxTree::TElemSeq elems;
1232 ebbTree->getElementsInSphere( center, radius, elems );
1234 foundElems.insert( foundElems.end(), elems.begin(), elems.end() );
1237 //=======================================================================
1239 * Return elements whose bounding box intersects a given bounding box
1241 //=======================================================================
1243 void SMESH_ElementSearcherImpl::
1244 GetElementsInBox( const Bnd_B3d& box,
1245 SMDSAbs_ElementType type,
1246 std::vector< const SMDS_MeshElement* >& foundElems)
1248 _elementType = type;
1249 ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
1251 ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt, getTolerance() );
1253 ElementBndBoxTree::TElemSeq elems;
1254 ebbTree->getElementsInBox( box, elems );
1256 foundElems.insert( foundElems.end(), elems.begin(), elems.end() );
1259 //=======================================================================
1261 * \brief Return a projection of a given point to a mesh.
1262 * Optionally return the closest element
1264 //=======================================================================
1266 gp_XYZ SMESH_ElementSearcherImpl::Project(const gp_Pnt& point,
1267 SMDSAbs_ElementType type,
1268 const SMDS_MeshElement** closestElem)
1270 _elementType = type;
1271 if ( _mesh->GetMeshInfo().NbElements( _elementType ) == 0 )
1272 throw SALOME_Exception( LOCALIZED( "No elements of given type in the mesh" ));
1274 ElementBndBoxTree*& ebbTree = _ebbTree[ _elementType ];
1276 ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
1278 gp_XYZ p = point.XYZ();
1279 ElementBndBoxTree* ebbLeaf = ebbTree->getLeafAtPoint( p );
1280 const Bnd_B3d* box = ebbLeaf ? ebbLeaf->getBox() : ebbTree->getBox();
1281 gp_XYZ pMin = box->CornerMin(), pMax = box->CornerMax();
1282 double radius = Precision::Infinite();
1283 if ( ebbLeaf || !box->IsOut( p ))
1285 for ( int i = 1; i <= 3; ++i )
1287 double d = 0.5 * ( pMax.Coord(i) - pMin.Coord(i) );
1288 if ( d > Precision::Confusion() )
1289 radius = Min( d, radius );
1292 radius /= ebbTree->getHeight( /*full=*/true );
1294 else // p outside of box
1296 for ( int i = 1; i <= 3; ++i )
1299 if ( point.Coord(i) < pMin.Coord(i) )
1300 d = pMin.Coord(i) - point.Coord(i);
1301 else if ( point.Coord(i) > pMax.Coord(i) )
1302 d = point.Coord(i) - pMax.Coord(i);
1303 if ( d > Precision::Confusion() )
1304 radius = Min( d, radius );
1308 ElementBndBoxTree::TElemSeq elems;
1309 ebbTree->getElementsInSphere( p, radius, elems );
1310 while ( elems.empty() && radius < 1e100 )
1313 ebbTree->getElementsInSphere( p, radius, elems );
1315 gp_XYZ proj, bestProj;
1316 const SMDS_MeshElement* elem = 0;
1317 double minDist = Precision::Infinite();
1318 ElementBndBoxTree::TElemSeq::iterator e = elems.begin();
1319 for ( ; e != elems.end(); ++e )
1321 double d = SMESH_MeshAlgos::GetDistance( *e, point, &proj );
1329 if ( minDist > radius )
1331 ElementBndBoxTree::TElemSeq elems2;
1332 ebbTree->getElementsInSphere( p, minDist, elems2 );
1333 for ( e = elems2.begin(); e != elems2.end(); ++e )
1335 if ( elems.count( *e ))
1337 double d = SMESH_MeshAlgos::GetDistance( *e, point, &proj );
1346 if ( closestElem ) *closestElem = elem;
1351 //=======================================================================
1353 * \brief Return true if the point is IN or ON of the element
1355 //=======================================================================
1357 bool SMESH_MeshAlgos::IsOut( const SMDS_MeshElement* element, const gp_Pnt& point, double tol )
1359 if ( element->GetType() == SMDSAbs_Volume)
1361 return SMDS_VolumeTool( element ).IsOut( point.X(), point.Y(), point.Z(), tol );
1364 // get ordered nodes
1366 std::vector< SMESH_TNodeXYZ > xyz; xyz.reserve( element->NbNodes()+1 );
1368 SMDS_NodeIteratorPtr nodeIt = element->interlacedNodesIterator();
1369 for ( int i = 0; nodeIt->more(); ++i )
1370 xyz.push_back( SMESH_TNodeXYZ( nodeIt->next() ));
1372 int i, nbNodes = (int) xyz.size(); // central node of biquadratic is missing
1374 if ( element->GetType() == SMDSAbs_Face ) // --------------------------------------------------
1376 // compute face normal
1377 gp_Vec faceNorm(0,0,0);
1378 xyz.push_back( xyz.front() );
1379 for ( i = 0; i < nbNodes; ++i )
1381 gp_Vec edge1( xyz[i+1], xyz[i]);
1382 gp_Vec edge2( xyz[i+1], xyz[(i+2)%nbNodes] );
1383 faceNorm += edge1 ^ edge2;
1385 double fNormSize = faceNorm.Magnitude();
1386 if ( fNormSize <= tol )
1388 // degenerated face: point is out if it is out of all face edges
1389 for ( i = 0; i < nbNodes; ++i )
1391 SMDS_LinearEdge edge( xyz[i]._node, xyz[i+1]._node );
1392 if ( !IsOut( &edge, point, tol ))
1397 faceNorm /= fNormSize;
1399 // check if the point lays on face plane
1400 gp_Vec n2p( xyz[0], point );
1401 double dot = n2p * faceNorm;
1402 if ( Abs( dot ) > tol ) // not on face plane
1405 if ( nbNodes > 3 ) // maybe the face is not planar
1407 double elemThick = 0;
1408 for ( i = 1; i < nbNodes; ++i )
1410 gp_Vec n2n( xyz[0], xyz[i] );
1411 elemThick = Max( elemThick, Abs( n2n * faceNorm ));
1413 isOut = Abs( dot ) > elemThick + tol;
1419 // check if point is out of face boundary:
1420 // define it by closest transition of a ray point->infinity through face boundary
1421 // on the face plane.
1422 // First, find normal of a plane perpendicular to face plane, to be used as a cutting tool
1423 // to find intersections of the ray with the boundary.
1425 gp_Vec plnNorm = ray ^ faceNorm;
1426 double n2pSize = plnNorm.Magnitude();
1427 if ( n2pSize <= tol ) return false; // point coincides with the first node
1428 if ( n2pSize * n2pSize > fNormSize * 100 ) return true; // point is very far
1430 // for each node of the face, compute its signed distance to the cutting plane
1431 std::vector<double> dist( nbNodes + 1);
1432 for ( i = 0; i < nbNodes; ++i )
1434 gp_Vec n2p( xyz[i], point );
1435 dist[i] = n2p * plnNorm;
1437 dist.back() = dist.front();
1438 // find the closest intersection
1440 double rClosest = 0, distClosest = 1e100;
1442 for ( i = 0; i < nbNodes; ++i )
1445 if ( fabs( dist[i] ) < tol )
1447 else if ( fabs( dist[i+1]) < tol )
1449 else if ( dist[i] * dist[i+1] < 0 )
1450 r = dist[i] / ( dist[i] - dist[i+1] );
1452 continue; // no intersection
1453 gp_Pnt pInt = xyz[i] * (1.-r) + xyz[i+1] * r;
1454 gp_Vec p2int( point, pInt);
1455 double intDist = p2int.SquareMagnitude();
1456 if ( intDist < distClosest )
1461 distClosest = intDist;
1465 return true; // no intesections - out
1467 // analyse transition
1468 gp_Vec edge( xyz[iClosest], xyz[iClosest+1] );
1469 gp_Vec edgeNorm = -( edge ^ faceNorm ); // normal to intersected edge pointing out of face
1470 gp_Vec p2int ( point, pClosest );
1471 bool out = (edgeNorm * p2int) < -tol;
1472 if ( rClosest > 0. && rClosest < 1. ) // not node intersection
1475 // the ray passes through a face node; analyze transition through an adjacent edge
1476 gp_Pnt p1 = xyz[ (rClosest == 0.) ? ((iClosest+nbNodes-1) % nbNodes) : (iClosest+1) ];
1477 gp_Pnt p2 = xyz[ (rClosest == 0.) ? iClosest : ((iClosest+2) % nbNodes) ];
1478 gp_Vec edgeAdjacent( p1, p2 );
1479 gp_Vec edgeNorm2 = -( edgeAdjacent ^ faceNorm );
1480 bool out2 = (edgeNorm2 * p2int) < -tol;
1482 bool covexCorner = ( edgeNorm * edgeAdjacent * (rClosest==1. ? 1. : -1.)) < 0;
1483 return covexCorner ? (out || out2) : (out && out2);
1486 if ( element->GetType() == SMDSAbs_Edge ) // --------------------------------------------------
1488 // point is out of edge if it is NOT ON any straight part of edge
1489 // (we consider quadratic edge as being composed of two straight parts)
1490 for ( i = 1; i < nbNodes; ++i )
1492 gp_Vec edge( xyz[i-1], xyz[i] );
1493 gp_Vec n1p ( xyz[i-1], point );
1494 double u = ( edge * n1p ) / edge.SquareMagnitude(); // param [0,1] on the edge
1496 if ( n1p.SquareMagnitude() < tol * tol )
1501 if ( point.SquareDistance( xyz[i] ) < tol * tol )
1505 gp_XYZ proj = ( 1. - u ) * xyz[i-1] + u * xyz[i]; // projection of the point on the edge
1506 double dist2 = point.SquareDistance( proj );
1507 if ( dist2 > tol * tol )
1509 return false; // point is ON this part
1514 // Node or 0D element -------------------------------------------------------------------------
1516 gp_Vec n2p ( xyz[0], point );
1517 return n2p.SquareMagnitude() > tol * tol;
1522 //=======================================================================
1525 // Position of a point relative to a segment
1529 // VERTEX 1 o----ON-----> VERTEX 2
1533 enum PositionName { POS_LEFT = 1, POS_VERTEX = 2, POS_RIGHT = 4, //POS_ON = 8,
1534 POS_ALL = POS_LEFT | POS_RIGHT | POS_VERTEX,
1535 POS_MAX = POS_RIGHT };
1539 int _index; // index of vertex or segment
1541 PointPos( PositionName n, int i=-1 ): _name(n), _index(i) {}
1542 bool operator < (const PointPos& other ) const
1544 if ( _name == other._name )
1545 return ( _index < 0 || other._index < 0 ) ? false : _index < other._index;
1546 return _name < other._name;
1550 //================================================================================
1552 * \brief Return position of a point relative to a segment
1553 * \param point2D - the point to analyze position of
1554 * \param segEnds - end points of segments
1555 * \param index0 - 0-based index of the first point of segment
1556 * \param posToFindOut - flags of positions to detect
1557 * \retval PointPos - point position
1559 //================================================================================
1561 PointPos getPointPosition( const gp_XY& point2D,
1562 const gp_XY* segEnds,
1563 const int index0 = 0,
1564 const int posToFindOut = POS_ALL)
1566 const gp_XY& p1 = segEnds[ index0 ];
1567 const gp_XY& p2 = segEnds[ index0+1 ];
1568 const gp_XY grad = p2 - p1;
1570 if ( posToFindOut & POS_VERTEX )
1572 // check if the point2D is at "vertex 1" zone
1573 gp_XY pp1[2] = { p1, gp_XY( p1.X() - grad.Y(),
1574 p1.Y() + grad.X() ) };
1575 if ( getPointPosition( point2D, pp1, 0, POS_LEFT|POS_RIGHT )._name == POS_LEFT )
1576 return PointPos( POS_VERTEX, index0 );
1578 // check if the point2D is at "vertex 2" zone
1579 gp_XY pp2[2] = { p2, gp_XY( p2.X() - grad.Y(),
1580 p2.Y() + grad.X() ) };
1581 if ( getPointPosition( point2D, pp2, 0, POS_LEFT|POS_RIGHT )._name == POS_RIGHT )
1582 return PointPos( POS_VERTEX, index0 + 1);
1584 double edgeEquation =
1585 ( point2D.X() - p1.X() ) * grad.Y() - ( point2D.Y() - p1.Y() ) * grad.X();
1586 return PointPos( edgeEquation < 0 ? POS_LEFT : POS_RIGHT, index0 );
1590 //=======================================================================
1592 * \brief Return minimal distance from a point to an element
1594 * Currently we ignore non-planarity and 2nd order of face
1596 //=======================================================================
1598 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshElement* elem,
1599 const gp_Pnt& point,
1600 gp_XYZ* closestPnt )
1602 switch ( elem->GetType() )
1604 case SMDSAbs_Volume:
1605 return GetDistance( static_cast<const SMDS_MeshVolume*>( elem ), point, closestPnt );
1607 return GetDistance( static_cast<const SMDS_MeshFace*>( elem ), point, closestPnt );
1609 return GetDistance( static_cast<const SMDS_MeshEdge*>( elem ), point, closestPnt );
1611 if ( closestPnt ) *closestPnt = SMESH_TNodeXYZ( elem );
1612 return point.Distance( SMESH_TNodeXYZ( elem ));
1618 //=======================================================================
1620 * \brief Return minimal distance from a point to a face
1622 * Currently we ignore non-planarity and 2nd order of face
1624 //=======================================================================
1626 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshFace* face,
1627 const gp_Pnt& point,
1628 gp_XYZ* closestPnt )
1630 const double badDistance = -1;
1631 if ( !face ) return badDistance;
1633 int nbCorners = face->NbCornerNodes();
1634 if ( nbCorners > 3 )
1636 std::vector< const SMDS_MeshNode* > nodes;
1637 int nbTria = SMESH_MeshAlgos::Triangulate().GetTriangles( face, nodes );
1639 double minDist = Precision::Infinite();
1641 for ( int i = 0; i < 3 * nbTria; i += 3 )
1643 SMDS_FaceOfNodes triangle( nodes[i], nodes[i+1], nodes[i+2] );
1644 double dist = GetDistance( &triangle, point, closestPnt );
1645 if ( dist < minDist )
1658 // coordinates of nodes (medium nodes, if any, ignored)
1659 typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
1660 std::vector<gp_XYZ> xyz( TXyzIterator( face->nodesIterator()), TXyzIterator() );
1663 // transformation to get xyz[0] lies on the origin, xyz[1] lies on the Z axis,
1664 // and xyz[2] lies in the XZ plane. This is to pass to 2D space on XZ plane.
1666 gp_Vec OZ ( xyz[0], xyz[1] );
1667 gp_Vec OX ( xyz[0], xyz[2] );
1668 if ( OZ.Magnitude() < std::numeric_limits<double>::min() )
1670 if ( xyz.size() < 4 ) return badDistance;
1671 OZ = gp_Vec ( xyz[0], xyz[2] );
1672 OX = gp_Vec ( xyz[0], xyz[3] );
1676 tgtCS = gp_Ax3( xyz[0], OZ, OX );
1678 catch ( Standard_Failure& ) {
1681 trsf.SetTransformation( tgtCS );
1683 // move all the nodes to 2D
1684 std::vector<gp_XY> xy( xyz.size() );
1685 for ( size_t i = 0; i < 3; ++i )
1687 gp_XYZ p3d = xyz[i];
1688 trsf.Transforms( p3d );
1689 xy[i].SetCoord( p3d.X(), p3d.Z() );
1691 xyz.back() = xyz.front();
1692 xy.back() = xy.front();
1694 // // move the point in 2D
1695 gp_XYZ tmpPnt = point.XYZ();
1696 trsf.Transforms( tmpPnt );
1697 gp_XY point2D( tmpPnt.X(), tmpPnt.Z() );
1699 // loop on edges of the face to analyze point position ralative to the face
1700 std::vector< PointPos > pntPosByType[ POS_MAX + 1 ];
1701 for ( size_t i = 1; i < xy.size(); ++i )
1703 PointPos pos = getPointPosition( point2D, &xy[0], i-1 );
1704 pntPosByType[ pos._name ].push_back( pos );
1709 double dist = badDistance;
1711 if ( pntPosByType[ POS_LEFT ].size() > 0 ) // point is most close to an edge
1713 PointPos& pos = pntPosByType[ POS_LEFT ][0];
1715 gp_Vec edge( xyz[ pos._index ], xyz[ pos._index+1 ]);
1716 gp_Vec n1p ( xyz[ pos._index ], point );
1717 double u = ( edge * n1p ) / edge.SquareMagnitude(); // param [0,1] on the edge
1718 gp_XYZ proj = xyz[ pos._index ] + u * edge.XYZ(); // projection on the edge
1719 dist = point.Distance( proj );
1720 if ( closestPnt ) *closestPnt = proj;
1723 else if ( pntPosByType[ POS_RIGHT ].size() >= 2 ) // point is inside the face
1725 dist = Abs( tmpPnt.Y() );
1728 if ( dist < std::numeric_limits<double>::min() ) {
1729 *closestPnt = point.XYZ();
1733 trsf.Inverted().Transforms( tmpPnt );
1734 *closestPnt = tmpPnt;
1739 else if ( pntPosByType[ POS_VERTEX ].size() > 0 ) // point is most close to a node
1741 double minDist2 = Precision::Infinite();
1742 for ( size_t i = 0; i < pntPosByType[ POS_VERTEX ].size(); ++i )
1744 PointPos& pos = pntPosByType[ POS_VERTEX ][i];
1746 double d2 = point.SquareDistance( xyz[ pos._index ]);
1747 if ( minDist2 > d2 )
1749 if ( closestPnt ) *closestPnt = xyz[ pos._index ];
1753 dist = Sqrt( minDist2 );
1759 //=======================================================================
1761 * \brief Return minimal distance from a point to an edge
1763 //=======================================================================
1765 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshEdge* seg,
1766 const gp_Pnt& point,
1767 gp_XYZ* closestPnt )
1769 double dist = Precision::Infinite();
1770 if ( !seg ) return dist;
1772 int i = 0, nbNodes = seg->NbNodes();
1774 std::vector< SMESH_TNodeXYZ > xyz( nbNodes );
1775 for ( SMDS_NodeIteratorPtr nodeIt = seg->interlacedNodesIterator(); nodeIt->more(); i++ )
1776 xyz[ i ].Set( nodeIt->next() );
1778 for ( i = 1; i < nbNodes; ++i )
1780 gp_Vec edge( xyz[i-1], xyz[i] );
1781 gp_Vec n1p ( xyz[i-1], point );
1782 double d, u = ( edge * n1p ) / edge.SquareMagnitude(); // param [0,1] on the edge
1784 if (( d = n1p.SquareMagnitude() ) < dist ) {
1786 if ( closestPnt ) *closestPnt = xyz[i-1];
1789 else if ( u >= 1. ) {
1790 if (( d = point.SquareDistance( xyz[i] )) < dist ) {
1792 if ( closestPnt ) *closestPnt = xyz[i];
1796 gp_XYZ proj = xyz[i-1] + u * edge.XYZ(); // projection of the point on the edge
1797 if (( d = point.SquareDistance( proj )) < dist ) {
1799 if ( closestPnt ) *closestPnt = proj;
1803 return Sqrt( dist );
1806 //=======================================================================
1808 * \brief Return minimal distance from a point to a volume
1810 * Currently we ignore non-planarity and 2nd order
1812 //=======================================================================
1814 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshVolume* volume,
1815 const gp_Pnt& point,
1816 gp_XYZ* closestPnt )
1818 SMDS_VolumeTool vTool( volume );
1819 vTool.SetExternalNormal();
1820 const int iQ = volume->IsQuadratic() ? 2 : 1;
1823 double minDist = 1e100, dist;
1824 gp_XYZ closeP = point.XYZ();
1826 for ( int iF = 0; iF < vTool.NbFaces(); ++iF )
1828 // skip a facet with normal not "looking at" the point
1829 if ( !vTool.GetFaceNormal( iF, n[0], n[1], n[2] ) ||
1830 !vTool.GetFaceBaryCenter( iF, bc[0], bc[1], bc[2] ))
1832 gp_XYZ bcp = point.XYZ() - gp_XYZ( bc[0], bc[1], bc[2] );
1833 if ( gp_XYZ( n[0], n[1], n[2] ) * bcp < -1e-12 )
1836 // find distance to a facet
1837 const SMDS_MeshNode** nodes = vTool.GetFaceNodes( iF );
1838 switch ( vTool.NbFaceNodes( iF ) / iQ ) {
1841 SMDS_FaceOfNodes tmpFace( nodes[0], nodes[ 1*iQ ], nodes[ 2*iQ ] );
1842 dist = GetDistance( &tmpFace, point, closestPnt );
1847 SMDS_FaceOfNodes tmpFace( nodes[0], nodes[ 1*iQ ], nodes[ 2*iQ ], nodes[ 3*iQ ]);
1848 dist = GetDistance( &tmpFace, point, closestPnt );
1852 std::vector<const SMDS_MeshNode *> nvec( nodes, nodes + vTool.NbFaceNodes( iF ));
1853 SMDS_PolygonalFaceOfNodes tmpFace( nvec );
1854 dist = GetDistance( &tmpFace, point, closestPnt );
1856 if ( dist < minDist )
1860 if ( closestPnt ) closeP = *closestPnt;
1865 if ( closestPnt ) *closestPnt = closeP;
1869 return 0; // point is inside the volume
1872 //================================================================================
1874 * \brief Returns barycentric coordinates of a point within a triangle.
1875 * A not returned bc2 = 1. - bc0 - bc1.
1876 * The point lies within the triangle if ( bc0 >= 0 && bc1 >= 0 && bc0+bc1 <= 1 )
1878 //================================================================================
1880 void SMESH_MeshAlgos::GetBarycentricCoords( const gp_XY& p,
1887 const double // matrix 2x2
1888 T11 = t0.X()-t2.X(), T12 = t1.X()-t2.X(),
1889 T21 = t0.Y()-t2.Y(), T22 = t1.Y()-t2.Y();
1890 const double Tdet = T11*T22 - T12*T21; // matrix determinant
1891 if ( Abs( Tdet ) < std::numeric_limits<double>::min() )
1897 const double t11 = T22, t12 = -T12, t21 = -T21, t22 = T11;
1899 const double r11 = p.X()-t2.X(), r12 = p.Y()-t2.Y();
1900 // barycentric coordinates: multiply matrix by vector
1901 bc0 = (t11 * r11 + t12 * r12)/Tdet;
1902 bc1 = (t21 * r11 + t22 * r12)/Tdet;
1905 //=======================================================================
1906 //function : FindFaceInSet
1907 //purpose : Return a face having linked nodes n1 and n2 and which is
1908 // - not in avoidSet,
1909 // - in elemSet provided that !elemSet.empty()
1910 // i1 and i2 optionally returns indices of n1 and n2
1911 //=======================================================================
1913 const SMDS_MeshElement*
1914 SMESH_MeshAlgos::FindFaceInSet(const SMDS_MeshNode* n1,
1915 const SMDS_MeshNode* n2,
1916 const TIDSortedElemSet& elemSet,
1917 const TIDSortedElemSet& avoidSet,
1923 const SMDS_MeshElement* face = 0;
1925 SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator(SMDSAbs_Face);
1926 while ( invElemIt->more() && !face ) // loop on inverse faces of n1
1928 const SMDS_MeshElement* elem = invElemIt->next();
1929 if (avoidSet.count( elem ))
1931 if ( !elemSet.empty() && !elemSet.count( elem ))
1934 i1 = elem->GetNodeIndex( n1 );
1935 // find a n2 linked to n1
1936 int nbN = elem->IsQuadratic() ? elem->NbNodes()/2 : elem->NbNodes();
1937 for ( int di = -1; di < 2 && !face; di += 2 )
1939 i2 = (i1+di+nbN) % nbN;
1940 if ( elem->GetNode( i2 ) == n2 )
1943 if ( !face && elem->IsQuadratic())
1945 // analysis for quadratic elements using all nodes
1946 SMDS_NodeIteratorPtr anIter = elem->interlacedNodesIterator();
1947 const SMDS_MeshNode* prevN = static_cast<const SMDS_MeshNode*>( anIter->next() );
1948 for ( i1 = -1, i2 = 0; anIter->more() && !face; i1++, i2++ )
1950 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( anIter->next() );
1951 if ( n1 == prevN && n2 == n )
1955 else if ( n2 == prevN && n1 == n )
1957 face = elem; std::swap( i1, i2 );
1963 if ( n1ind ) *n1ind = i1;
1964 if ( n2ind ) *n2ind = i2;
1968 //================================================================================
1970 * Return sharp edges of faces and non-manifold ones. Optionally adds existing edges.
1972 //================================================================================
1974 std::vector< SMESH_MeshAlgos::Edge >
1975 SMESH_MeshAlgos::FindSharpEdges( SMDS_Mesh* theMesh,
1977 bool theAddExisting )
1979 std::vector< Edge > resultEdges;
1980 if ( !theMesh ) return resultEdges;
1982 typedef std::pair< bool, const SMDS_MeshNode* > TIsSharpAndMedium;
1983 typedef NCollection_DataMap< SMESH_TLink, TIsSharpAndMedium, SMESH_TLink > TLinkSharpMap;
1985 TLinkSharpMap linkIsSharp;
1986 Standard_Integer nbBuckets = FromSmIdType<Standard_Integer>( theMesh->NbFaces() );
1987 if ( nbBuckets > 0 )
1988 linkIsSharp.ReSize( nbBuckets );
1990 TIsSharpAndMedium sharpMedium( true, 0 );
1991 bool & isSharp = sharpMedium.first;
1992 const SMDS_MeshNode* & nMedium = sharpMedium.second;
1994 if ( theAddExisting )
1996 for ( SMDS_EdgeIteratorPtr edgeIt = theMesh->edgesIterator(); edgeIt->more(); )
1998 const SMDS_MeshElement* edge = edgeIt->next();
1999 nMedium = ( edge->IsQuadratic() ) ? edge->GetNode(2) : 0;
2000 linkIsSharp.Bind( SMESH_TLink( edge->GetNode(0), edge->GetNode(1)), sharpMedium );
2004 // check angles between face normals
2006 const double angleCos = Cos( theAngle * M_PI / 180. ), angleCos2 = angleCos * angleCos;
2007 gp_XYZ norm1, norm2;
2008 std::vector< const SMDS_MeshNode* > faceNodes, linkNodes(2);
2009 std::vector<const SMDS_MeshElement *> linkFaces;
2011 int nbSharp = linkIsSharp.Extent();
2012 for ( SMDS_FaceIteratorPtr faceIt = theMesh->facesIterator(); faceIt->more(); )
2014 const SMDS_MeshElement* face = faceIt->next();
2015 size_t nbCorners = face->NbCornerNodes();
2017 faceNodes.assign( face->begin_nodes(), face->end_nodes() );
2018 if ( faceNodes.size() == nbCorners )
2019 faceNodes.resize( nbCorners * 2, 0 );
2021 const SMDS_MeshNode* nPrev = faceNodes[ nbCorners-1 ];
2022 for ( size_t i = 0; i < nbCorners; ++i )
2024 SMESH_TLink link( nPrev, faceNodes[i] );
2025 if ( !linkIsSharp.IsBound( link ))
2027 linkNodes[0] = link.node1();
2028 linkNodes[1] = link.node2();
2030 theMesh->GetElementsByNodes( linkNodes, linkFaces, SMDSAbs_Face );
2033 if ( linkFaces.size() > 2 )
2037 else if ( linkFaces.size() == 2 &&
2038 FaceNormal( linkFaces[0], norm1, /*normalize=*/false ) &&
2039 FaceNormal( linkFaces[1], norm2, /*normalize=*/false ))
2041 double dot = norm1 * norm2; // == cos * |norm1| * |norm2|
2042 if (( dot < 0 ) == ( angleCos < 0 ))
2044 double cos2 = dot * dot / norm1.SquareModulus() / norm2.SquareModulus();
2045 isSharp = ( angleCos < 0 ) ? ( cos2 > angleCos2 ) : ( cos2 < angleCos2 );
2049 isSharp = ( angleCos > 0 );
2052 nMedium = faceNodes[( i-1+nbCorners ) % nbCorners + nbCorners ];
2054 linkIsSharp.Bind( link, sharpMedium );
2058 nPrev = faceNodes[i];
2062 resultEdges.resize( nbSharp );
2063 TLinkSharpMap::Iterator linkIsSharpIter( linkIsSharp );
2064 for ( int i = 0; linkIsSharpIter.More() && i < nbSharp; linkIsSharpIter.Next() )
2066 const SMESH_TLink& link = linkIsSharpIter.Key();
2067 const TIsSharpAndMedium& isSharpMedium = linkIsSharpIter.Value();
2068 if ( isSharpMedium.first )
2070 Edge & edge = resultEdges[ i++ ];
2071 edge._node1 = link.node1();
2072 edge._node2 = link.node2();
2073 edge._medium = isSharpMedium.second;
2080 //================================================================================
2082 * Distribute all faces of the mesh between groups using given edges as group boundaries
2084 //================================================================================
2086 std::vector< std::vector< const SMDS_MeshElement* > >
2087 SMESH_MeshAlgos::SeparateFacesByEdges( SMDS_Mesh* theMesh, const std::vector< Edge >& theEdges )
2089 std::vector< std::vector< const SMDS_MeshElement* > > groups;
2090 if ( !theMesh ) return groups;
2092 // build map of face edges (SMESH_TLink) and their faces
2094 typedef std::vector< const SMDS_MeshElement* > TFaceVec;
2095 typedef NCollection_DataMap< SMESH_TLink, TFaceVec, SMESH_TLink > TFacesByLinks;
2096 TFacesByLinks facesByLink;
2097 Standard_Integer nbBuckets = FromSmIdType<Standard_Integer>( theMesh->NbFaces() );
2098 if ( nbBuckets > 0 )
2099 facesByLink.ReSize( nbBuckets );
2101 std::vector< const SMDS_MeshNode* > faceNodes;
2102 for ( SMDS_FaceIteratorPtr faceIt = theMesh->facesIterator(); faceIt->more(); )
2104 const SMDS_MeshElement* face = faceIt->next();
2105 size_t nbCorners = face->NbCornerNodes();
2107 faceNodes.assign( face->begin_nodes(), face->end_nodes() );
2108 faceNodes.resize( nbCorners + 1 );
2109 faceNodes[ nbCorners ] = faceNodes[0];
2111 face->setIsMarked( false );
2113 for ( size_t i = 0; i < nbCorners; ++i )
2115 SMESH_TLink link( faceNodes[i], faceNodes[i+1] );
2116 TFaceVec* linkFaces = facesByLink.ChangeSeek( link );
2119 linkFaces = facesByLink.Bound( link, TFaceVec() );
2120 linkFaces->reserve(2);
2122 linkFaces->push_back( face );
2126 // remove the given edges from facesByLink map
2128 for ( size_t i = 0; i < theEdges.size(); ++i )
2130 SMESH_TLink link( theEdges[i]._node1, theEdges[i]._node2 );
2131 facesByLink.UnBind( link );
2134 // faces connected via links of facesByLink map form a group
2136 while ( !facesByLink.IsEmpty() )
2138 groups.push_back( TFaceVec() );
2139 TFaceVec & group = groups.back();
2141 group.push_back( TFacesByLinks::Iterator( facesByLink ).Value()[0] );
2142 group.back()->setIsMarked( true );
2144 for ( size_t iF = 0; iF < group.size(); ++iF )
2146 const SMDS_MeshElement* face = group[iF];
2147 size_t nbCorners = face->NbCornerNodes();
2148 faceNodes.assign( face->begin_nodes(), face->end_nodes() );
2149 faceNodes.resize( nbCorners + 1 );
2150 faceNodes[ nbCorners ] = faceNodes[0];
2152 for ( size_t iN = 0; iN < nbCorners; ++iN )
2154 SMESH_TLink link( faceNodes[iN], faceNodes[iN+1] );
2155 if ( const TFaceVec* faces = facesByLink.Seek( link ))
2157 const TFaceVec& faceNeighbors = *faces;
2158 for ( size_t i = 0; i < faceNeighbors.size(); ++i )
2159 if ( !faceNeighbors[i]->isMarked() )
2161 group.push_back( faceNeighbors[i] );
2162 faceNeighbors[i]->setIsMarked( true );
2164 facesByLink.UnBind( link );
2170 // find faces that are alone in its group; they were not in facesByLink
2173 for ( size_t i = 0; i < groups.size(); ++i )
2174 nbInGroups += groups[i].size();
2175 if ( nbInGroups < theMesh->NbFaces() )
2177 for ( SMDS_FaceIteratorPtr faceIt = theMesh->facesIterator(); faceIt->more(); )
2179 const SMDS_MeshElement* face = faceIt->next();
2180 if ( !face->isMarked() )
2182 groups.push_back( TFaceVec() );
2183 groups.back().push_back( face );
2191 //================================================================================
2193 * \brief Calculate normal of a mesh face
2195 //================================================================================
2197 bool SMESH_MeshAlgos::FaceNormal(const SMDS_MeshElement* F, gp_XYZ& normal, bool normalized)
2199 if ( !F || F->GetType() != SMDSAbs_Face )
2202 normal.SetCoord(0,0,0);
2203 int nbNodes = F->NbCornerNodes();
2204 for ( int i = 0; i < nbNodes-2; ++i )
2207 for ( int n = 0; n < 3; ++n )
2209 const SMDS_MeshNode* node = F->GetNode( i + n );
2210 p[n].SetCoord( node->X(), node->Y(), node->Z() );
2212 normal += ( p[2] - p[1] ) ^ ( p[0] - p[1] );
2214 double size2 = normal.SquareModulus();
2215 bool ok = ( size2 > std::numeric_limits<double>::min() * std::numeric_limits<double>::min());
2216 if ( normalized && ok )
2217 normal /= sqrt( size2 );
2222 //================================================================================
2224 * \brief Return nodes common to two elements
2226 //================================================================================
2228 int SMESH_MeshAlgos::NbCommonNodes(const SMDS_MeshElement* e1,
2229 const SMDS_MeshElement* e2)
2232 for ( int i = 0 ; i < e1->NbNodes(); ++i )
2233 nb += ( e2->GetNodeIndex( e1->GetNode( i )) >= 0 );
2237 //================================================================================
2239 * \brief Return nodes common to two elements
2241 //================================================================================
2243 std::vector< const SMDS_MeshNode*> SMESH_MeshAlgos::GetCommonNodes(const SMDS_MeshElement* e1,
2244 const SMDS_MeshElement* e2)
2246 std::vector< const SMDS_MeshNode*> common;
2247 for ( int i = 0 ; i < e1->NbNodes(); ++i )
2248 if ( e2->GetNodeIndex( e1->GetNode( i )) >= 0 )
2249 common.push_back( e1->GetNode( i ));
2253 //================================================================================
2255 * \brief Return true if a node is on a boundary of 2D mesh.
2256 * Optionally returns two neighboring boundary nodes (or more in non-manifold mesh)
2258 //================================================================================
2260 bool SMESH_MeshAlgos::IsOn2DBoundary( const SMDS_MeshNode* theNode,
2261 std::vector< const SMDS_MeshNode*> * theNeibors )
2263 typedef NCollection_DataMap< SMESH_TLink, int, SMESH_TLink > TLinkCountMap;
2264 TLinkCountMap linkCountMap( 10 );
2266 int nbFreeLinks = 0;
2267 for ( SMDS_ElemIteratorPtr fIt = theNode->GetInverseElementIterator(SMDSAbs_Face); fIt->more(); )
2269 const SMDS_MeshElement* face = fIt->next();
2270 const int nbCorners = face->NbCornerNodes();
2272 int iN = face->GetNodeIndex( theNode );
2273 int iPrev = ( iN - 1 + nbCorners ) % nbCorners;
2274 int iNext = ( iN + 1 ) % nbCorners;
2276 for ( int i : { iPrev, iNext } )
2278 SMESH_TLink link( theNode, face->GetNode( i ));
2279 int* count = linkCountMap.ChangeSeek( link );
2280 if ( count ) ++( *count );
2281 else linkCountMap.Bind( link, 1 );
2283 if ( !count ) ++nbFreeLinks;
2290 theNeibors->clear();
2291 theNeibors->reserve( nbFreeLinks );
2292 for ( TLinkCountMap::Iterator linkIt( linkCountMap ); linkIt.More(); linkIt.Next() )
2293 if ( linkIt.Value() == 1 )
2295 theNeibors->push_back( linkIt.Key().node1() );
2296 if ( theNeibors->back() == theNode )
2297 theNeibors->back() = linkIt.Key().node2();
2300 return nbFreeLinks > 0;
2303 //================================================================================
2305 * \brief Return true if node1 encounters first in the face and node2, after
2307 //================================================================================
2309 bool SMESH_MeshAlgos::IsRightOrder( const SMDS_MeshElement* face,
2310 const SMDS_MeshNode* node0,
2311 const SMDS_MeshNode* node1 )
2313 int i0 = face->GetNodeIndex( node0 );
2314 int i1 = face->GetNodeIndex( node1 );
2315 if ( face->IsQuadratic() )
2317 if ( face->IsMediumNode( node0 ))
2319 i0 -= ( face->NbNodes()/2 - 1 );
2324 i1 -= ( face->NbNodes()/2 - 1 );
2329 return ( diff == 1 ) || ( diff == -face->NbNodes()+1 );
2332 //=======================================================================
2334 * \brief Partition given 1D elements into groups of contiguous edges.
2335 * A node where number of meeting edges != 2 is a group end.
2336 * An optional startNode is used to orient groups it belongs to.
2337 * \return a list of edge groups and a list of corresponding node groups.
2338 * If a group is closed, the first and last nodes of the group are same.
2340 //=======================================================================
2342 void SMESH_MeshAlgos::Get1DBranches( SMDS_ElemIteratorPtr theEdgeIt,
2343 TElemGroupVector& theEdgeGroups,
2344 TNodeGroupVector& theNodeGroups,
2345 const SMDS_MeshNode* theStartNode )
2350 // build map of nodes and their adjacent edges
2352 typedef std::vector< const SMDS_MeshNode* > TNodeVec;
2353 typedef std::vector< const SMDS_MeshElement* > TEdgeVec;
2354 typedef NCollection_DataMap< const SMDS_MeshNode*, TEdgeVec, SMESH_Hasher > TEdgesByNodeMap;
2355 TEdgesByNodeMap edgesByNode;
2357 while ( theEdgeIt->more() )
2359 const SMDS_MeshElement* edge = theEdgeIt->next();
2360 if ( edge->GetType() != SMDSAbs_Edge )
2363 const SMDS_MeshNode* nodes[2] = { edge->GetNode(0), edge->GetNode(1) };
2364 for ( int i = 0; i < 2; ++i )
2366 TEdgeVec* nodeEdges = edgesByNode.ChangeSeek( nodes[i] );
2369 nodeEdges = edgesByNode.Bound( nodes[i], TEdgeVec() );
2370 nodeEdges->reserve(2);
2372 nodeEdges->push_back( edge );
2376 if ( edgesByNode.IsEmpty() )
2380 // build edge branches
2382 TElemGroupVector branches(2);
2383 TNodeGroupVector nodeBranches(2);
2385 while ( !edgesByNode.IsEmpty() )
2387 if ( !theStartNode || !edgesByNode.IsBound( theStartNode ))
2389 theStartNode = TEdgesByNodeMap::Iterator( edgesByNode ).Key();
2392 size_t nbBranches = 0;
2393 bool startIsBranchEnd = false;
2395 while ( edgesByNode.IsBound( theStartNode ))
2397 // initialize a new branch
2400 if ( branches.size() < nbBranches )
2402 branches.push_back ( TEdgeVec() );
2403 nodeBranches.push_back( TNodeVec() );
2405 TEdgeVec & branch = branches [ nbBranches - 1 ];
2406 TNodeVec & nodeBranch = nodeBranches[ nbBranches - 1 ];
2410 TEdgeVec& edges = edgesByNode( theStartNode );
2411 startIsBranchEnd = ( edges.size() != 2 );
2414 const SMDS_MeshElement* startEdge = 0;
2415 for ( size_t i = 0; i < edges.size(); ++i )
2417 if ( !startEdge && edges[i] )
2419 startEdge = edges[i];
2422 nbEdges += bool( edges[i] );
2425 edgesByNode.UnBind( theStartNode );
2429 branch.push_back( startEdge );
2431 nodeBranch.push_back( theStartNode );
2432 nodeBranch.push_back( branch.back()->GetNode(0) );
2433 if ( nodeBranch.back() == theStartNode )
2434 nodeBranch.back() = branch.back()->GetNode(1);
2439 bool isBranchEnd = false;
2442 while (( !isBranchEnd ) && ( edgesPtr = edgesByNode.ChangeSeek( nodeBranch.back() )))
2444 TEdgeVec& edges = *edgesPtr;
2446 isBranchEnd = ( edges.size() != 2 );
2448 const SMDS_MeshNode* lastNode = nodeBranch.back();
2450 switch ( edges.size() )
2453 edgesByNode.UnBind( lastNode );
2458 if ( const SMDS_MeshElement* nextEdge = edges[ edges[0] == branch.back() ])
2460 branch.push_back( nextEdge );
2462 const SMDS_MeshNode* nextNode = nextEdge->GetNode(0);
2463 if ( nodeBranch.back() == nextNode )
2464 nextNode = nextEdge->GetNode(1);
2465 nodeBranch.push_back( nextNode );
2467 edgesByNode.UnBind( lastNode );
2473 for ( size_t i = 0; i < edges.size(); ++i )
2475 if ( edges[i] == branch.back() )
2477 nbEdges += bool( edges[i] );
2480 edgesByNode.UnBind( lastNode );
2483 } // while ( edgesByNode.IsBound( theStartNode ))
2486 // put the found branches to the result
2488 if ( nbBranches == 2 && !startIsBranchEnd ) // join two branches starting at the same node
2490 std::reverse( nodeBranches[0].begin(), nodeBranches[0].end() );
2491 nodeBranches[0].pop_back();
2492 nodeBranches[0].reserve( nodeBranches[0].size() + nodeBranches[1].size() );
2493 nodeBranches[0].insert( nodeBranches[0].end(),
2494 nodeBranches[1].begin(), nodeBranches[1].end() );
2496 std::reverse( branches[0].begin(), branches[0].end() );
2497 branches[0].reserve( branches[0].size() + branches[1].size() );
2498 branches[0].insert( branches[0].end(), branches[1].begin(), branches[1].end() );
2500 nodeBranches[1].clear();
2501 branches[1].clear();
2504 for ( size_t i = 0; i < nbBranches; ++i )
2506 if ( branches[i].empty() )
2509 theEdgeGroups.push_back( TEdgeVec() );
2510 theEdgeGroups.back().swap( branches[i] );
2512 theNodeGroups.push_back( TNodeVec() );
2513 theNodeGroups.back().swap( nodeBranches[i] );
2516 } // while ( !edgesByNode.IsEmpty() )
2521 //=======================================================================
2523 * \brief Return SMESH_NodeSearcher
2525 //=======================================================================
2527 SMESH_NodeSearcher* SMESH_MeshAlgos::GetNodeSearcher(SMDS_Mesh& mesh)
2529 return new SMESH_NodeSearcherImpl( &mesh );
2532 //=======================================================================
2534 * \brief Return SMESH_NodeSearcher
2536 //=======================================================================
2538 SMESH_NodeSearcher* SMESH_MeshAlgos::GetNodeSearcher(SMDS_ElemIteratorPtr elemIt)
2540 return new SMESH_NodeSearcherImpl( 0, elemIt );
2543 //=======================================================================
2545 * \brief Return SMESH_ElementSearcher
2547 //=======================================================================
2549 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh& mesh,
2552 return new SMESH_ElementSearcherImpl( mesh, tolerance );
2555 //=======================================================================
2557 * \brief Return SMESH_ElementSearcher acting on a sub-set of elements
2559 //=======================================================================
2561 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh& mesh,
2562 SMDS_ElemIteratorPtr elemIt,
2565 return new SMESH_ElementSearcherImpl( mesh, tolerance, elemIt );