1 // Copyright (C) 2007-2016 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 // This file holds some low level algorithms extracted from SMESH_MeshEditor
27 // to make them accessible from Controls package
29 #include "SMESH_MeshAlgos.hxx"
31 #include "SMDS_FaceOfNodes.hxx"
32 #include "SMDS_LinearEdge.hxx"
33 #include "SMDS_Mesh.hxx"
34 #include "SMDS_PolygonalFaceOfNodes.hxx"
35 #include "SMDS_VolumeTool.hxx"
36 #include "SMESH_OctreeNode.hxx"
38 #include <Utils_SALOME_Exception.hxx>
40 #include <GC_MakeSegment.hxx>
41 #include <GeomAPI_ExtremaCurveCurve.hxx>
42 #include <Geom_Line.hxx>
43 #include <IntAna_IntConicQuad.hxx>
44 #include <IntAna_Quadric.hxx>
53 //=======================================================================
55 * \brief Implementation of search for the node closest to point
57 //=======================================================================
59 struct SMESH_NodeSearcherImpl: public SMESH_NodeSearcher
61 //---------------------------------------------------------------------
65 SMESH_NodeSearcherImpl( const SMDS_Mesh* theMesh = 0,
66 SMDS_ElemIteratorPtr theElemIt = SMDS_ElemIteratorPtr() )
68 myMesh = ( SMDS_Mesh* ) theMesh;
70 TIDSortedNodeSet nodes;
72 SMDS_NodeIteratorPtr nIt = theMesh->nodesIterator(/*idInceasingOrder=*/true);
74 nodes.insert( nodes.end(), nIt->next() );
78 while ( theElemIt->more() )
80 const SMDS_MeshElement* e = theElemIt->next();
81 nodes.insert( e->begin_nodes(), e->end_nodes() );
84 myOctreeNode = new SMESH_OctreeNode(nodes) ;
86 // get max size of a leaf box
87 SMESH_OctreeNode* tree = myOctreeNode;
88 while ( !tree->isLeaf() )
90 SMESH_OctreeNodeIteratorPtr cIt = tree->GetChildrenIterator();
94 myHalfLeafSize = tree->maxSize() / 2.;
97 //---------------------------------------------------------------------
99 * \brief Move node and update myOctreeNode accordingly
101 void MoveNode( const SMDS_MeshNode* node, const gp_Pnt& toPnt )
103 myOctreeNode->UpdateByMoveNode( node, toPnt );
104 myMesh->MoveNode( node, toPnt.X(), toPnt.Y(), toPnt.Z() );
107 //---------------------------------------------------------------------
111 const SMDS_MeshNode* FindClosestTo( const gp_Pnt& thePnt )
113 map<double, const SMDS_MeshNode*> dist2Nodes;
114 myOctreeNode->NodesAround( thePnt.Coord(), dist2Nodes, myHalfLeafSize );
115 if ( !dist2Nodes.empty() )
116 return dist2Nodes.begin()->second;
117 list<const SMDS_MeshNode*> nodes;
118 //myOctreeNode->NodesAround( &tgtNode, &nodes, myHalfLeafSize );
120 double minSqDist = DBL_MAX;
121 if ( nodes.empty() ) // get all nodes of OctreeNode's closest to thePnt
123 // sort leafs by their distance from thePnt
124 typedef map< double, SMESH_OctreeNode* > TDistTreeMap;
125 TDistTreeMap treeMap;
126 list< SMESH_OctreeNode* > treeList;
127 list< SMESH_OctreeNode* >::iterator trIt;
128 treeList.push_back( myOctreeNode );
130 gp_XYZ pointNode( thePnt.X(), thePnt.Y(), thePnt.Z() );
131 bool pointInside = myOctreeNode->isInside( pointNode, myHalfLeafSize );
132 for ( trIt = treeList.begin(); trIt != treeList.end(); ++trIt)
134 SMESH_OctreeNode* tree = *trIt;
135 if ( !tree->isLeaf() ) // put children to the queue
137 if ( pointInside && !tree->isInside( pointNode, myHalfLeafSize )) continue;
138 SMESH_OctreeNodeIteratorPtr cIt = tree->GetChildrenIterator();
139 while ( cIt->more() )
140 treeList.push_back( cIt->next() );
142 else if ( tree->NbNodes() ) // put a tree to the treeMap
144 const Bnd_B3d& box = *tree->getBox();
145 double sqDist = thePnt.SquareDistance( 0.5 * ( box.CornerMin() + box.CornerMax() ));
146 pair<TDistTreeMap::iterator,bool> it_in = treeMap.insert( make_pair( sqDist, tree ));
147 if ( !it_in.second ) // not unique distance to box center
148 treeMap.insert( it_in.first, make_pair( sqDist + 1e-13*treeMap.size(), tree ));
151 // find distance after which there is no sense to check tree's
152 double sqLimit = DBL_MAX;
153 TDistTreeMap::iterator sqDist_tree = treeMap.begin();
154 if ( treeMap.size() > 5 ) {
155 SMESH_OctreeNode* closestTree = sqDist_tree->second;
156 const Bnd_B3d& box = *closestTree->getBox();
157 double limit = sqrt( sqDist_tree->first ) + sqrt ( box.SquareExtent() );
158 sqLimit = limit * limit;
160 // get all nodes from trees
161 for ( ; sqDist_tree != treeMap.end(); ++sqDist_tree) {
162 if ( sqDist_tree->first > sqLimit )
164 SMESH_OctreeNode* tree = sqDist_tree->second;
165 tree->NodesAround( tree->GetNodeIterator()->next(), &nodes );
168 // find closest among nodes
170 const SMDS_MeshNode* closestNode = 0;
171 list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
172 for ( ; nIt != nodes.end(); ++nIt ) {
173 double sqDist = thePnt.SquareDistance( SMESH_TNodeXYZ( *nIt ) );
174 if ( minSqDist > sqDist ) {
182 //---------------------------------------------------------------------
184 * \brief Finds nodes located within a tolerance near a point
186 int FindNearPoint(const gp_Pnt& point,
187 const double tolerance,
188 std::vector< const SMDS_MeshNode* >& foundNodes)
190 myOctreeNode->NodesAround( point.Coord(), foundNodes, tolerance );
191 return foundNodes.size();
194 //---------------------------------------------------------------------
198 ~SMESH_NodeSearcherImpl() { delete myOctreeNode; }
200 //---------------------------------------------------------------------
202 * \brief Return the node tree
204 const SMESH_OctreeNode* getTree() const { return myOctreeNode; }
207 SMESH_OctreeNode* myOctreeNode;
209 double myHalfLeafSize; // max size of a leaf box
212 // ========================================================================
213 namespace // Utils used in SMESH_ElementSearcherImpl::FindElementsByPoint()
215 const int MaxNbElemsInLeaf = 10; // maximal number of elements in a leaf of tree
216 const int MaxLevel = 7; // maximal tree height -> nb terminal boxes: 8^7 = 2097152
217 const double NodeRadius = 1e-9; // to enlarge bnd box of element
219 //=======================================================================
221 * \brief Octal tree of bounding boxes of elements
223 //=======================================================================
225 class ElementBndBoxTree : public SMESH_Octree
229 ElementBndBoxTree(const SMDS_Mesh& mesh,
230 SMDSAbs_ElementType elemType,
231 SMDS_ElemIteratorPtr theElemIt = SMDS_ElemIteratorPtr(),
232 double tolerance = NodeRadius );
233 void getElementsNearPoint( const gp_Pnt& point, vector<const SMDS_MeshElement*>& foundElems );
234 void getElementsNearLine ( const gp_Ax1& line, vector<const SMDS_MeshElement*>& foundElems);
235 void getElementsInSphere ( const gp_XYZ& center,
237 vector<const SMDS_MeshElement*>& foundElems);
238 ElementBndBoxTree* getLeafAtPoint( const gp_XYZ& point );
241 ElementBndBoxTree() {}
242 SMESH_Octree* newChild() const { return new ElementBndBoxTree; }
243 void buildChildrenData();
244 Bnd_B3d* buildRootBox();
246 //!< Bounding box of element
247 struct ElementBox : public Bnd_B3d
249 const SMDS_MeshElement* _element;
251 void init(const SMDS_MeshElement* elem, double tolerance);
253 vector< ElementBox* > _elements;
255 typedef ObjectPool< ElementBox > TElementBoxPool;
257 //!< allocator of ElementBox's and SMESH_TreeLimit
258 struct LimitAndPool : public SMESH_TreeLimit
260 TElementBoxPool _elBoPool;
261 std::vector< ElementBox* > _markedElems;
262 LimitAndPool():SMESH_TreeLimit( MaxLevel, /*minSize=*/0. ) {}
264 LimitAndPool* getLimitAndPool() const
266 SMESH_TreeLimit* limitAndPool = const_cast< SMESH_TreeLimit* >( myLimit );
267 return static_cast< LimitAndPool* >( limitAndPool );
271 //================================================================================
273 * \brief ElementBndBoxTree creation
275 //================================================================================
277 ElementBndBoxTree::ElementBndBoxTree(const SMDS_Mesh& mesh,
278 SMDSAbs_ElementType elemType,
279 SMDS_ElemIteratorPtr theElemIt,
281 :SMESH_Octree( new LimitAndPool() )
283 int nbElems = mesh.GetMeshInfo().NbElements( elemType );
284 _elements.reserve( nbElems );
286 TElementBoxPool& elBoPool = getLimitAndPool()->_elBoPool;
288 SMDS_ElemIteratorPtr elemIt = theElemIt ? theElemIt : mesh.elementsIterator( elemType );
289 while ( elemIt->more() )
291 ElementBox* eb = elBoPool.getNew();
292 eb->init( elemIt->next(), tolerance );
293 _elements.push_back( eb );
298 //================================================================================
300 * \brief Return the maximal box
302 //================================================================================
304 Bnd_B3d* ElementBndBoxTree::buildRootBox()
306 Bnd_B3d* box = new Bnd_B3d;
307 for ( size_t i = 0; i < _elements.size(); ++i )
308 box->Add( *_elements[i] );
312 //================================================================================
314 * \brief Redistrubute element boxes among children
316 //================================================================================
318 void ElementBndBoxTree::buildChildrenData()
320 for ( size_t i = 0; i < _elements.size(); ++i )
322 for (int j = 0; j < 8; j++)
324 if ( !_elements[i]->IsOut( *myChildren[j]->getBox() ))
325 ((ElementBndBoxTree*)myChildren[j])->_elements.push_back( _elements[i]);
328 //_size = _elements.size();
329 SMESHUtils::FreeVector( _elements ); // = _elements.clear() + free memory
331 for (int j = 0; j < 8; j++)
333 ElementBndBoxTree* child = static_cast<ElementBndBoxTree*>( myChildren[j]);
334 if ((int) child->_elements.size() <= MaxNbElemsInLeaf )
335 child->myIsLeaf = true;
337 if ( child->isLeaf() && child->_elements.capacity() > child->_elements.size() )
338 SMESHUtils::CompactVector( child->_elements );
342 //================================================================================
344 * \brief Return elements which can include the point
346 //================================================================================
348 void ElementBndBoxTree::getElementsNearPoint( const gp_Pnt& point,
349 vector<const SMDS_MeshElement*>& foundElems)
351 if ( getBox()->IsOut( point.XYZ() ))
356 LimitAndPool* pool = getLimitAndPool();
358 for ( size_t i = 0; i < _elements.size(); ++i )
359 if ( !_elements[i]->IsOut( point.XYZ() ) &&
360 !_elements[i]->_isMarked )
362 foundElems.push_back( _elements[i]->_element );
363 _elements[i]->_isMarked = true;
364 pool->_markedElems.push_back( _elements[i] );
369 for (int i = 0; i < 8; i++)
370 ((ElementBndBoxTree*) myChildren[i])->getElementsNearPoint( point, foundElems );
374 LimitAndPool* pool = getLimitAndPool();
375 for ( size_t i = 0; i < pool->_markedElems.size(); ++i )
376 pool->_markedElems[i]->_isMarked = false;
377 pool->_markedElems.clear();
382 //================================================================================
384 * \brief Return elements which can be intersected by the line
386 //================================================================================
388 void ElementBndBoxTree::getElementsNearLine( const gp_Ax1& line,
389 vector<const SMDS_MeshElement*>& foundElems)
391 if ( getBox()->IsOut( line ))
396 LimitAndPool* pool = getLimitAndPool();
398 for ( size_t i = 0; i < _elements.size(); ++i )
399 if ( !_elements[i]->IsOut( line ) &&
400 !_elements[i]->_isMarked )
402 foundElems.push_back( _elements[i]->_element );
403 _elements[i]->_isMarked = true;
404 pool->_markedElems.push_back( _elements[i] );
409 for (int i = 0; i < 8; i++)
410 ((ElementBndBoxTree*) myChildren[i])->getElementsNearLine( line, foundElems );
414 LimitAndPool* pool = getLimitAndPool();
415 for ( size_t i = 0; i < pool->_markedElems.size(); ++i )
416 pool->_markedElems[i]->_isMarked = false;
417 pool->_markedElems.clear();
422 //================================================================================
424 * \brief Return elements from leaves intersecting the sphere
426 //================================================================================
428 void ElementBndBoxTree::getElementsInSphere ( const gp_XYZ& center,
430 vector<const SMDS_MeshElement*>& foundElems)
432 if ( getBox()->IsOut( center, radius ))
437 LimitAndPool* pool = getLimitAndPool();
439 for ( size_t i = 0; i < _elements.size(); ++i )
440 if ( !_elements[i]->IsOut( center, radius ) &&
441 !_elements[i]->_isMarked )
443 foundElems.push_back( _elements[i]->_element );
444 _elements[i]->_isMarked = true;
445 pool->_markedElems.push_back( _elements[i] );
450 for (int i = 0; i < 8; i++)
451 ((ElementBndBoxTree*) myChildren[i])->getElementsInSphere( center, radius, foundElems );
455 LimitAndPool* pool = getLimitAndPool();
456 for ( size_t i = 0; i < pool->_markedElems.size(); ++i )
457 pool->_markedElems[i]->_isMarked = false;
458 pool->_markedElems.clear();
463 //================================================================================
465 * \brief Return a leaf including a point
467 //================================================================================
469 ElementBndBoxTree* ElementBndBoxTree::getLeafAtPoint( const gp_XYZ& point )
471 if ( getBox()->IsOut( point ))
480 for (int i = 0; i < 8; i++)
481 if ( ElementBndBoxTree* l = ((ElementBndBoxTree*) myChildren[i])->getLeafAtPoint( point ))
487 //================================================================================
489 * \brief Construct the element box
491 //================================================================================
493 void ElementBndBoxTree::ElementBox::init(const SMDS_MeshElement* elem, double tolerance)
497 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
498 while ( nIt->more() )
499 Add( SMESH_NodeXYZ( nIt->next() ));
500 Enlarge( tolerance );
505 //=======================================================================
507 * \brief Implementation of search for the elements by point and
508 * of classification of point in 2D mesh
510 //=======================================================================
512 SMESH_ElementSearcher::~SMESH_ElementSearcher()
516 struct SMESH_ElementSearcherImpl: public SMESH_ElementSearcher
519 SMDS_ElemIteratorPtr _meshPartIt;
520 ElementBndBoxTree* _ebbTree [SMDSAbs_NbElementTypes];
521 int _ebbTreeHeight[SMDSAbs_NbElementTypes];
522 SMESH_NodeSearcherImpl* _nodeSearcher;
523 SMDSAbs_ElementType _elementType;
525 bool _outerFacesFound;
526 set<const SMDS_MeshElement*> _outerFaces; // empty means "no internal faces at all"
528 SMESH_ElementSearcherImpl( SMDS_Mesh& mesh,
530 SMDS_ElemIteratorPtr elemIt=SMDS_ElemIteratorPtr())
531 : _mesh(&mesh),_meshPartIt(elemIt),_nodeSearcher(0),_tolerance(tol),_outerFacesFound(false)
533 for ( int i = 0; i < SMDSAbs_NbElementTypes; ++i )
536 _ebbTreeHeight[i] = -1;
538 _elementType = SMDSAbs_All;
540 virtual ~SMESH_ElementSearcherImpl()
542 for ( int i = 0; i < SMDSAbs_NbElementTypes; ++i )
544 delete _ebbTree[i]; _ebbTree[i] = NULL;
546 if ( _nodeSearcher ) delete _nodeSearcher; _nodeSearcher = 0;
548 virtual int FindElementsByPoint(const gp_Pnt& point,
549 SMDSAbs_ElementType type,
550 vector< const SMDS_MeshElement* >& foundElements);
551 virtual TopAbs_State GetPointState(const gp_Pnt& point);
552 virtual const SMDS_MeshElement* FindClosestTo( const gp_Pnt& point,
553 SMDSAbs_ElementType type );
555 virtual void GetElementsNearLine( const gp_Ax1& line,
556 SMDSAbs_ElementType type,
557 vector< const SMDS_MeshElement* >& foundElems);
558 virtual void GetElementsInSphere( const gp_XYZ& center,
560 SMDSAbs_ElementType type,
561 vector< const SMDS_MeshElement* >& foundElems);
562 virtual gp_XYZ Project(const gp_Pnt& point,
563 SMDSAbs_ElementType type,
564 const SMDS_MeshElement** closestElem);
565 double getTolerance();
566 bool getIntersParamOnLine(const gp_Lin& line, const SMDS_MeshElement* face,
567 const double tolerance, double & param);
568 void findOuterBoundary(const SMDS_MeshElement* anyOuterFace);
569 bool isOuterBoundary(const SMDS_MeshElement* face) const
571 return _outerFaces.empty() || _outerFaces.count(face);
575 if ( _ebbTreeHeight[ _elementType ] < 0 )
576 _ebbTreeHeight[ _elementType ] = _ebbTree[ _elementType ]->getHeight();
577 return _ebbTreeHeight[ _elementType ];
580 struct TInters //!< data of intersection of the line and the mesh face (used in GetPointState())
582 const SMDS_MeshElement* _face;
584 bool _coincides; //!< the line lays in face plane
585 TInters(const SMDS_MeshElement* face, const gp_Vec& faceNorm, bool coinc=false)
586 : _face(face), _faceNorm( faceNorm ), _coincides( coinc ) {}
588 struct TFaceLink //!< link and faces sharing it (used in findOuterBoundary())
591 TIDSortedElemSet _faces;
592 TFaceLink( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshElement* face)
593 : _link( n1, n2 ), _faces( &face, &face + 1) {}
597 ostream& operator<< (ostream& out, const SMESH_ElementSearcherImpl::TInters& i)
599 return out << "TInters(face=" << ( i._face ? i._face->GetID() : 0)
600 << ", _coincides="<<i._coincides << ")";
603 //=======================================================================
605 * \brief define tolerance for search
607 //=======================================================================
609 double SMESH_ElementSearcherImpl::getTolerance()
611 if ( _tolerance < 0 )
613 const SMDS_MeshInfo& meshInfo = _mesh->GetMeshInfo();
616 if ( _nodeSearcher && meshInfo.NbNodes() > 1 )
618 double boxSize = _nodeSearcher->getTree()->maxSize();
619 _tolerance = 1e-8 * boxSize/* / meshInfo.NbNodes()*/;
621 else if ( _ebbTree[_elementType] && meshInfo.NbElements() > 0 )
623 double boxSize = _ebbTree[_elementType]->maxSize();
624 _tolerance = 1e-8 * boxSize/* / meshInfo.NbElements()*/;
626 if ( _tolerance == 0 )
628 // define tolerance by size of a most complex element
629 int complexType = SMDSAbs_Volume;
630 while ( complexType > SMDSAbs_All &&
631 meshInfo.NbElements( SMDSAbs_ElementType( complexType )) < 1 )
633 if ( complexType == SMDSAbs_All ) return 0; // empty mesh
635 if ( complexType == int( SMDSAbs_Node ))
637 SMDS_NodeIteratorPtr nodeIt = _mesh->nodesIterator();
639 if ( meshInfo.NbNodes() > 2 )
640 elemSize = SMESH_TNodeXYZ( nodeIt->next() ).Distance( nodeIt->next() );
644 SMDS_ElemIteratorPtr elemIt = _mesh->elementsIterator( SMDSAbs_ElementType( complexType ));
645 const SMDS_MeshElement* elem = elemIt->next();
646 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
647 SMESH_TNodeXYZ n1( nodeIt->next() );
649 while ( nodeIt->more() )
651 double dist = n1.Distance( static_cast<const SMDS_MeshNode*>( nodeIt->next() ));
652 elemSize = max( dist, elemSize );
655 _tolerance = 1e-4 * elemSize;
661 //================================================================================
663 * \brief Find intersection of the line and an edge of face and return parameter on line
665 //================================================================================
667 bool SMESH_ElementSearcherImpl::getIntersParamOnLine(const gp_Lin& line,
668 const SMDS_MeshElement* face,
675 GeomAPI_ExtremaCurveCurve anExtCC;
676 Handle(Geom_Curve) lineCurve = new Geom_Line( line );
678 int nbNodes = face->IsQuadratic() ? face->NbNodes()/2 : face->NbNodes();
679 for ( int i = 0; i < nbNodes && nbInts < 2; ++i )
681 GC_MakeSegment edge( SMESH_TNodeXYZ( face->GetNode( i )),
682 SMESH_TNodeXYZ( face->GetNode( (i+1)%nbNodes) ));
683 anExtCC.Init( lineCurve, edge.Value() );
684 if ( anExtCC.NbExtrema() > 0 && anExtCC.LowerDistance() <= tol)
686 Standard_Real pl, pe;
687 anExtCC.LowerDistanceParameters( pl, pe );
693 if ( nbInts > 0 ) param /= nbInts;
696 //================================================================================
698 * \brief Find all faces belonging to the outer boundary of mesh
700 //================================================================================
702 void SMESH_ElementSearcherImpl::findOuterBoundary(const SMDS_MeshElement* outerFace)
704 if ( _outerFacesFound ) return;
706 // Collect all outer faces by passing from one outer face to another via their links
707 // and BTW find out if there are internal faces at all.
709 // checked links and links where outer boundary meets internal one
710 set< SMESH_TLink > visitedLinks, seamLinks;
712 // links to treat with already visited faces sharing them
713 list < TFaceLink > startLinks;
715 // load startLinks with the first outerFace
716 startLinks.push_back( TFaceLink( outerFace->GetNode(0), outerFace->GetNode(1), outerFace));
717 _outerFaces.insert( outerFace );
719 TIDSortedElemSet emptySet;
720 while ( !startLinks.empty() )
722 const SMESH_TLink& link = startLinks.front()._link;
723 TIDSortedElemSet& faces = startLinks.front()._faces;
725 outerFace = *faces.begin();
726 // find other faces sharing the link
727 const SMDS_MeshElement* f;
728 while (( f = SMESH_MeshAlgos::FindFaceInSet(link.node1(), link.node2(), emptySet, faces )))
731 // select another outer face among the found
732 const SMDS_MeshElement* outerFace2 = 0;
733 if ( faces.size() == 2 )
735 outerFace2 = (outerFace == *faces.begin() ? *faces.rbegin() : *faces.begin());
737 else if ( faces.size() > 2 )
739 seamLinks.insert( link );
741 // link direction within the outerFace
742 gp_Vec n1n2( SMESH_TNodeXYZ( link.node1()),
743 SMESH_TNodeXYZ( link.node2()));
744 int i1 = outerFace->GetNodeIndex( link.node1() );
745 int i2 = outerFace->GetNodeIndex( link.node2() );
746 bool rev = ( abs(i2-i1) == 1 ? i1 > i2 : i2 > i1 );
747 if ( rev ) n1n2.Reverse();
749 gp_XYZ ofNorm, fNorm;
750 if ( SMESH_MeshAlgos::FaceNormal( outerFace, ofNorm, /*normalized=*/false ))
752 // direction from the link inside outerFace
753 gp_Vec dirInOF = gp_Vec( ofNorm ) ^ n1n2;
754 // sort all other faces by angle with the dirInOF
755 map< double, const SMDS_MeshElement* > angle2Face;
756 set< const SMDS_MeshElement*, TIDCompare >::const_iterator face = faces.begin();
757 for ( ; face != faces.end(); ++face )
759 if ( *face == outerFace ) continue;
760 if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false ))
762 gp_Vec dirInF = gp_Vec( fNorm ) ^ n1n2;
763 double angle = dirInOF.AngleWithRef( dirInF, n1n2 );
764 if ( angle < 0 ) angle += 2. * M_PI;
765 angle2Face.insert( make_pair( angle, *face ));
767 if ( !angle2Face.empty() )
768 outerFace2 = angle2Face.begin()->second;
771 // store the found outer face and add its links to continue searching from
774 _outerFaces.insert( outerFace2 );
775 int nbNodes = outerFace2->NbCornerNodes();
776 for ( int i = 0; i < nbNodes; ++i )
778 SMESH_TLink link2( outerFace2->GetNode(i), outerFace2->GetNode((i+1)%nbNodes));
779 if ( visitedLinks.insert( link2 ).second )
780 startLinks.push_back( TFaceLink( link2.node1(), link2.node2(), outerFace2 ));
783 startLinks.pop_front();
785 _outerFacesFound = true;
787 if ( !seamLinks.empty() )
789 // There are internal boundaries touching the outher one,
790 // find all faces of internal boundaries in order to find
791 // faces of boundaries of holes, if any.
800 //=======================================================================
802 * \brief Find elements of given type where the given point is IN or ON.
803 * Returns nb of found elements and elements them-selves.
805 * 'ALL' type means elements of any type excluding nodes, balls and 0D elements
807 //=======================================================================
809 int SMESH_ElementSearcherImpl::
810 FindElementsByPoint(const gp_Pnt& point,
811 SMDSAbs_ElementType type,
812 vector< const SMDS_MeshElement* >& foundElements)
814 foundElements.clear();
817 double tolerance = getTolerance();
819 // =================================================================================
820 if ( type == SMDSAbs_Node || type == SMDSAbs_0DElement || type == SMDSAbs_Ball)
822 if ( !_nodeSearcher )
825 _nodeSearcher = new SMESH_NodeSearcherImpl( 0, _meshPartIt );
827 _nodeSearcher = new SMESH_NodeSearcherImpl( _mesh );
829 std::vector< const SMDS_MeshNode* > foundNodes;
830 _nodeSearcher->FindNearPoint( point, tolerance, foundNodes );
832 if ( type == SMDSAbs_Node )
834 foundElements.assign( foundNodes.begin(), foundNodes.end() );
838 for ( size_t i = 0; i < foundNodes.size(); ++i )
840 SMDS_ElemIteratorPtr elemIt = foundNodes[i]->GetInverseElementIterator( type );
841 while ( elemIt->more() )
842 foundElements.push_back( elemIt->next() );
846 // =================================================================================
847 else // elements more complex than 0D
849 if ( !_ebbTree[type] )
851 _ebbTree[_elementType] = new ElementBndBoxTree( *_mesh, type, _meshPartIt, tolerance );
853 vector< const SMDS_MeshElement* > suspectElems;
854 _ebbTree[ type ]->getElementsNearPoint( point, suspectElems );
855 vector< const SMDS_MeshElement* >::iterator elem = suspectElems.begin();
856 for ( ; elem != suspectElems.end(); ++elem )
857 if ( !SMESH_MeshAlgos::IsOut( *elem, point, tolerance ))
858 foundElements.push_back( *elem );
860 return foundElements.size();
863 //=======================================================================
865 * \brief Find an element of given type most close to the given point
867 * WARNING: Only face search is implemeneted so far
869 //=======================================================================
871 const SMDS_MeshElement*
872 SMESH_ElementSearcherImpl::FindClosestTo( const gp_Pnt& point,
873 SMDSAbs_ElementType type )
875 const SMDS_MeshElement* closestElem = 0;
878 if ( type == SMDSAbs_Face ||
879 type == SMDSAbs_Volume ||
880 type == SMDSAbs_Edge )
882 ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
884 ebbTree = new ElementBndBoxTree( *_mesh, type, _meshPartIt );
886 vector<const SMDS_MeshElement*> suspectElems;
887 ebbTree->getElementsNearPoint( point, suspectElems );
889 if ( suspectElems.empty() && ebbTree->maxSize() > 0 )
891 gp_Pnt boxCenter = 0.5 * ( ebbTree->getBox()->CornerMin() +
892 ebbTree->getBox()->CornerMax() );
894 if ( ebbTree->getBox()->IsOut( point.XYZ() ))
895 radius = point.Distance( boxCenter ) - 0.5 * ebbTree->maxSize();
897 radius = ebbTree->maxSize() / pow( 2., getTreeHeight()) / 2;
898 while ( suspectElems.empty() )
900 ebbTree->getElementsInSphere( point.XYZ(), radius, suspectElems );
904 double minDist = std::numeric_limits<double>::max();
905 multimap< double, const SMDS_MeshElement* > dist2face;
906 vector<const SMDS_MeshElement*>::iterator elem = suspectElems.begin();
907 for ( ; elem != suspectElems.end(); ++elem )
909 double dist = SMESH_MeshAlgos::GetDistance( *elem, point );
910 if ( dist < minDist + 1e-10)
913 dist2face.insert( dist2face.begin(), make_pair( dist, *elem ));
916 if ( !dist2face.empty() )
918 multimap< double, const SMDS_MeshElement* >::iterator d2f = dist2face.begin();
919 closestElem = d2f->second;
920 // if there are several elements at the same distance, select one
921 // with GC closest to the point
922 typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
923 double minDistToGC = 0;
924 for ( ++d2f; d2f != dist2face.end() && fabs( d2f->first - minDist ) < 1e-10; ++d2f )
926 if ( minDistToGC == 0 )
929 gc = accumulate( TXyzIterator(closestElem->nodesIterator()),
930 TXyzIterator(), gc ) / closestElem->NbNodes();
931 minDistToGC = point.SquareDistance( gc );
934 gc = accumulate( TXyzIterator( d2f->second->nodesIterator()),
935 TXyzIterator(), gc ) / d2f->second->NbNodes();
936 double d = point.SquareDistance( gc );
937 if ( d < minDistToGC )
940 closestElem = d2f->second;
943 // cout << "FindClosestTo( " <<point.X()<<", "<<point.Y()<<", "<<point.Z()<<" ) FACE "
944 // <<closestElem->GetID() << " DIST " << minDist << endl;
949 // NOT IMPLEMENTED SO FAR
955 //================================================================================
957 * \brief Classify the given point in the closed 2D mesh
959 //================================================================================
961 TopAbs_State SMESH_ElementSearcherImpl::GetPointState(const gp_Pnt& point)
963 _elementType = SMDSAbs_Face;
965 double tolerance = getTolerance();
967 ElementBndBoxTree*& ebbTree = _ebbTree[ SMDSAbs_Face ];
969 ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
971 // Algo: analyse transition of a line starting at the point through mesh boundary;
972 // try three lines parallel to axis of the coordinate system and perform rough
973 // analysis. If solution is not clear perform thorough analysis.
975 const int nbAxes = 3;
976 gp_Dir axisDir[ nbAxes ] = { gp::DX(), gp::DY(), gp::DZ() };
977 map< double, TInters > paramOnLine2TInters[ nbAxes ];
978 list< TInters > tangentInters[ nbAxes ]; // of faces whose plane includes the line
979 multimap< int, int > nbInt2Axis; // to find the simplest case
980 for ( int axis = 0; axis < nbAxes; ++axis )
982 gp_Ax1 lineAxis( point, axisDir[axis]);
983 gp_Lin line ( lineAxis );
985 vector<const SMDS_MeshElement*> suspectFaces; // faces possibly intersecting the line
986 ebbTree->getElementsNearLine( lineAxis, suspectFaces );
988 // Intersect faces with the line
990 map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
991 vector<const SMDS_MeshElement*>::iterator face = suspectFaces.begin();
992 for ( ; face != suspectFaces.end(); ++face )
996 if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false)) continue;
997 gp_Pln facePlane( SMESH_TNodeXYZ( (*face)->GetNode(0)), fNorm );
999 // perform intersection
1000 IntAna_IntConicQuad intersection( line, IntAna_Quadric( facePlane ));
1001 if ( !intersection.IsDone() )
1003 if ( intersection.IsInQuadric() )
1005 tangentInters[ axis ].push_back( TInters( *face, fNorm, true ));
1007 else if ( ! intersection.IsParallel() && intersection.NbPoints() > 0 )
1009 double tol = 1e-4 * Sqrt( fNorm.Modulus() );
1010 gp_Pnt intersectionPoint = intersection.Point(1);
1011 if ( !SMESH_MeshAlgos::IsOut( *face, intersectionPoint, tol ))
1012 u2inters.insert(make_pair( intersection.ParamOnConic(1), TInters( *face, fNorm )));
1015 // Analyse intersections roughly
1017 int nbInter = u2inters.size();
1021 double f = u2inters.begin()->first, l = u2inters.rbegin()->first;
1022 if ( nbInter == 1 ) // not closed mesh
1023 return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
1025 if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
1028 if ( (f<0) == (l<0) )
1031 int nbIntBeforePoint = std::distance( u2inters.begin(), u2inters.lower_bound(0));
1032 int nbIntAfterPoint = nbInter - nbIntBeforePoint;
1033 if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
1036 nbInt2Axis.insert( make_pair( min( nbIntBeforePoint, nbIntAfterPoint ), axis ));
1038 if ( _outerFacesFound ) break; // pass to thorough analysis
1040 } // three attempts - loop on CS axes
1042 // Analyse intersections thoroughly.
1043 // We make two loops maximum, on the first one we only exclude touching intersections,
1044 // on the second, if situation is still unclear, we gather and use information on
1045 // position of faces (internal or outer). If faces position is already gathered,
1046 // we make the second loop right away.
1048 for ( int hasPositionInfo = _outerFacesFound; hasPositionInfo < 2; ++hasPositionInfo )
1050 multimap< int, int >::const_iterator nb_axis = nbInt2Axis.begin();
1051 for ( ; nb_axis != nbInt2Axis.end(); ++nb_axis )
1053 int axis = nb_axis->second;
1054 map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
1056 gp_Ax1 lineAxis( point, axisDir[axis]);
1057 gp_Lin line ( lineAxis );
1059 // add tangent intersections to u2inters
1061 list< TInters >::const_iterator tgtInt = tangentInters[ axis ].begin();
1062 for ( ; tgtInt != tangentInters[ axis ].end(); ++tgtInt )
1063 if ( getIntersParamOnLine( line, tgtInt->_face, tolerance, param ))
1064 u2inters.insert(make_pair( param, *tgtInt ));
1065 tangentInters[ axis ].clear();
1067 // Count intersections before and after the point excluding touching ones.
1068 // If hasPositionInfo we count intersections of outer boundary only
1070 int nbIntBeforePoint = 0, nbIntAfterPoint = 0;
1071 double f = numeric_limits<double>::max(), l = -numeric_limits<double>::max();
1072 map< double, TInters >::iterator u_int1 = u2inters.begin(), u_int2 = u_int1;
1073 bool ok = ! u_int1->second._coincides;
1074 while ( ok && u_int1 != u2inters.end() )
1076 double u = u_int1->first;
1077 bool touchingInt = false;
1078 if ( ++u_int2 != u2inters.end() )
1080 // skip intersections at the same point (if the line passes through edge or node)
1082 while ( u_int2 != u2inters.end() && fabs( u_int2->first - u ) < tolerance )
1088 // skip tangent intersections
1090 if ( u_int2 != u2inters.end() )
1092 const SMDS_MeshElement* prevFace = u_int1->second._face;
1093 while ( ok && u_int2->second._coincides )
1095 if ( SMESH_MeshAlgos::GetCommonNodes(prevFace , u_int2->second._face).empty() )
1101 ok = ( u_int2 != u2inters.end() );
1107 // skip intersections at the same point after tangent intersections
1110 double u2 = u_int2->first;
1112 while ( u_int2 != u2inters.end() && fabs( u_int2->first - u2 ) < tolerance )
1118 // decide if we skipped a touching intersection
1119 if ( nbSamePnt + nbTgt > 0 )
1121 double minDot = numeric_limits<double>::max(), maxDot = -numeric_limits<double>::max();
1122 map< double, TInters >::iterator u_int = u_int1;
1123 for ( ; u_int != u_int2; ++u_int )
1125 if ( u_int->second._coincides ) continue;
1126 double dot = u_int->second._faceNorm * line.Direction();
1127 if ( dot > maxDot ) maxDot = dot;
1128 if ( dot < minDot ) minDot = dot;
1130 touchingInt = ( minDot*maxDot < 0 );
1135 if ( !hasPositionInfo || isOuterBoundary( u_int1->second._face ))
1146 u_int1 = u_int2; // to next intersection
1148 } // loop on intersections with one line
1152 if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
1155 if ( nbIntBeforePoint == 0 || nbIntAfterPoint == 0)
1158 if ( nbIntBeforePoint + nbIntAfterPoint == 1 ) // not closed mesh
1159 return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
1161 if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
1164 if ( (f<0) == (l<0) )
1167 if ( hasPositionInfo )
1168 return nbIntBeforePoint % 2 ? TopAbs_IN : TopAbs_OUT;
1170 } // loop on intersections of the tree lines - thorough analysis
1172 if ( !hasPositionInfo )
1174 // gather info on faces position - is face in the outer boundary or not
1175 map< double, TInters > & u2inters = paramOnLine2TInters[ 0 ];
1176 findOuterBoundary( u2inters.begin()->second._face );
1179 } // two attempts - with and w/o faces position info in the mesh
1181 return TopAbs_UNKNOWN;
1184 //=======================================================================
1186 * \brief Return elements possibly intersecting the line
1188 //=======================================================================
1190 void SMESH_ElementSearcherImpl::GetElementsNearLine( const gp_Ax1& line,
1191 SMDSAbs_ElementType type,
1192 vector< const SMDS_MeshElement* >& foundElems)
1194 _elementType = type;
1195 ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
1197 ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
1199 ebbTree->getElementsNearLine( line, foundElems );
1202 //=======================================================================
1204 * Return elements whose bounding box intersects a sphere
1206 //=======================================================================
1208 void SMESH_ElementSearcherImpl::GetElementsInSphere( const gp_XYZ& center,
1209 const double radius,
1210 SMDSAbs_ElementType type,
1211 vector< const SMDS_MeshElement* >& foundElems)
1213 _elementType = type;
1214 ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
1216 ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
1218 ebbTree->getElementsInSphere( center, radius, foundElems );
1221 //=======================================================================
1223 * \brief Return a projection of a given point to a mesh.
1224 * Optionally return the closest element
1226 //=======================================================================
1228 gp_XYZ SMESH_ElementSearcherImpl::Project(const gp_Pnt& point,
1229 SMDSAbs_ElementType type,
1230 const SMDS_MeshElement** closestElem)
1232 _elementType = type;
1233 if ( _mesh->GetMeshInfo().NbElements( _elementType ) == 0 )
1234 throw SALOME_Exception( LOCALIZED( "No elements of given type in the mesh" ));
1236 ElementBndBoxTree*& ebbTree = _ebbTree[ _elementType ];
1238 ebbTree = new ElementBndBoxTree( *_mesh, _elementType );
1240 gp_XYZ p = point.XYZ();
1241 ElementBndBoxTree* ebbLeaf = ebbTree->getLeafAtPoint( p );
1242 const Bnd_B3d* box = ebbLeaf->getBox();
1243 double radius = ( box->CornerMax() - box->CornerMin() ).Modulus();
1245 vector< const SMDS_MeshElement* > elems;
1246 ebbTree->getElementsInSphere( p, radius, elems );
1247 while ( elems.empty() )
1250 ebbTree->getElementsInSphere( p, radius, elems );
1252 gp_XYZ proj, bestProj;
1253 const SMDS_MeshElement* elem = 0;
1254 double minDist = 2 * radius;
1255 for ( size_t i = 0; i < elems.size(); ++i )
1257 double d = SMESH_MeshAlgos::GetDistance( elems[i], p, &proj );
1265 if ( closestElem ) *closestElem = elem;
1270 //=======================================================================
1272 * \brief Return true if the point is IN or ON of the element
1274 //=======================================================================
1276 bool SMESH_MeshAlgos::IsOut( const SMDS_MeshElement* element, const gp_Pnt& point, double tol )
1278 if ( element->GetType() == SMDSAbs_Volume)
1280 return SMDS_VolumeTool( element ).IsOut( point.X(), point.Y(), point.Z(), tol );
1283 // get ordered nodes
1285 vector< SMESH_TNodeXYZ > xyz; xyz.reserve( element->NbNodes()+1 );
1287 SMDS_ElemIteratorPtr nodeIt = element->interlacedNodesElemIterator();
1288 for ( int i = 0; nodeIt->more(); ++i )
1289 xyz.push_back( SMESH_TNodeXYZ( nodeIt->next() ));
1291 int i, nbNodes = (int) xyz.size(); // central node of biquadratic is missing
1293 if ( element->GetType() == SMDSAbs_Face ) // --------------------------------------------------
1295 // compute face normal
1296 gp_Vec faceNorm(0,0,0);
1297 xyz.push_back( xyz.front() );
1298 for ( i = 0; i < nbNodes; ++i )
1300 gp_Vec edge1( xyz[i+1], xyz[i]);
1301 gp_Vec edge2( xyz[i+1], xyz[(i+2)%nbNodes] );
1302 faceNorm += edge1 ^ edge2;
1304 double fNormSize = faceNorm.Magnitude();
1305 if ( fNormSize <= tol )
1307 // degenerated face: point is out if it is out of all face edges
1308 for ( i = 0; i < nbNodes; ++i )
1310 SMDS_LinearEdge edge( xyz[i]._node, xyz[i+1]._node );
1311 if ( !IsOut( &edge, point, tol ))
1316 faceNorm /= fNormSize;
1318 // check if the point lays on face plane
1319 gp_Vec n2p( xyz[0], point );
1320 double dot = n2p * faceNorm;
1321 if ( Abs( dot ) > tol ) // not on face plane
1324 if ( nbNodes > 3 ) // maybe the face is not planar
1326 double elemThick = 0;
1327 for ( i = 1; i < nbNodes; ++i )
1329 gp_Vec n2n( xyz[0], xyz[i] );
1330 elemThick = Max( elemThick, Abs( n2n * faceNorm ));
1332 isOut = Abs( dot ) > elemThick + tol;
1338 // check if point is out of face boundary:
1339 // define it by closest transition of a ray point->infinity through face boundary
1340 // on the face plane.
1341 // First, find normal of a plane perpendicular to face plane, to be used as a cutting tool
1342 // to find intersections of the ray with the boundary.
1344 gp_Vec plnNorm = ray ^ faceNorm;
1345 double n2pSize = plnNorm.Magnitude();
1346 if ( n2pSize <= tol ) return false; // point coincides with the first node
1347 if ( n2pSize * n2pSize > fNormSize * 100 ) return true; // point is very far
1349 // for each node of the face, compute its signed distance to the cutting plane
1350 vector<double> dist( nbNodes + 1);
1351 for ( i = 0; i < nbNodes; ++i )
1353 gp_Vec n2p( xyz[i], point );
1354 dist[i] = n2p * plnNorm;
1356 dist.back() = dist.front();
1357 // find the closest intersection
1359 double rClosest = 0, distClosest = 1e100;
1361 for ( i = 0; i < nbNodes; ++i )
1364 if ( fabs( dist[i] ) < tol )
1366 else if ( fabs( dist[i+1]) < tol )
1368 else if ( dist[i] * dist[i+1] < 0 )
1369 r = dist[i] / ( dist[i] - dist[i+1] );
1371 continue; // no intersection
1372 gp_Pnt pInt = xyz[i] * (1.-r) + xyz[i+1] * r;
1373 gp_Vec p2int( point, pInt);
1374 double intDist = p2int.SquareMagnitude();
1375 if ( intDist < distClosest )
1380 distClosest = intDist;
1384 return true; // no intesections - out
1386 // analyse transition
1387 gp_Vec edge( xyz[iClosest], xyz[iClosest+1] );
1388 gp_Vec edgeNorm = -( edge ^ faceNorm ); // normal to intersected edge pointing out of face
1389 gp_Vec p2int ( point, pClosest );
1390 bool out = (edgeNorm * p2int) < -tol;
1391 if ( rClosest > 0. && rClosest < 1. ) // not node intersection
1394 // the ray passes through a face node; analyze transition through an adjacent edge
1395 gp_Pnt p1 = xyz[ (rClosest == 0.) ? ((iClosest+nbNodes-1) % nbNodes) : (iClosest+1) ];
1396 gp_Pnt p2 = xyz[ (rClosest == 0.) ? iClosest : ((iClosest+2) % nbNodes) ];
1397 gp_Vec edgeAdjacent( p1, p2 );
1398 gp_Vec edgeNorm2 = -( edgeAdjacent ^ faceNorm );
1399 bool out2 = (edgeNorm2 * p2int) < -tol;
1401 bool covexCorner = ( edgeNorm * edgeAdjacent * (rClosest==1. ? 1. : -1.)) < 0;
1402 return covexCorner ? (out || out2) : (out && out2);
1405 if ( element->GetType() == SMDSAbs_Edge ) // --------------------------------------------------
1407 // point is out of edge if it is NOT ON any straight part of edge
1408 // (we consider quadratic edge as being composed of two straight parts)
1409 for ( i = 1; i < nbNodes; ++i )
1411 gp_Vec edge( xyz[i-1], xyz[i] );
1412 gp_Vec n1p ( xyz[i-1], point );
1413 double u = ( edge * n1p ) / edge.SquareMagnitude(); // param [0,1] on the edge
1415 if ( n1p.SquareMagnitude() < tol * tol )
1420 if ( point.SquareDistance( xyz[i] ) < tol * tol )
1424 gp_XYZ proj = ( 1. - u ) * xyz[i-1] + u * xyz[i]; // projection of the point on the edge
1425 double dist2 = point.SquareDistance( proj );
1426 if ( dist2 > tol * tol )
1428 return false; // point is ON this part
1433 // Node or 0D element -------------------------------------------------------------------------
1435 gp_Vec n2p ( xyz[0], point );
1436 return n2p.SquareMagnitude() > tol * tol;
1441 //=======================================================================
1444 // Position of a point relative to a segment
1448 // VERTEX 1 o----ON-----> VERTEX 2
1452 enum PositionName { POS_LEFT = 1, POS_VERTEX = 2, POS_RIGHT = 4, //POS_ON = 8,
1453 POS_ALL = POS_LEFT | POS_RIGHT | POS_VERTEX };
1457 int _index; // index of vertex or segment
1459 PointPos( PositionName n, int i=-1 ): _name(n), _index(i) {}
1460 bool operator < (const PointPos& other ) const
1462 if ( _name == other._name )
1463 return ( _index < 0 || other._index < 0 ) ? false : _index < other._index;
1464 return _name < other._name;
1468 //================================================================================
1470 * \brief Return of a point relative to a segment
1471 * \param point2D - the point to analyze position of
1472 * \param xyVec - end points of segments
1473 * \param index0 - 0-based index of the first point of segment
1474 * \param posToFindOut - flags of positions to detect
1475 * \retval PointPos - point position
1477 //================================================================================
1479 PointPos getPointPosition( const gp_XY& point2D,
1480 const gp_XY* segEnds,
1481 const int index0 = 0,
1482 const int posToFindOut = POS_ALL)
1484 const gp_XY& p1 = segEnds[ index0 ];
1485 const gp_XY& p2 = segEnds[ index0+1 ];
1486 const gp_XY grad = p2 - p1;
1488 if ( posToFindOut & POS_VERTEX )
1490 // check if the point2D is at "vertex 1" zone
1491 gp_XY pp1[2] = { p1, gp_XY( p1.X() - grad.Y(),
1492 p1.Y() + grad.X() ) };
1493 if ( getPointPosition( point2D, pp1, 0, POS_LEFT|POS_RIGHT )._name == POS_LEFT )
1494 return PointPos( POS_VERTEX, index0 );
1496 // check if the point2D is at "vertex 2" zone
1497 gp_XY pp2[2] = { p2, gp_XY( p2.X() - grad.Y(),
1498 p2.Y() + grad.X() ) };
1499 if ( getPointPosition( point2D, pp2, 0, POS_LEFT|POS_RIGHT )._name == POS_RIGHT )
1500 return PointPos( POS_VERTEX, index0 + 1);
1502 double edgeEquation =
1503 ( point2D.X() - p1.X() ) * grad.Y() - ( point2D.Y() - p1.Y() ) * grad.X();
1504 return PointPos( edgeEquation < 0 ? POS_LEFT : POS_RIGHT, index0 );
1508 //=======================================================================
1510 * \brief Return minimal distance from a point to an element
1512 * Currently we ignore non-planarity and 2nd order of face
1514 //=======================================================================
1516 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshElement* elem,
1517 const gp_Pnt& point,
1518 gp_XYZ* closestPnt )
1520 switch ( elem->GetType() )
1522 case SMDSAbs_Volume:
1523 return GetDistance( dynamic_cast<const SMDS_MeshVolume*>( elem ), point, closestPnt );
1525 return GetDistance( dynamic_cast<const SMDS_MeshFace*>( elem ), point, closestPnt );
1527 return GetDistance( dynamic_cast<const SMDS_MeshEdge*>( elem ), point, closestPnt );
1529 if ( closestPnt ) *closestPnt = SMESH_TNodeXYZ( elem );
1530 return point.Distance( SMESH_TNodeXYZ( elem ));
1536 //=======================================================================
1538 * \brief Return minimal distance from a point to a face
1540 * Currently we ignore non-planarity and 2nd order of face
1542 //=======================================================================
1544 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshFace* face,
1545 const gp_Pnt& point,
1546 gp_XYZ* closestPnt )
1548 const double badDistance = -1;
1549 if ( !face ) return badDistance;
1551 // coordinates of nodes (medium nodes, if any, ignored)
1552 typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
1553 vector<gp_XYZ> xyz( TXyzIterator( face->nodesIterator()), TXyzIterator() );
1554 xyz.resize( face->NbCornerNodes()+1 );
1556 // transformation to get xyz[0] lies on the origin, xyz[1] lies on the Z axis,
1557 // and xyz[2] lies in the XZ plane. This is to pass to 2D space on XZ plane.
1559 gp_Vec OZ ( xyz[0], xyz[1] );
1560 gp_Vec OX ( xyz[0], xyz[2] );
1561 if ( OZ.Magnitude() < std::numeric_limits<double>::min() )
1563 if ( xyz.size() < 4 ) return badDistance;
1564 OZ = gp_Vec ( xyz[0], xyz[2] );
1565 OX = gp_Vec ( xyz[0], xyz[3] );
1569 tgtCS = gp_Ax3( xyz[0], OZ, OX );
1571 catch ( Standard_Failure ) {
1574 trsf.SetTransformation( tgtCS );
1576 // move all the nodes to 2D
1577 vector<gp_XY> xy( xyz.size() );
1578 for ( size_t i = 0;i < xyz.size()-1; ++i )
1580 gp_XYZ p3d = xyz[i];
1581 trsf.Transforms( p3d );
1582 xy[i].SetCoord( p3d.X(), p3d.Z() );
1584 xyz.back() = xyz.front();
1585 xy.back() = xy.front();
1587 // // move the point in 2D
1588 gp_XYZ tmpPnt = point.XYZ();
1589 trsf.Transforms( tmpPnt );
1590 gp_XY point2D( tmpPnt.X(), tmpPnt.Z() );
1592 // loop on edges of the face to analyze point position ralative to the face
1593 set< PointPos > pntPosSet;
1594 for ( size_t i = 1; i < xy.size(); ++i )
1596 PointPos pos = getPointPosition( point2D, &xy[0], i-1 );
1597 pntPosSet.insert( pos );
1601 PointPos pos = *pntPosSet.begin();
1602 switch ( pos._name )
1606 // point is most close to an edge
1607 gp_Vec edge( xyz[ pos._index ], xyz[ pos._index+1 ]);
1608 gp_Vec n1p ( xyz[ pos._index ], point );
1609 double u = ( edge * n1p ) / edge.SquareMagnitude(); // param [0,1] on the edge
1610 // projection of the point on the edge
1611 gp_XYZ proj = ( 1. - u ) * xyz[ pos._index ] + u * xyz[ pos._index+1 ];
1612 if ( closestPnt ) *closestPnt = proj;
1613 return point.Distance( proj );
1617 // point is inside the face
1618 double distToFacePlane = Abs( tmpPnt.Y() );
1621 if ( distToFacePlane < std::numeric_limits<double>::min() ) {
1622 *closestPnt = point.XYZ();
1626 trsf.Inverted().Transforms( tmpPnt );
1627 *closestPnt = tmpPnt;
1630 return distToFacePlane;
1634 // point is most close to a node
1635 gp_Vec distVec( point, xyz[ pos._index ]);
1636 return distVec.Magnitude();
1643 //=======================================================================
1645 * \brief Return minimal distance from a point to an edge
1647 //=======================================================================
1649 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshEdge* seg,
1650 const gp_Pnt& point,
1651 gp_XYZ* closestPnt )
1653 double dist = Precision::Infinite();
1654 if ( !seg ) return dist;
1656 int i = 0, nbNodes = seg->NbNodes();
1658 vector< SMESH_TNodeXYZ > xyz( nbNodes );
1659 SMDS_ElemIteratorPtr nodeIt = seg->interlacedNodesElemIterator();
1660 while ( nodeIt->more() )
1661 xyz[ i++ ].Set( nodeIt->next() );
1663 for ( i = 1; i < nbNodes; ++i )
1665 gp_Vec edge( xyz[i-1], xyz[i] );
1666 gp_Vec n1p ( xyz[i-1], point );
1667 double d, u = ( edge * n1p ) / edge.SquareMagnitude(); // param [0,1] on the edge
1669 if (( d = n1p.SquareMagnitude() ) < dist ) {
1671 if ( closestPnt ) *closestPnt = xyz[i-1];
1674 else if ( u >= 1. ) {
1675 if (( d = point.SquareDistance( xyz[i] )) < dist ) {
1677 if ( closestPnt ) *closestPnt = xyz[i];
1681 gp_XYZ proj = xyz[i-1] + u * edge.XYZ(); // projection of the point on the edge
1682 if (( d = point.SquareDistance( proj )) < dist ) {
1684 if ( closestPnt ) *closestPnt = proj;
1688 return Sqrt( dist );
1691 //=======================================================================
1693 * \brief Return minimal distance from a point to a volume
1695 * Currently we ignore non-planarity and 2nd order
1697 //=======================================================================
1699 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshVolume* volume,
1700 const gp_Pnt& point,
1701 gp_XYZ* closestPnt )
1703 SMDS_VolumeTool vTool( volume );
1704 vTool.SetExternalNormal();
1705 const int iQ = volume->IsQuadratic() ? 2 : 1;
1708 double minDist = 1e100, dist;
1709 gp_XYZ closeP = point.XYZ();
1711 for ( int iF = 0; iF < vTool.NbFaces(); ++iF )
1713 // skip a facet with normal not "looking at" the point
1714 if ( !vTool.GetFaceNormal( iF, n[0], n[1], n[2] ) ||
1715 !vTool.GetFaceBaryCenter( iF, bc[0], bc[1], bc[2] ))
1717 gp_XYZ bcp = point.XYZ() - gp_XYZ( bc[0], bc[1], bc[2] );
1718 if ( gp_XYZ( n[0], n[1], n[2] ) * bcp < 1e-6 )
1721 // find distance to a facet
1722 const SMDS_MeshNode** nodes = vTool.GetFaceNodes( iF );
1723 switch ( vTool.NbFaceNodes( iF ) / iQ ) {
1726 SMDS_FaceOfNodes tmpFace( nodes[0], nodes[ 1*iQ ], nodes[ 2*iQ ] );
1727 dist = GetDistance( &tmpFace, point, closestPnt );
1732 SMDS_FaceOfNodes tmpFace( nodes[0], nodes[ 1*iQ ], nodes[ 2*iQ ], nodes[ 3*iQ ]);
1733 dist = GetDistance( &tmpFace, point, closestPnt );
1737 vector<const SMDS_MeshNode *> nvec( nodes, nodes + vTool.NbFaceNodes( iF ));
1738 SMDS_PolygonalFaceOfNodes tmpFace( nvec );
1739 dist = GetDistance( &tmpFace, point, closestPnt );
1741 if ( dist < minDist )
1745 if ( closestPnt ) closeP = *closestPnt;
1750 if ( closestPnt ) *closestPnt = closeP;
1754 return 0; // point is inside the volume
1757 //================================================================================
1759 * \brief Returns barycentric coordinates of a point within a triangle.
1760 * A not returned bc2 = 1. - bc0 - bc1.
1761 * The point lies within the triangle if ( bc0 >= 0 && bc1 >= 0 && bc0+bc1 <= 1 )
1763 //================================================================================
1765 void SMESH_MeshAlgos::GetBarycentricCoords( const gp_XY& p,
1772 const double // matrix 2x2
1773 T11 = t0.X()-t2.X(), T12 = t1.X()-t2.X(),
1774 T21 = t0.Y()-t2.Y(), T22 = t1.Y()-t2.Y();
1775 const double Tdet = T11*T22 - T12*T21; // matrix determinant
1776 if ( Abs( Tdet ) < std::numeric_limits<double>::min() )
1782 const double t11 = T22, t12 = -T12, t21 = -T21, t22 = T11;
1784 const double r11 = p.X()-t2.X(), r12 = p.Y()-t2.Y();
1785 // barycentric coordinates: mutiply matrix by vector
1786 bc0 = (t11 * r11 + t12 * r12)/Tdet;
1787 bc1 = (t21 * r11 + t22 * r12)/Tdet;
1790 //=======================================================================
1791 //function : FindFaceInSet
1792 //purpose : Return a face having linked nodes n1 and n2 and which is
1793 // - not in avoidSet,
1794 // - in elemSet provided that !elemSet.empty()
1795 // i1 and i2 optionally returns indices of n1 and n2
1796 //=======================================================================
1798 const SMDS_MeshElement*
1799 SMESH_MeshAlgos::FindFaceInSet(const SMDS_MeshNode* n1,
1800 const SMDS_MeshNode* n2,
1801 const TIDSortedElemSet& elemSet,
1802 const TIDSortedElemSet& avoidSet,
1808 const SMDS_MeshElement* face = 0;
1810 SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator(SMDSAbs_Face);
1811 while ( invElemIt->more() && !face ) // loop on inverse faces of n1
1813 const SMDS_MeshElement* elem = invElemIt->next();
1814 if (avoidSet.count( elem ))
1816 if ( !elemSet.empty() && !elemSet.count( elem ))
1819 i1 = elem->GetNodeIndex( n1 );
1820 // find a n2 linked to n1
1821 int nbN = elem->IsQuadratic() ? elem->NbNodes()/2 : elem->NbNodes();
1822 for ( int di = -1; di < 2 && !face; di += 2 )
1824 i2 = (i1+di+nbN) % nbN;
1825 if ( elem->GetNode( i2 ) == n2 )
1828 if ( !face && elem->IsQuadratic())
1830 // analysis for quadratic elements using all nodes
1831 SMDS_ElemIteratorPtr anIter = elem->interlacedNodesElemIterator();
1832 const SMDS_MeshNode* prevN = static_cast<const SMDS_MeshNode*>( anIter->next() );
1833 for ( i1 = -1, i2 = 0; anIter->more() && !face; i1++, i2++ )
1835 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( anIter->next() );
1836 if ( n1 == prevN && n2 == n )
1840 else if ( n2 == prevN && n1 == n )
1842 face = elem; swap( i1, i2 );
1848 if ( n1ind ) *n1ind = i1;
1849 if ( n2ind ) *n2ind = i2;
1853 //================================================================================
1855 * \brief Calculate normal of a mesh face
1857 //================================================================================
1859 bool SMESH_MeshAlgos::FaceNormal(const SMDS_MeshElement* F, gp_XYZ& normal, bool normalized)
1861 if ( !F || F->GetType() != SMDSAbs_Face )
1864 normal.SetCoord(0,0,0);
1865 int nbNodes = F->NbCornerNodes();
1866 for ( int i = 0; i < nbNodes-2; ++i )
1869 for ( int n = 0; n < 3; ++n )
1871 const SMDS_MeshNode* node = F->GetNode( i + n );
1872 p[n].SetCoord( node->X(), node->Y(), node->Z() );
1874 normal += ( p[2] - p[1] ) ^ ( p[0] - p[1] );
1876 double size2 = normal.SquareModulus();
1877 bool ok = ( size2 > numeric_limits<double>::min() * numeric_limits<double>::min());
1878 if ( normalized && ok )
1879 normal /= sqrt( size2 );
1884 //=======================================================================
1885 //function : GetCommonNodes
1886 //purpose : Return nodes common to two elements
1887 //=======================================================================
1889 vector< const SMDS_MeshNode*> SMESH_MeshAlgos::GetCommonNodes(const SMDS_MeshElement* e1,
1890 const SMDS_MeshElement* e2)
1892 vector< const SMDS_MeshNode*> common;
1893 for ( int i = 0 ; i < e1->NbNodes(); ++i )
1894 if ( e2->GetNodeIndex( e1->GetNode( i )) >= 0 )
1895 common.push_back( e1->GetNode( i ));
1898 //================================================================================
1900 * \brief Return true if node1 encounters first in the face and node2, after
1902 //================================================================================
1904 bool SMESH_MeshAlgos::IsRightOrder( const SMDS_MeshElement* face,
1905 const SMDS_MeshNode* node0,
1906 const SMDS_MeshNode* node1 )
1908 int i0 = face->GetNodeIndex( node0 );
1909 int i1 = face->GetNodeIndex( node1 );
1910 if ( face->IsQuadratic() )
1912 if ( face->IsMediumNode( node0 ))
1914 i0 -= ( face->NbNodes()/2 - 1 );
1919 i1 -= ( face->NbNodes()/2 - 1 );
1924 return ( diff == 1 ) || ( diff == -face->NbNodes()+1 );
1927 //=======================================================================
1929 * \brief Return SMESH_NodeSearcher
1931 //=======================================================================
1933 SMESH_NodeSearcher* SMESH_MeshAlgos::GetNodeSearcher(SMDS_Mesh& mesh)
1935 return new SMESH_NodeSearcherImpl( &mesh );
1938 //=======================================================================
1940 * \brief Return SMESH_NodeSearcher
1942 //=======================================================================
1944 SMESH_NodeSearcher* SMESH_MeshAlgos::GetNodeSearcher(SMDS_ElemIteratorPtr elemIt)
1946 return new SMESH_NodeSearcherImpl( 0, elemIt );
1949 //=======================================================================
1951 * \brief Return SMESH_ElementSearcher
1953 //=======================================================================
1955 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh& mesh,
1958 return new SMESH_ElementSearcherImpl( mesh, tolerance );
1961 //=======================================================================
1963 * \brief Return SMESH_ElementSearcher acting on a sub-set of elements
1965 //=======================================================================
1967 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh& mesh,
1968 SMDS_ElemIteratorPtr elemIt,
1971 return new SMESH_ElementSearcherImpl( mesh, tolerance, elemIt );