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 prepare(); // !!!call it before calling the following methods!!!
234 void getElementsNearPoint( const gp_Pnt& point, vector<const SMDS_MeshElement*>& foundElems );
235 void getElementsNearLine ( const gp_Ax1& line, vector<const SMDS_MeshElement*>& foundElems);
236 void getElementsInSphere ( const gp_XYZ& center,
238 vector<const SMDS_MeshElement*>& foundElems);
239 ElementBndBoxTree* getLeafAtPoint( const gp_XYZ& point );
242 ElementBndBoxTree() {}
243 SMESH_Octree* newChild() const { return new ElementBndBoxTree; }
244 void buildChildrenData();
245 Bnd_B3d* buildRootBox();
247 //!< Bounding box of element
248 struct ElementBox : public Bnd_B3d
250 const SMDS_MeshElement* _element;
252 void init(const SMDS_MeshElement* elem, double tolerance);
254 vector< ElementBox* > _elements;
256 typedef ObjectPool< ElementBox > TElementBoxPool;
258 //!< allocator of ElementBox's and SMESH_TreeLimit
259 struct LimitAndPool : public SMESH_TreeLimit
261 TElementBoxPool _elBoPool;
262 std::vector< ElementBox* > _markedElems;
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 int nbElems = mesh.GetMeshInfo().NbElements( elemType );
285 _elements.reserve( nbElems );
287 TElementBoxPool& elBoPool = getLimitAndPool()->_elBoPool;
289 SMDS_ElemIteratorPtr elemIt = theElemIt ? theElemIt : mesh.elementsIterator( elemType );
290 while ( elemIt->more() )
292 ElementBox* eb = elBoPool.getNew();
293 eb->init( elemIt->next(), tolerance );
294 _elements.push_back( eb );
299 //================================================================================
301 * \brief Return the maximal box
303 //================================================================================
305 Bnd_B3d* ElementBndBoxTree::buildRootBox()
307 Bnd_B3d* box = new Bnd_B3d;
308 for ( size_t i = 0; i < _elements.size(); ++i )
309 box->Add( *_elements[i] );
313 //================================================================================
315 * \brief Redistrubute element boxes among children
317 //================================================================================
319 void ElementBndBoxTree::buildChildrenData()
321 for ( size_t i = 0; i < _elements.size(); ++i )
323 for (int j = 0; j < 8; j++)
325 if ( !_elements[i]->IsOut( *myChildren[j]->getBox() ))
326 ((ElementBndBoxTree*)myChildren[j])->_elements.push_back( _elements[i]);
329 //_size = _elements.size();
330 SMESHUtils::FreeVector( _elements ); // = _elements.clear() + free memory
332 for (int j = 0; j < 8; j++)
334 ElementBndBoxTree* child = static_cast<ElementBndBoxTree*>( myChildren[j]);
335 if ((int) child->_elements.size() <= MaxNbElemsInLeaf )
336 child->myIsLeaf = true;
338 if ( child->isLeaf() && child->_elements.capacity() > child->_elements.size() )
339 SMESHUtils::CompactVector( child->_elements );
343 //================================================================================
345 * \brief Un-mark all elements
347 //================================================================================
349 void ElementBndBoxTree::prepare()
351 // TElementBoxPool& elBoPool = getElementBoxPool();
352 // for ( size_t i = 0; i < elBoPool.nbElements(); ++i )
353 // const_cast< ElementBox* >( elBoPool[ i ])->_isMarked = false;
356 //================================================================================
358 * \brief Return elements which can include the point
360 //================================================================================
362 void ElementBndBoxTree::getElementsNearPoint( const gp_Pnt& point,
363 vector<const SMDS_MeshElement*>& foundElems)
365 if ( getBox()->IsOut( point.XYZ() ))
370 LimitAndPool* pool = getLimitAndPool();
372 for ( size_t i = 0; i < _elements.size(); ++i )
373 if ( !_elements[i]->IsOut( point.XYZ() ) &&
374 !_elements[i]->_isMarked )
376 foundElems.push_back( _elements[i]->_element );
377 _elements[i]->_isMarked = true;
378 pool->_markedElems.push_back( _elements[i] );
383 for (int i = 0; i < 8; i++)
384 ((ElementBndBoxTree*) myChildren[i])->getElementsNearPoint( point, foundElems );
388 LimitAndPool* pool = getLimitAndPool();
389 for ( size_t i = 0; i < pool->_markedElems.size(); ++i )
390 pool->_markedElems[i]->_isMarked = false;
391 pool->_markedElems.clear();
396 //================================================================================
398 * \brief Return elements which can be intersected by the line
400 //================================================================================
402 void ElementBndBoxTree::getElementsNearLine( const gp_Ax1& line,
403 vector<const SMDS_MeshElement*>& foundElems)
405 if ( getBox()->IsOut( line ))
410 LimitAndPool* pool = getLimitAndPool();
412 for ( size_t i = 0; i < _elements.size(); ++i )
413 if ( !_elements[i]->IsOut( line ) &&
414 !_elements[i]->_isMarked )
416 foundElems.push_back( _elements[i]->_element );
417 _elements[i]->_isMarked = true;
418 pool->_markedElems.push_back( _elements[i] );
423 for (int i = 0; i < 8; i++)
424 ((ElementBndBoxTree*) myChildren[i])->getElementsNearLine( line, foundElems );
428 LimitAndPool* pool = getLimitAndPool();
429 for ( size_t i = 0; i < pool->_markedElems.size(); ++i )
430 pool->_markedElems[i]->_isMarked = false;
431 pool->_markedElems.clear();
436 //================================================================================
438 * \brief Return elements from leaves intersecting the sphere
440 //================================================================================
442 void ElementBndBoxTree::getElementsInSphere ( const gp_XYZ& center,
444 vector<const SMDS_MeshElement*>& foundElems)
446 if ( getBox()->IsOut( center, radius ))
451 LimitAndPool* pool = getLimitAndPool();
453 for ( size_t i = 0; i < _elements.size(); ++i )
454 if ( !_elements[i]->IsOut( center, radius ) &&
455 !_elements[i]->_isMarked )
457 foundElems.push_back( _elements[i]->_element );
458 _elements[i]->_isMarked = true;
459 pool->_markedElems.push_back( _elements[i] );
464 for (int i = 0; i < 8; i++)
465 ((ElementBndBoxTree*) myChildren[i])->getElementsInSphere( center, radius, foundElems );
469 LimitAndPool* pool = getLimitAndPool();
470 for ( size_t i = 0; i < pool->_markedElems.size(); ++i )
471 pool->_markedElems[i]->_isMarked = false;
472 pool->_markedElems.clear();
477 //================================================================================
479 * \brief Return a leaf including a point
481 //================================================================================
483 ElementBndBoxTree* ElementBndBoxTree::getLeafAtPoint( const gp_XYZ& point )
485 if ( getBox()->IsOut( point ))
494 for (int i = 0; i < 8; i++)
495 if ( ElementBndBoxTree* l = ((ElementBndBoxTree*) myChildren[i])->getLeafAtPoint( point ))
501 //================================================================================
503 * \brief Construct the element box
505 //================================================================================
507 void ElementBndBoxTree::ElementBox::init(const SMDS_MeshElement* elem, double tolerance)
511 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
512 while ( nIt->more() )
513 Add( SMESH_NodeXYZ( nIt->next() ));
514 Enlarge( tolerance );
519 //=======================================================================
521 * \brief Implementation of search for the elements by point and
522 * of classification of point in 2D mesh
524 //=======================================================================
526 SMESH_ElementSearcher::~SMESH_ElementSearcher()
530 struct SMESH_ElementSearcherImpl: public SMESH_ElementSearcher
533 SMDS_ElemIteratorPtr _meshPartIt;
534 ElementBndBoxTree* _ebbTree [SMDSAbs_NbElementTypes];
535 int _ebbTreeHeight[SMDSAbs_NbElementTypes];
536 SMESH_NodeSearcherImpl* _nodeSearcher;
537 SMDSAbs_ElementType _elementType;
539 bool _outerFacesFound;
540 set<const SMDS_MeshElement*> _outerFaces; // empty means "no internal faces at all"
542 SMESH_ElementSearcherImpl( SMDS_Mesh& mesh,
544 SMDS_ElemIteratorPtr elemIt=SMDS_ElemIteratorPtr())
545 : _mesh(&mesh),_meshPartIt(elemIt),_nodeSearcher(0),_tolerance(tol),_outerFacesFound(false)
547 for ( int i = 0; i < SMDSAbs_NbElementTypes; ++i )
550 _ebbTreeHeight[i] = -1;
552 _elementType = SMDSAbs_All;
554 virtual ~SMESH_ElementSearcherImpl()
556 for ( int i = 0; i < SMDSAbs_NbElementTypes; ++i )
558 delete _ebbTree[i]; _ebbTree[i] = NULL;
560 if ( _nodeSearcher ) delete _nodeSearcher; _nodeSearcher = 0;
562 virtual int FindElementsByPoint(const gp_Pnt& point,
563 SMDSAbs_ElementType type,
564 vector< const SMDS_MeshElement* >& foundElements);
565 virtual TopAbs_State GetPointState(const gp_Pnt& point);
566 virtual const SMDS_MeshElement* FindClosestTo( const gp_Pnt& point,
567 SMDSAbs_ElementType type );
569 virtual void GetElementsNearLine( const gp_Ax1& line,
570 SMDSAbs_ElementType type,
571 vector< const SMDS_MeshElement* >& foundElems);
572 virtual void GetElementsInSphere( const gp_XYZ& center,
574 SMDSAbs_ElementType type,
575 vector< const SMDS_MeshElement* >& foundElems);
576 virtual gp_XYZ Project(const gp_Pnt& point,
577 SMDSAbs_ElementType type,
578 const SMDS_MeshElement** closestElem);
579 double getTolerance();
580 bool getIntersParamOnLine(const gp_Lin& line, const SMDS_MeshElement* face,
581 const double tolerance, double & param);
582 void findOuterBoundary(const SMDS_MeshElement* anyOuterFace);
583 bool isOuterBoundary(const SMDS_MeshElement* face) const
585 return _outerFaces.empty() || _outerFaces.count(face);
589 if ( _ebbTreeHeight[ _elementType ] < 0 )
590 _ebbTreeHeight[ _elementType ] = _ebbTree[ _elementType ]->getHeight();
591 return _ebbTreeHeight[ _elementType ];
594 struct TInters //!< data of intersection of the line and the mesh face (used in GetPointState())
596 const SMDS_MeshElement* _face;
598 bool _coincides; //!< the line lays in face plane
599 TInters(const SMDS_MeshElement* face, const gp_Vec& faceNorm, bool coinc=false)
600 : _face(face), _faceNorm( faceNorm ), _coincides( coinc ) {}
602 struct TFaceLink //!< link and faces sharing it (used in findOuterBoundary())
605 TIDSortedElemSet _faces;
606 TFaceLink( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshElement* face)
607 : _link( n1, n2 ), _faces( &face, &face + 1) {}
611 ostream& operator<< (ostream& out, const SMESH_ElementSearcherImpl::TInters& i)
613 return out << "TInters(face=" << ( i._face ? i._face->GetID() : 0)
614 << ", _coincides="<<i._coincides << ")";
617 //=======================================================================
619 * \brief define tolerance for search
621 //=======================================================================
623 double SMESH_ElementSearcherImpl::getTolerance()
625 if ( _tolerance < 0 )
627 const SMDS_MeshInfo& meshInfo = _mesh->GetMeshInfo();
630 if ( _nodeSearcher && meshInfo.NbNodes() > 1 )
632 double boxSize = _nodeSearcher->getTree()->maxSize();
633 _tolerance = 1e-8 * boxSize/* / meshInfo.NbNodes()*/;
635 else if ( _ebbTree[_elementType] && meshInfo.NbElements() > 0 )
637 double boxSize = _ebbTree[_elementType]->maxSize();
638 _tolerance = 1e-8 * boxSize/* / meshInfo.NbElements()*/;
640 if ( _tolerance == 0 )
642 // define tolerance by size of a most complex element
643 int complexType = SMDSAbs_Volume;
644 while ( complexType > SMDSAbs_All &&
645 meshInfo.NbElements( SMDSAbs_ElementType( complexType )) < 1 )
647 if ( complexType == SMDSAbs_All ) return 0; // empty mesh
649 if ( complexType == int( SMDSAbs_Node ))
651 SMDS_NodeIteratorPtr nodeIt = _mesh->nodesIterator();
653 if ( meshInfo.NbNodes() > 2 )
654 elemSize = SMESH_TNodeXYZ( nodeIt->next() ).Distance( nodeIt->next() );
658 SMDS_ElemIteratorPtr elemIt = _mesh->elementsIterator( SMDSAbs_ElementType( complexType ));
659 const SMDS_MeshElement* elem = elemIt->next();
660 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
661 SMESH_TNodeXYZ n1( nodeIt->next() );
663 while ( nodeIt->more() )
665 double dist = n1.Distance( static_cast<const SMDS_MeshNode*>( nodeIt->next() ));
666 elemSize = max( dist, elemSize );
669 _tolerance = 1e-4 * elemSize;
675 //================================================================================
677 * \brief Find intersection of the line and an edge of face and return parameter on line
679 //================================================================================
681 bool SMESH_ElementSearcherImpl::getIntersParamOnLine(const gp_Lin& line,
682 const SMDS_MeshElement* face,
689 GeomAPI_ExtremaCurveCurve anExtCC;
690 Handle(Geom_Curve) lineCurve = new Geom_Line( line );
692 int nbNodes = face->IsQuadratic() ? face->NbNodes()/2 : face->NbNodes();
693 for ( int i = 0; i < nbNodes && nbInts < 2; ++i )
695 GC_MakeSegment edge( SMESH_TNodeXYZ( face->GetNode( i )),
696 SMESH_TNodeXYZ( face->GetNode( (i+1)%nbNodes) ));
697 anExtCC.Init( lineCurve, edge.Value() );
698 if ( anExtCC.NbExtrema() > 0 && anExtCC.LowerDistance() <= tol)
700 Standard_Real pl, pe;
701 anExtCC.LowerDistanceParameters( pl, pe );
707 if ( nbInts > 0 ) param /= nbInts;
710 //================================================================================
712 * \brief Find all faces belonging to the outer boundary of mesh
714 //================================================================================
716 void SMESH_ElementSearcherImpl::findOuterBoundary(const SMDS_MeshElement* outerFace)
718 if ( _outerFacesFound ) return;
720 // Collect all outer faces by passing from one outer face to another via their links
721 // and BTW find out if there are internal faces at all.
723 // checked links and links where outer boundary meets internal one
724 set< SMESH_TLink > visitedLinks, seamLinks;
726 // links to treat with already visited faces sharing them
727 list < TFaceLink > startLinks;
729 // load startLinks with the first outerFace
730 startLinks.push_back( TFaceLink( outerFace->GetNode(0), outerFace->GetNode(1), outerFace));
731 _outerFaces.insert( outerFace );
733 TIDSortedElemSet emptySet;
734 while ( !startLinks.empty() )
736 const SMESH_TLink& link = startLinks.front()._link;
737 TIDSortedElemSet& faces = startLinks.front()._faces;
739 outerFace = *faces.begin();
740 // find other faces sharing the link
741 const SMDS_MeshElement* f;
742 while (( f = SMESH_MeshAlgos::FindFaceInSet(link.node1(), link.node2(), emptySet, faces )))
745 // select another outer face among the found
746 const SMDS_MeshElement* outerFace2 = 0;
747 if ( faces.size() == 2 )
749 outerFace2 = (outerFace == *faces.begin() ? *faces.rbegin() : *faces.begin());
751 else if ( faces.size() > 2 )
753 seamLinks.insert( link );
755 // link direction within the outerFace
756 gp_Vec n1n2( SMESH_TNodeXYZ( link.node1()),
757 SMESH_TNodeXYZ( link.node2()));
758 int i1 = outerFace->GetNodeIndex( link.node1() );
759 int i2 = outerFace->GetNodeIndex( link.node2() );
760 bool rev = ( abs(i2-i1) == 1 ? i1 > i2 : i2 > i1 );
761 if ( rev ) n1n2.Reverse();
763 gp_XYZ ofNorm, fNorm;
764 if ( SMESH_MeshAlgos::FaceNormal( outerFace, ofNorm, /*normalized=*/false ))
766 // direction from the link inside outerFace
767 gp_Vec dirInOF = gp_Vec( ofNorm ) ^ n1n2;
768 // sort all other faces by angle with the dirInOF
769 map< double, const SMDS_MeshElement* > angle2Face;
770 set< const SMDS_MeshElement*, TIDCompare >::const_iterator face = faces.begin();
771 for ( ; face != faces.end(); ++face )
773 if ( *face == outerFace ) continue;
774 if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false ))
776 gp_Vec dirInF = gp_Vec( fNorm ) ^ n1n2;
777 double angle = dirInOF.AngleWithRef( dirInF, n1n2 );
778 if ( angle < 0 ) angle += 2. * M_PI;
779 angle2Face.insert( make_pair( angle, *face ));
781 if ( !angle2Face.empty() )
782 outerFace2 = angle2Face.begin()->second;
785 // store the found outer face and add its links to continue searching from
788 _outerFaces.insert( outerFace2 );
789 int nbNodes = outerFace2->NbCornerNodes();
790 for ( int i = 0; i < nbNodes; ++i )
792 SMESH_TLink link2( outerFace2->GetNode(i), outerFace2->GetNode((i+1)%nbNodes));
793 if ( visitedLinks.insert( link2 ).second )
794 startLinks.push_back( TFaceLink( link2.node1(), link2.node2(), outerFace2 ));
797 startLinks.pop_front();
799 _outerFacesFound = true;
801 if ( !seamLinks.empty() )
803 // There are internal boundaries touching the outher one,
804 // find all faces of internal boundaries in order to find
805 // faces of boundaries of holes, if any.
814 //=======================================================================
816 * \brief Find elements of given type where the given point is IN or ON.
817 * Returns nb of found elements and elements them-selves.
819 * 'ALL' type means elements of any type excluding nodes, balls and 0D elements
821 //=======================================================================
823 int SMESH_ElementSearcherImpl::
824 FindElementsByPoint(const gp_Pnt& point,
825 SMDSAbs_ElementType type,
826 vector< const SMDS_MeshElement* >& foundElements)
828 foundElements.clear();
831 double tolerance = getTolerance();
833 // =================================================================================
834 if ( type == SMDSAbs_Node || type == SMDSAbs_0DElement || type == SMDSAbs_Ball)
836 if ( !_nodeSearcher )
839 _nodeSearcher = new SMESH_NodeSearcherImpl( 0, _meshPartIt );
841 _nodeSearcher = new SMESH_NodeSearcherImpl( _mesh );
843 std::vector< const SMDS_MeshNode* > foundNodes;
844 _nodeSearcher->FindNearPoint( point, tolerance, foundNodes );
846 if ( type == SMDSAbs_Node )
848 foundElements.assign( foundNodes.begin(), foundNodes.end() );
852 for ( size_t i = 0; i < foundNodes.size(); ++i )
854 SMDS_ElemIteratorPtr elemIt = foundNodes[i]->GetInverseElementIterator( type );
855 while ( elemIt->more() )
856 foundElements.push_back( elemIt->next() );
860 // =================================================================================
861 else // elements more complex than 0D
863 if ( !_ebbTree[type] )
865 _ebbTree[_elementType] = new ElementBndBoxTree( *_mesh, type, _meshPartIt, tolerance );
869 _ebbTree[ type ]->prepare();
871 vector< const SMDS_MeshElement* > suspectElems;
872 _ebbTree[ type ]->getElementsNearPoint( point, suspectElems );
873 vector< const SMDS_MeshElement* >::iterator elem = suspectElems.begin();
874 for ( ; elem != suspectElems.end(); ++elem )
875 if ( !SMESH_MeshAlgos::IsOut( *elem, point, tolerance ))
876 foundElements.push_back( *elem );
878 return foundElements.size();
881 //=======================================================================
883 * \brief Find an element of given type most close to the given point
885 * WARNING: Only face search is implemeneted so far
887 //=======================================================================
889 const SMDS_MeshElement*
890 SMESH_ElementSearcherImpl::FindClosestTo( const gp_Pnt& point,
891 SMDSAbs_ElementType type )
893 const SMDS_MeshElement* closestElem = 0;
896 if ( type == SMDSAbs_Face || type == SMDSAbs_Volume )
898 ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
900 ebbTree = new ElementBndBoxTree( *_mesh, type, _meshPartIt );
904 vector<const SMDS_MeshElement*> suspectElems;
905 ebbTree->getElementsNearPoint( point, suspectElems );
907 if ( suspectElems.empty() && ebbTree->maxSize() > 0 )
909 gp_Pnt boxCenter = 0.5 * ( ebbTree->getBox()->CornerMin() +
910 ebbTree->getBox()->CornerMax() );
912 if ( ebbTree->getBox()->IsOut( point.XYZ() ))
913 radius = point.Distance( boxCenter ) - 0.5 * ebbTree->maxSize();
915 radius = ebbTree->maxSize() / pow( 2., getTreeHeight()) / 2;
916 while ( suspectElems.empty() )
919 ebbTree->getElementsInSphere( point.XYZ(), radius, suspectElems );
923 double minDist = std::numeric_limits<double>::max();
924 multimap< double, const SMDS_MeshElement* > dist2face;
925 vector<const SMDS_MeshElement*>::iterator elem = suspectElems.begin();
926 for ( ; elem != suspectElems.end(); ++elem )
928 double dist = SMESH_MeshAlgos::GetDistance( *elem, point );
929 if ( dist < minDist + 1e-10)
932 dist2face.insert( dist2face.begin(), make_pair( dist, *elem ));
935 if ( !dist2face.empty() )
937 multimap< double, const SMDS_MeshElement* >::iterator d2f = dist2face.begin();
938 closestElem = d2f->second;
939 // if there are several elements at the same distance, select one
940 // with GC closest to the point
941 typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
942 double minDistToGC = 0;
943 for ( ++d2f; d2f != dist2face.end() && fabs( d2f->first - minDist ) < 1e-10; ++d2f )
945 if ( minDistToGC == 0 )
948 gc = accumulate( TXyzIterator(closestElem->nodesIterator()),
949 TXyzIterator(), gc ) / closestElem->NbNodes();
950 minDistToGC = point.SquareDistance( gc );
953 gc = accumulate( TXyzIterator( d2f->second->nodesIterator()),
954 TXyzIterator(), gc ) / d2f->second->NbNodes();
955 double d = point.SquareDistance( gc );
956 if ( d < minDistToGC )
959 closestElem = d2f->second;
962 // cout << "FindClosestTo( " <<point.X()<<", "<<point.Y()<<", "<<point.Z()<<" ) FACE "
963 // <<closestElem->GetID() << " DIST " << minDist << endl;
968 // NOT IMPLEMENTED SO FAR
974 //================================================================================
976 * \brief Classify the given point in the closed 2D mesh
978 //================================================================================
980 TopAbs_State SMESH_ElementSearcherImpl::GetPointState(const gp_Pnt& point)
982 _elementType = SMDSAbs_Face;
984 double tolerance = getTolerance();
986 ElementBndBoxTree*& ebbTree = _ebbTree[ SMDSAbs_Face ];
988 ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
992 // Algo: analyse transition of a line starting at the point through mesh boundary;
993 // try three lines parallel to axis of the coordinate system and perform rough
994 // analysis. If solution is not clear perform thorough analysis.
996 const int nbAxes = 3;
997 gp_Dir axisDir[ nbAxes ] = { gp::DX(), gp::DY(), gp::DZ() };
998 map< double, TInters > paramOnLine2TInters[ nbAxes ];
999 list< TInters > tangentInters[ nbAxes ]; // of faces whose plane includes the line
1000 multimap< int, int > nbInt2Axis; // to find the simplest case
1001 for ( int axis = 0; axis < nbAxes; ++axis )
1003 gp_Ax1 lineAxis( point, axisDir[axis]);
1004 gp_Lin line ( lineAxis );
1006 vector<const SMDS_MeshElement*> suspectFaces; // faces possibly intersecting the line
1007 if ( axis > 0 ) ebbTree->prepare();
1008 ebbTree->getElementsNearLine( lineAxis, suspectFaces );
1010 // Intersect faces with the line
1012 map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
1013 vector<const SMDS_MeshElement*>::iterator face = suspectFaces.begin();
1014 for ( ; face != suspectFaces.end(); ++face )
1018 if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false)) continue;
1019 gp_Pln facePlane( SMESH_TNodeXYZ( (*face)->GetNode(0)), fNorm );
1021 // perform intersection
1022 IntAna_IntConicQuad intersection( line, IntAna_Quadric( facePlane ));
1023 if ( !intersection.IsDone() )
1025 if ( intersection.IsInQuadric() )
1027 tangentInters[ axis ].push_back( TInters( *face, fNorm, true ));
1029 else if ( ! intersection.IsParallel() && intersection.NbPoints() > 0 )
1031 double tol = 1e-4 * Sqrt( fNorm.Modulus() );
1032 gp_Pnt intersectionPoint = intersection.Point(1);
1033 if ( !SMESH_MeshAlgos::IsOut( *face, intersectionPoint, tol ))
1034 u2inters.insert(make_pair( intersection.ParamOnConic(1), TInters( *face, fNorm )));
1037 // Analyse intersections roughly
1039 int nbInter = u2inters.size();
1043 double f = u2inters.begin()->first, l = u2inters.rbegin()->first;
1044 if ( nbInter == 1 ) // not closed mesh
1045 return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
1047 if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
1050 if ( (f<0) == (l<0) )
1053 int nbIntBeforePoint = std::distance( u2inters.begin(), u2inters.lower_bound(0));
1054 int nbIntAfterPoint = nbInter - nbIntBeforePoint;
1055 if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
1058 nbInt2Axis.insert( make_pair( min( nbIntBeforePoint, nbIntAfterPoint ), axis ));
1060 if ( _outerFacesFound ) break; // pass to thorough analysis
1062 } // three attempts - loop on CS axes
1064 // Analyse intersections thoroughly.
1065 // We make two loops maximum, on the first one we only exclude touching intersections,
1066 // on the second, if situation is still unclear, we gather and use information on
1067 // position of faces (internal or outer). If faces position is already gathered,
1068 // we make the second loop right away.
1070 for ( int hasPositionInfo = _outerFacesFound; hasPositionInfo < 2; ++hasPositionInfo )
1072 multimap< int, int >::const_iterator nb_axis = nbInt2Axis.begin();
1073 for ( ; nb_axis != nbInt2Axis.end(); ++nb_axis )
1075 int axis = nb_axis->second;
1076 map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
1078 gp_Ax1 lineAxis( point, axisDir[axis]);
1079 gp_Lin line ( lineAxis );
1081 // add tangent intersections to u2inters
1083 list< TInters >::const_iterator tgtInt = tangentInters[ axis ].begin();
1084 for ( ; tgtInt != tangentInters[ axis ].end(); ++tgtInt )
1085 if ( getIntersParamOnLine( line, tgtInt->_face, tolerance, param ))
1086 u2inters.insert(make_pair( param, *tgtInt ));
1087 tangentInters[ axis ].clear();
1089 // Count intersections before and after the point excluding touching ones.
1090 // If hasPositionInfo we count intersections of outer boundary only
1092 int nbIntBeforePoint = 0, nbIntAfterPoint = 0;
1093 double f = numeric_limits<double>::max(), l = -numeric_limits<double>::max();
1094 map< double, TInters >::iterator u_int1 = u2inters.begin(), u_int2 = u_int1;
1095 bool ok = ! u_int1->second._coincides;
1096 while ( ok && u_int1 != u2inters.end() )
1098 double u = u_int1->first;
1099 bool touchingInt = false;
1100 if ( ++u_int2 != u2inters.end() )
1102 // skip intersections at the same point (if the line passes through edge or node)
1104 while ( u_int2 != u2inters.end() && fabs( u_int2->first - u ) < tolerance )
1110 // skip tangent intersections
1112 if ( u_int2 != u2inters.end() )
1114 const SMDS_MeshElement* prevFace = u_int1->second._face;
1115 while ( ok && u_int2->second._coincides )
1117 if ( SMESH_MeshAlgos::GetCommonNodes(prevFace , u_int2->second._face).empty() )
1123 ok = ( u_int2 != u2inters.end() );
1129 // skip intersections at the same point after tangent intersections
1132 double u2 = u_int2->first;
1134 while ( u_int2 != u2inters.end() && fabs( u_int2->first - u2 ) < tolerance )
1140 // decide if we skipped a touching intersection
1141 if ( nbSamePnt + nbTgt > 0 )
1143 double minDot = numeric_limits<double>::max(), maxDot = -numeric_limits<double>::max();
1144 map< double, TInters >::iterator u_int = u_int1;
1145 for ( ; u_int != u_int2; ++u_int )
1147 if ( u_int->second._coincides ) continue;
1148 double dot = u_int->second._faceNorm * line.Direction();
1149 if ( dot > maxDot ) maxDot = dot;
1150 if ( dot < minDot ) minDot = dot;
1152 touchingInt = ( minDot*maxDot < 0 );
1157 if ( !hasPositionInfo || isOuterBoundary( u_int1->second._face ))
1168 u_int1 = u_int2; // to next intersection
1170 } // loop on intersections with one line
1174 if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
1177 if ( nbIntBeforePoint == 0 || nbIntAfterPoint == 0)
1180 if ( nbIntBeforePoint + nbIntAfterPoint == 1 ) // not closed mesh
1181 return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
1183 if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
1186 if ( (f<0) == (l<0) )
1189 if ( hasPositionInfo )
1190 return nbIntBeforePoint % 2 ? TopAbs_IN : TopAbs_OUT;
1192 } // loop on intersections of the tree lines - thorough analysis
1194 if ( !hasPositionInfo )
1196 // gather info on faces position - is face in the outer boundary or not
1197 map< double, TInters > & u2inters = paramOnLine2TInters[ 0 ];
1198 findOuterBoundary( u2inters.begin()->second._face );
1201 } // two attempts - with and w/o faces position info in the mesh
1203 return TopAbs_UNKNOWN;
1206 //=======================================================================
1208 * \brief Return elements possibly intersecting the line
1210 //=======================================================================
1212 void SMESH_ElementSearcherImpl::GetElementsNearLine( const gp_Ax1& line,
1213 SMDSAbs_ElementType type,
1214 vector< const SMDS_MeshElement* >& foundElems)
1216 _elementType = type;
1217 ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
1219 ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
1223 ebbTree->getElementsNearLine( line, foundElems );
1226 //=======================================================================
1228 * Return elements whose bounding box intersects a sphere
1230 //=======================================================================
1232 void SMESH_ElementSearcherImpl::GetElementsInSphere( const gp_XYZ& center,
1233 const double radius,
1234 SMDSAbs_ElementType type,
1235 vector< const SMDS_MeshElement* >& foundElems)
1237 _elementType = type;
1238 ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
1240 ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
1244 ebbTree->getElementsInSphere( center, radius, foundElems );
1247 //=======================================================================
1249 * \brief Return a projection of a given point to a mesh.
1250 * Optionally return the closest element
1252 //=======================================================================
1254 gp_XYZ SMESH_ElementSearcherImpl::Project(const gp_Pnt& point,
1255 SMDSAbs_ElementType type,
1256 const SMDS_MeshElement** closestElem)
1258 _elementType = type;
1259 if ( _mesh->GetMeshInfo().NbElements( _elementType ) == 0 )
1260 throw SALOME_Exception( LOCALIZED( "No elements of given type in the mesh" ));
1262 ElementBndBoxTree*& ebbTree = _ebbTree[ _elementType ];
1264 ebbTree = new ElementBndBoxTree( *_mesh, _elementType );
1266 gp_XYZ p = point.XYZ();
1267 ElementBndBoxTree* ebbLeaf = ebbTree->getLeafAtPoint( p );
1268 const Bnd_B3d* box = ebbLeaf->getBox();
1269 double radius = ( box->CornerMax() - box->CornerMin() ).Modulus();
1271 vector< const SMDS_MeshElement* > elems;
1272 ebbTree->getElementsInSphere( p, radius, elems );
1273 while ( elems.empty() )
1276 ebbTree->getElementsInSphere( p, radius, elems );
1278 gp_XYZ proj, bestProj;
1279 const SMDS_MeshElement* elem = 0;
1280 double minDist = 2 * radius;
1281 for ( size_t i = 0; i < elems.size(); ++i )
1283 double d = SMESH_MeshAlgos::GetDistance( elems[i], p, &proj );
1291 if ( closestElem ) *closestElem = elem;
1296 //=======================================================================
1298 * \brief Return true if the point is IN or ON of the element
1300 //=======================================================================
1302 bool SMESH_MeshAlgos::IsOut( const SMDS_MeshElement* element, const gp_Pnt& point, double tol )
1304 if ( element->GetType() == SMDSAbs_Volume)
1306 return SMDS_VolumeTool( element ).IsOut( point.X(), point.Y(), point.Z(), tol );
1309 // get ordered nodes
1311 vector< SMESH_TNodeXYZ > xyz; xyz.reserve( element->NbNodes()+1 );
1313 SMDS_ElemIteratorPtr nodeIt = element->interlacedNodesElemIterator();
1314 for ( int i = 0; nodeIt->more(); ++i )
1315 xyz.push_back( SMESH_TNodeXYZ( nodeIt->next() ));
1317 int i, nbNodes = (int) xyz.size(); // central node of biquadratic is missing
1319 if ( element->GetType() == SMDSAbs_Face ) // --------------------------------------------------
1321 // compute face normal
1322 gp_Vec faceNorm(0,0,0);
1323 xyz.push_back( xyz.front() );
1324 for ( i = 0; i < nbNodes; ++i )
1326 gp_Vec edge1( xyz[i+1], xyz[i]);
1327 gp_Vec edge2( xyz[i+1], xyz[(i+2)%nbNodes] );
1328 faceNorm += edge1 ^ edge2;
1330 double fNormSize = faceNorm.Magnitude();
1331 if ( fNormSize <= tol )
1333 // degenerated face: point is out if it is out of all face edges
1334 for ( i = 0; i < nbNodes; ++i )
1336 SMDS_LinearEdge edge( xyz[i]._node, xyz[i+1]._node );
1337 if ( !IsOut( &edge, point, tol ))
1342 faceNorm /= fNormSize;
1344 // check if the point lays on face plane
1345 gp_Vec n2p( xyz[0], point );
1346 double dot = n2p * faceNorm;
1347 if ( Abs( dot ) > tol ) // not on face plane
1350 if ( nbNodes > 3 ) // maybe the face is not planar
1352 double elemThick = 0;
1353 for ( i = 1; i < nbNodes; ++i )
1355 gp_Vec n2n( xyz[0], xyz[i] );
1356 elemThick = Max( elemThick, Abs( n2n * faceNorm ));
1358 isOut = Abs( dot ) > elemThick + tol;
1364 // check if point is out of face boundary:
1365 // define it by closest transition of a ray point->infinity through face boundary
1366 // on the face plane.
1367 // First, find normal of a plane perpendicular to face plane, to be used as a cutting tool
1368 // to find intersections of the ray with the boundary.
1370 gp_Vec plnNorm = ray ^ faceNorm;
1371 double n2pSize = plnNorm.Magnitude();
1372 if ( n2pSize <= tol ) return false; // point coincides with the first node
1373 if ( n2pSize * n2pSize > fNormSize * 100 ) return true; // point is very far
1375 // for each node of the face, compute its signed distance to the cutting plane
1376 vector<double> dist( nbNodes + 1);
1377 for ( i = 0; i < nbNodes; ++i )
1379 gp_Vec n2p( xyz[i], point );
1380 dist[i] = n2p * plnNorm;
1382 dist.back() = dist.front();
1383 // find the closest intersection
1385 double rClosest = 0, distClosest = 1e100;
1387 for ( i = 0; i < nbNodes; ++i )
1390 if ( fabs( dist[i] ) < tol )
1392 else if ( fabs( dist[i+1]) < tol )
1394 else if ( dist[i] * dist[i+1] < 0 )
1395 r = dist[i] / ( dist[i] - dist[i+1] );
1397 continue; // no intersection
1398 gp_Pnt pInt = xyz[i] * (1.-r) + xyz[i+1] * r;
1399 gp_Vec p2int( point, pInt);
1400 double intDist = p2int.SquareMagnitude();
1401 if ( intDist < distClosest )
1406 distClosest = intDist;
1410 return true; // no intesections - out
1412 // analyse transition
1413 gp_Vec edge( xyz[iClosest], xyz[iClosest+1] );
1414 gp_Vec edgeNorm = -( edge ^ faceNorm ); // normal to intersected edge pointing out of face
1415 gp_Vec p2int ( point, pClosest );
1416 bool out = (edgeNorm * p2int) < -tol;
1417 if ( rClosest > 0. && rClosest < 1. ) // not node intersection
1420 // the ray passes through a face node; analyze transition through an adjacent edge
1421 gp_Pnt p1 = xyz[ (rClosest == 0.) ? ((iClosest+nbNodes-1) % nbNodes) : (iClosest+1) ];
1422 gp_Pnt p2 = xyz[ (rClosest == 0.) ? iClosest : ((iClosest+2) % nbNodes) ];
1423 gp_Vec edgeAdjacent( p1, p2 );
1424 gp_Vec edgeNorm2 = -( edgeAdjacent ^ faceNorm );
1425 bool out2 = (edgeNorm2 * p2int) < -tol;
1427 bool covexCorner = ( edgeNorm * edgeAdjacent * (rClosest==1. ? 1. : -1.)) < 0;
1428 return covexCorner ? (out || out2) : (out && out2);
1431 if ( element->GetType() == SMDSAbs_Edge ) // --------------------------------------------------
1433 // point is out of edge if it is NOT ON any straight part of edge
1434 // (we consider quadratic edge as being composed of two straight parts)
1435 for ( i = 1; i < nbNodes; ++i )
1437 gp_Vec edge( xyz[i-1], xyz[i] );
1438 gp_Vec n1p ( xyz[i-1], point );
1439 double u = ( edge * n1p ) / edge.SquareMagnitude(); // param [0,1] on the edge
1441 if ( n1p.SquareMagnitude() < tol * tol )
1446 if ( point.SquareDistance( xyz[i] ) < tol * tol )
1450 gp_XYZ proj = ( 1. - u ) * xyz[i-1] + u * xyz[i]; // projection of the point on the edge
1451 double dist2 = point.SquareDistance( proj );
1452 if ( dist2 > tol * tol )
1454 return false; // point is ON this part
1459 // Node or 0D element -------------------------------------------------------------------------
1461 gp_Vec n2p ( xyz[0], point );
1462 return n2p.SquareMagnitude() > tol * tol;
1467 //=======================================================================
1470 // Position of a point relative to a segment
1474 // VERTEX 1 o----ON-----> VERTEX 2
1478 enum PositionName { POS_LEFT = 1, POS_VERTEX = 2, POS_RIGHT = 4, //POS_ON = 8,
1479 POS_ALL = POS_LEFT | POS_RIGHT | POS_VERTEX };
1483 int _index; // index of vertex or segment
1485 PointPos( PositionName n, int i=-1 ): _name(n), _index(i) {}
1486 bool operator < (const PointPos& other ) const
1488 if ( _name == other._name )
1489 return ( _index < 0 || other._index < 0 ) ? false : _index < other._index;
1490 return _name < other._name;
1494 //================================================================================
1496 * \brief Return of a point relative to a segment
1497 * \param point2D - the point to analyze position of
1498 * \param xyVec - end points of segments
1499 * \param index0 - 0-based index of the first point of segment
1500 * \param posToFindOut - flags of positions to detect
1501 * \retval PointPos - point position
1503 //================================================================================
1505 PointPos getPointPosition( const gp_XY& point2D,
1506 const gp_XY* segEnds,
1507 const int index0 = 0,
1508 const int posToFindOut = POS_ALL)
1510 const gp_XY& p1 = segEnds[ index0 ];
1511 const gp_XY& p2 = segEnds[ index0+1 ];
1512 const gp_XY grad = p2 - p1;
1514 if ( posToFindOut & POS_VERTEX )
1516 // check if the point2D is at "vertex 1" zone
1517 gp_XY pp1[2] = { p1, gp_XY( p1.X() - grad.Y(),
1518 p1.Y() + grad.X() ) };
1519 if ( getPointPosition( point2D, pp1, 0, POS_LEFT|POS_RIGHT )._name == POS_LEFT )
1520 return PointPos( POS_VERTEX, index0 );
1522 // check if the point2D is at "vertex 2" zone
1523 gp_XY pp2[2] = { p2, gp_XY( p2.X() - grad.Y(),
1524 p2.Y() + grad.X() ) };
1525 if ( getPointPosition( point2D, pp2, 0, POS_LEFT|POS_RIGHT )._name == POS_RIGHT )
1526 return PointPos( POS_VERTEX, index0 + 1);
1528 double edgeEquation =
1529 ( point2D.X() - p1.X() ) * grad.Y() - ( point2D.Y() - p1.Y() ) * grad.X();
1530 return PointPos( edgeEquation < 0 ? POS_LEFT : POS_RIGHT, index0 );
1534 //=======================================================================
1536 * \brief Return minimal distance from a point to an element
1538 * Currently we ignore non-planarity and 2nd order of face
1540 //=======================================================================
1542 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshElement* elem,
1543 const gp_Pnt& point,
1544 gp_XYZ* closestPnt )
1546 switch ( elem->GetType() )
1548 case SMDSAbs_Volume:
1549 return GetDistance( dynamic_cast<const SMDS_MeshVolume*>( elem ), point, closestPnt );
1551 return GetDistance( dynamic_cast<const SMDS_MeshFace*>( elem ), point, closestPnt );
1553 return GetDistance( dynamic_cast<const SMDS_MeshEdge*>( elem ), point, closestPnt );
1555 if ( closestPnt ) *closestPnt = SMESH_TNodeXYZ( elem );
1556 return point.Distance( SMESH_TNodeXYZ( elem ));
1562 //=======================================================================
1564 * \brief Return minimal distance from a point to a face
1566 * Currently we ignore non-planarity and 2nd order of face
1568 //=======================================================================
1570 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshFace* face,
1571 const gp_Pnt& point,
1572 gp_XYZ* closestPnt )
1574 const double badDistance = -1;
1575 if ( !face ) return badDistance;
1577 // coordinates of nodes (medium nodes, if any, ignored)
1578 typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
1579 vector<gp_XYZ> xyz( TXyzIterator( face->nodesIterator()), TXyzIterator() );
1580 xyz.resize( face->NbCornerNodes()+1 );
1582 // transformation to get xyz[0] lies on the origin, xyz[1] lies on the Z axis,
1583 // and xyz[2] lies in the XZ plane. This is to pass to 2D space on XZ plane.
1585 gp_Vec OZ ( xyz[0], xyz[1] );
1586 gp_Vec OX ( xyz[0], xyz[2] );
1587 if ( OZ.Magnitude() < std::numeric_limits<double>::min() )
1589 if ( xyz.size() < 4 ) return badDistance;
1590 OZ = gp_Vec ( xyz[0], xyz[2] );
1591 OX = gp_Vec ( xyz[0], xyz[3] );
1595 tgtCS = gp_Ax3( xyz[0], OZ, OX );
1597 catch ( Standard_Failure ) {
1600 trsf.SetTransformation( tgtCS );
1602 // move all the nodes to 2D
1603 vector<gp_XY> xy( xyz.size() );
1604 for ( size_t i = 0;i < xyz.size()-1; ++i )
1606 gp_XYZ p3d = xyz[i];
1607 trsf.Transforms( p3d );
1608 xy[i].SetCoord( p3d.X(), p3d.Z() );
1610 xyz.back() = xyz.front();
1611 xy.back() = xy.front();
1613 // // move the point in 2D
1614 gp_XYZ tmpPnt = point.XYZ();
1615 trsf.Transforms( tmpPnt );
1616 gp_XY point2D( tmpPnt.X(), tmpPnt.Z() );
1618 // loop on edges of the face to analyze point position ralative to the face
1619 set< PointPos > pntPosSet;
1620 for ( size_t i = 1; i < xy.size(); ++i )
1622 PointPos pos = getPointPosition( point2D, &xy[0], i-1 );
1623 pntPosSet.insert( pos );
1627 PointPos pos = *pntPosSet.begin();
1628 switch ( pos._name )
1632 // point is most close to an edge
1633 gp_Vec edge( xyz[ pos._index ], xyz[ pos._index+1 ]);
1634 gp_Vec n1p ( xyz[ pos._index ], point );
1635 double u = ( edge * n1p ) / edge.SquareMagnitude(); // param [0,1] on the edge
1636 // projection of the point on the edge
1637 gp_XYZ proj = ( 1. - u ) * xyz[ pos._index ] + u * xyz[ pos._index+1 ];
1638 if ( closestPnt ) *closestPnt = proj;
1639 return point.Distance( proj );
1643 // point is inside the face
1644 double distToFacePlane = Abs( tmpPnt.Y() );
1647 if ( distToFacePlane < std::numeric_limits<double>::min() ) {
1648 *closestPnt = point.XYZ();
1652 trsf.Inverted().Transforms( tmpPnt );
1653 *closestPnt = tmpPnt;
1656 return distToFacePlane;
1660 // point is most close to a node
1661 gp_Vec distVec( point, xyz[ pos._index ]);
1662 return distVec.Magnitude();
1669 //=======================================================================
1671 * \brief Return minimal distance from a point to an edge
1673 //=======================================================================
1675 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshEdge* seg,
1676 const gp_Pnt& point,
1677 gp_XYZ* closestPnt )
1679 double dist = Precision::Infinite();
1680 if ( !seg ) return dist;
1682 int i = 0, nbNodes = seg->NbNodes();
1684 vector< SMESH_TNodeXYZ > xyz( nbNodes );
1685 SMDS_ElemIteratorPtr nodeIt = seg->interlacedNodesElemIterator();
1686 while ( nodeIt->more() )
1687 xyz[ i++ ].Set( nodeIt->next() );
1689 for ( i = 1; i < nbNodes; ++i )
1691 gp_Vec edge( xyz[i-1], xyz[i] );
1692 gp_Vec n1p ( xyz[i-1], point );
1693 double u = ( edge * n1p ) / edge.SquareMagnitude(); // param [0,1] on the edge
1695 dist = Min( dist, n1p.SquareMagnitude() );
1696 if ( closestPnt ) *closestPnt = xyz[i-1];
1698 else if ( u >= 1. ) {
1699 dist = Min( dist, point.SquareDistance( xyz[i] ));
1700 if ( closestPnt ) *closestPnt = xyz[i];
1703 gp_XYZ proj = ( 1. - u ) * xyz[i-1] + u * xyz[i]; // projection of the point on the edge
1704 dist = Min( dist, point.SquareDistance( proj ));
1705 if ( closestPnt ) *closestPnt = proj;
1708 return Sqrt( dist );
1711 //=======================================================================
1713 * \brief Return minimal distance from a point to a volume
1715 * Currently we ignore non-planarity and 2nd order
1717 //=======================================================================
1719 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshVolume* volume,
1720 const gp_Pnt& point,
1721 gp_XYZ* closestPnt )
1723 SMDS_VolumeTool vTool( volume );
1724 vTool.SetExternalNormal();
1725 const int iQ = volume->IsQuadratic() ? 2 : 1;
1728 double minDist = 1e100, dist;
1729 gp_XYZ closeP = point.XYZ();
1731 for ( int iF = 0; iF < vTool.NbFaces(); ++iF )
1733 // skip a facet with normal not "looking at" the point
1734 if ( !vTool.GetFaceNormal( iF, n[0], n[1], n[2] ) ||
1735 !vTool.GetFaceBaryCenter( iF, bc[0], bc[1], bc[2] ))
1737 gp_XYZ bcp = point.XYZ() - gp_XYZ( bc[0], bc[1], bc[2] );
1738 if ( gp_XYZ( n[0], n[1], n[2] ) * bcp < 1e-6 )
1741 // find distance to a facet
1742 const SMDS_MeshNode** nodes = vTool.GetFaceNodes( iF );
1743 switch ( vTool.NbFaceNodes( iF ) / iQ ) {
1746 SMDS_FaceOfNodes tmpFace( nodes[0], nodes[ 1*iQ ], nodes[ 2*iQ ] );
1747 dist = GetDistance( &tmpFace, point, closestPnt );
1752 SMDS_FaceOfNodes tmpFace( nodes[0], nodes[ 1*iQ ], nodes[ 2*iQ ], nodes[ 3*iQ ]);
1753 dist = GetDistance( &tmpFace, point, closestPnt );
1757 vector<const SMDS_MeshNode *> nvec( nodes, nodes + vTool.NbFaceNodes( iF ));
1758 SMDS_PolygonalFaceOfNodes tmpFace( nvec );
1759 dist = GetDistance( &tmpFace, point, closestPnt );
1761 if ( dist < minDist )
1765 if ( closestPnt ) closeP = *closestPnt;
1770 if ( closestPnt ) *closestPnt = closeP;
1774 return 0; // point is inside the volume
1777 //================================================================================
1779 * \brief Returns barycentric coordinates of a point within a triangle.
1780 * A not returned bc2 = 1. - bc0 - bc1.
1781 * The point lies within the triangle if ( bc0 >= 0 && bc1 >= 0 && bc0+bc1 <= 1 )
1783 //================================================================================
1785 void SMESH_MeshAlgos::GetBarycentricCoords( const gp_XY& p,
1792 const double // matrix 2x2
1793 T11 = t0.X()-t2.X(), T12 = t1.X()-t2.X(),
1794 T21 = t0.Y()-t2.Y(), T22 = t1.Y()-t2.Y();
1795 const double Tdet = T11*T22 - T12*T21; // matrix determinant
1796 if ( Abs( Tdet ) < std::numeric_limits<double>::min() )
1802 const double t11 = T22, t12 = -T12, t21 = -T21, t22 = T11;
1804 const double r11 = p.X()-t2.X(), r12 = p.Y()-t2.Y();
1805 // barycentric coordinates: mutiply matrix by vector
1806 bc0 = (t11 * r11 + t12 * r12)/Tdet;
1807 bc1 = (t21 * r11 + t22 * r12)/Tdet;
1810 //=======================================================================
1811 //function : FindFaceInSet
1812 //purpose : Return a face having linked nodes n1 and n2 and which is
1813 // - not in avoidSet,
1814 // - in elemSet provided that !elemSet.empty()
1815 // i1 and i2 optionally returns indices of n1 and n2
1816 //=======================================================================
1818 const SMDS_MeshElement*
1819 SMESH_MeshAlgos::FindFaceInSet(const SMDS_MeshNode* n1,
1820 const SMDS_MeshNode* n2,
1821 const TIDSortedElemSet& elemSet,
1822 const TIDSortedElemSet& avoidSet,
1828 const SMDS_MeshElement* face = 0;
1830 SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator(SMDSAbs_Face);
1831 while ( invElemIt->more() && !face ) // loop on inverse faces of n1
1833 const SMDS_MeshElement* elem = invElemIt->next();
1834 if (avoidSet.count( elem ))
1836 if ( !elemSet.empty() && !elemSet.count( elem ))
1839 i1 = elem->GetNodeIndex( n1 );
1840 // find a n2 linked to n1
1841 int nbN = elem->IsQuadratic() ? elem->NbNodes()/2 : elem->NbNodes();
1842 for ( int di = -1; di < 2 && !face; di += 2 )
1844 i2 = (i1+di+nbN) % nbN;
1845 if ( elem->GetNode( i2 ) == n2 )
1848 if ( !face && elem->IsQuadratic())
1850 // analysis for quadratic elements using all nodes
1851 SMDS_ElemIteratorPtr anIter = elem->interlacedNodesElemIterator();
1852 const SMDS_MeshNode* prevN = static_cast<const SMDS_MeshNode*>( anIter->next() );
1853 for ( i1 = -1, i2 = 0; anIter->more() && !face; i1++, i2++ )
1855 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( anIter->next() );
1856 if ( n1 == prevN && n2 == n )
1860 else if ( n2 == prevN && n1 == n )
1862 face = elem; swap( i1, i2 );
1868 if ( n1ind ) *n1ind = i1;
1869 if ( n2ind ) *n2ind = i2;
1873 //================================================================================
1875 * \brief Calculate normal of a mesh face
1877 //================================================================================
1879 bool SMESH_MeshAlgos::FaceNormal(const SMDS_MeshElement* F, gp_XYZ& normal, bool normalized)
1881 if ( !F || F->GetType() != SMDSAbs_Face )
1884 normal.SetCoord(0,0,0);
1885 int nbNodes = F->NbCornerNodes();
1886 for ( int i = 0; i < nbNodes-2; ++i )
1889 for ( int n = 0; n < 3; ++n )
1891 const SMDS_MeshNode* node = F->GetNode( i + n );
1892 p[n].SetCoord( node->X(), node->Y(), node->Z() );
1894 normal += ( p[2] - p[1] ) ^ ( p[0] - p[1] );
1896 double size2 = normal.SquareModulus();
1897 bool ok = ( size2 > numeric_limits<double>::min() * numeric_limits<double>::min());
1898 if ( normalized && ok )
1899 normal /= sqrt( size2 );
1904 //=======================================================================
1905 //function : GetCommonNodes
1906 //purpose : Return nodes common to two elements
1907 //=======================================================================
1909 vector< const SMDS_MeshNode*> SMESH_MeshAlgos::GetCommonNodes(const SMDS_MeshElement* e1,
1910 const SMDS_MeshElement* e2)
1912 vector< const SMDS_MeshNode*> common;
1913 for ( int i = 0 ; i < e1->NbNodes(); ++i )
1914 if ( e2->GetNodeIndex( e1->GetNode( i )) >= 0 )
1915 common.push_back( e1->GetNode( i ));
1919 //=======================================================================
1921 * \brief Return SMESH_NodeSearcher
1923 //=======================================================================
1925 SMESH_NodeSearcher* SMESH_MeshAlgos::GetNodeSearcher(SMDS_Mesh& mesh)
1927 return new SMESH_NodeSearcherImpl( &mesh );
1930 //=======================================================================
1932 * \brief Return SMESH_NodeSearcher
1934 //=======================================================================
1936 SMESH_NodeSearcher* SMESH_MeshAlgos::GetNodeSearcher(SMDS_ElemIteratorPtr elemIt)
1938 return new SMESH_NodeSearcherImpl( 0, elemIt );
1941 //=======================================================================
1943 * \brief Return SMESH_ElementSearcher
1945 //=======================================================================
1947 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh& mesh,
1950 return new SMESH_ElementSearcherImpl( mesh, tolerance );
1953 //=======================================================================
1955 * \brief Return SMESH_ElementSearcher acting on a sub-set of elements
1957 //=======================================================================
1959 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh& mesh,
1960 SMDS_ElemIteratorPtr elemIt,
1963 return new SMESH_ElementSearcherImpl( mesh, tolerance, elemIt );