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>
51 #include <boost/container/flat_set.hpp>
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 std::map<double, const SMDS_MeshNode*> dist2Nodes;
114 myOctreeNode->NodesAround( thePnt.Coord(), dist2Nodes, myHalfLeafSize );
115 if ( !dist2Nodes.empty() )
116 return dist2Nodes.begin()->second;
117 std::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 std::map< double, SMESH_OctreeNode* > TDistTreeMap;
125 TDistTreeMap treeMap;
126 std::list< SMESH_OctreeNode* > treeList;
127 std::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 std::pair<TDistTreeMap::iterator,bool> it_in =
147 treeMap.insert( std::make_pair( sqDist, tree ));
148 if ( !it_in.second ) // not unique distance to box center
149 treeMap.insert( it_in.first, std::make_pair( sqDist + 1e-13*treeMap.size(), tree ));
152 // find distance after which there is no sense to check tree's
153 double sqLimit = DBL_MAX;
154 TDistTreeMap::iterator sqDist_tree = treeMap.begin();
155 if ( treeMap.size() > 5 ) {
156 SMESH_OctreeNode* closestTree = sqDist_tree->second;
157 const Bnd_B3d& box = *closestTree->getBox();
158 double limit = sqrt( sqDist_tree->first ) + sqrt ( box.SquareExtent() );
159 sqLimit = limit * limit;
161 // get all nodes from trees
162 for ( ; sqDist_tree != treeMap.end(); ++sqDist_tree) {
163 if ( sqDist_tree->first > sqLimit )
165 SMESH_OctreeNode* tree = sqDist_tree->second;
166 tree->NodesAround( tree->GetNodeIterator()->next(), &nodes );
169 // find closest among nodes
171 const SMDS_MeshNode* closestNode = 0;
172 std::list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
173 for ( ; nIt != nodes.end(); ++nIt ) {
174 double sqDist = thePnt.SquareDistance( SMESH_TNodeXYZ( *nIt ) );
175 if ( minSqDist > sqDist ) {
183 //---------------------------------------------------------------------
185 * \brief Finds nodes located within a tolerance near a point
187 int FindNearPoint(const gp_Pnt& point,
188 const double tolerance,
189 std::vector< const SMDS_MeshNode* >& foundNodes)
191 myOctreeNode->NodesAround( point.Coord(), foundNodes, tolerance );
192 return foundNodes.size();
195 //---------------------------------------------------------------------
199 ~SMESH_NodeSearcherImpl() { delete myOctreeNode; }
201 //---------------------------------------------------------------------
203 * \brief Return the node tree
205 const SMESH_OctreeNode* getTree() const { return myOctreeNode; }
208 SMESH_OctreeNode* myOctreeNode;
210 double myHalfLeafSize; // max size of a leaf box
213 // ========================================================================
214 namespace // Utils used in SMESH_ElementSearcherImpl::FindElementsByPoint()
216 const int MaxNbElemsInLeaf = 10; // maximal number of elements in a leaf of tree
217 const int MaxLevel = 7; // maximal tree height -> nb terminal boxes: 8^7 = 2097152
218 const double NodeRadius = 1e-9; // to enlarge bnd box of element
220 //=======================================================================
222 * \brief Octal tree of bounding boxes of elements
224 //=======================================================================
226 class ElementBndBoxTree : public SMESH_Octree
230 typedef boost::container::flat_set< const SMDS_MeshElement* > TElemSeq;
232 ElementBndBoxTree(const SMDS_Mesh& mesh,
233 SMDSAbs_ElementType elemType,
234 SMDS_ElemIteratorPtr theElemIt = SMDS_ElemIteratorPtr(),
235 double tolerance = NodeRadius );
236 void getElementsNearPoint( const gp_Pnt& point, TElemSeq& foundElems );
237 void getElementsNearLine ( const gp_Ax1& line, TElemSeq& foundElems );
238 void getElementsInBox ( const Bnd_B3d& box, TElemSeq& foundElems );
239 void getElementsInSphere ( const gp_XYZ& center, const double radius, TElemSeq& foundElems );
240 ElementBndBoxTree* getLeafAtPoint( const gp_XYZ& point );
243 ElementBndBoxTree() {}
244 SMESH_Octree* newChild() const { return new ElementBndBoxTree; }
245 void buildChildrenData();
246 Bnd_B3d* buildRootBox();
248 //!< Bounding box of element
249 struct ElementBox : public Bnd_B3d
251 const SMDS_MeshElement* _element;
252 void init(const SMDS_MeshElement* elem, double tolerance);
254 std::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 LimitAndPool():SMESH_TreeLimit( MaxLevel, /*minSize=*/0. ), _elBoPool(1024) {}
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, TElemSeq& foundElems)
350 if ( getBox()->IsOut( point.XYZ() ))
355 for ( size_t i = 0; i < _elements.size(); ++i )
356 if ( !_elements[i]->IsOut( point.XYZ() ))
357 foundElems.insert( _elements[i]->_element );
361 for (int i = 0; i < 8; i++)
362 ((ElementBndBoxTree*) myChildren[i])->getElementsNearPoint( point, foundElems );
366 //================================================================================
368 * \brief Return elements which can be intersected by the line
370 //================================================================================
372 void ElementBndBoxTree::getElementsNearLine( const gp_Ax1& line, TElemSeq& foundElems )
374 if ( getBox()->IsOut( line ))
379 for ( size_t i = 0; i < _elements.size(); ++i )
380 if ( !_elements[i]->IsOut( line ) )
381 foundElems.insert( _elements[i]->_element );
385 for (int i = 0; i < 8; i++)
386 ((ElementBndBoxTree*) myChildren[i])->getElementsNearLine( line, foundElems );
390 //================================================================================
392 * \brief Return elements from leaves intersecting the sphere
394 //================================================================================
396 void ElementBndBoxTree::getElementsInSphere ( const gp_XYZ& center,
398 TElemSeq& foundElems)
400 if ( getBox()->IsOut( center, radius ))
405 for ( size_t i = 0; i < _elements.size(); ++i )
406 if ( !_elements[i]->IsOut( center, radius ))
407 foundElems.insert( _elements[i]->_element );
411 for (int i = 0; i < 8; i++)
412 ((ElementBndBoxTree*) myChildren[i])->getElementsInSphere( center, radius, foundElems );
416 //================================================================================
418 * \brief Return elements from leaves intersecting the box
420 //================================================================================
422 void ElementBndBoxTree::getElementsInBox( const Bnd_B3d& box, TElemSeq& foundElems )
424 if ( getBox()->IsOut( box ))
429 for ( size_t i = 0; i < _elements.size(); ++i )
430 if ( !_elements[i]->IsOut( box ))
431 foundElems.insert( _elements[i]->_element );
435 for (int i = 0; i < 8; i++)
436 ((ElementBndBoxTree*) myChildren[i])->getElementsInBox( box, foundElems );
440 //================================================================================
442 * \brief Return a leaf including a point
444 //================================================================================
446 ElementBndBoxTree* ElementBndBoxTree::getLeafAtPoint( const gp_XYZ& point )
448 if ( getBox()->IsOut( point ))
457 for (int i = 0; i < 8; i++)
458 if ( ElementBndBoxTree* l = ((ElementBndBoxTree*) myChildren[i])->getLeafAtPoint( point ))
464 //================================================================================
466 * \brief Construct the element box
468 //================================================================================
470 void ElementBndBoxTree::ElementBox::init(const SMDS_MeshElement* elem, double tolerance)
473 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
474 while ( nIt->more() )
475 Add( SMESH_NodeXYZ( nIt->next() ));
476 Enlarge( tolerance );
481 //=======================================================================
483 * \brief Implementation of search for the elements by point and
484 * of classification of point in 2D mesh
486 //=======================================================================
488 SMESH_ElementSearcher::~SMESH_ElementSearcher()
492 struct SMESH_ElementSearcherImpl: public SMESH_ElementSearcher
495 SMDS_ElemIteratorPtr _meshPartIt;
496 ElementBndBoxTree* _ebbTree [SMDSAbs_NbElementTypes];
497 int _ebbTreeHeight[SMDSAbs_NbElementTypes];
498 SMESH_NodeSearcherImpl* _nodeSearcher;
499 SMDSAbs_ElementType _elementType;
501 bool _outerFacesFound;
502 std::set<const SMDS_MeshElement*> _outerFaces; // empty means "no internal faces at all"
504 SMESH_ElementSearcherImpl( SMDS_Mesh& mesh,
506 SMDS_ElemIteratorPtr elemIt=SMDS_ElemIteratorPtr())
507 : _mesh(&mesh),_meshPartIt(elemIt),_nodeSearcher(0),_tolerance(tol),_outerFacesFound(false)
509 for ( int i = 0; i < SMDSAbs_NbElementTypes; ++i )
512 _ebbTreeHeight[i] = -1;
514 _elementType = SMDSAbs_All;
516 virtual ~SMESH_ElementSearcherImpl()
518 for ( int i = 0; i < SMDSAbs_NbElementTypes; ++i )
520 delete _ebbTree[i]; _ebbTree[i] = NULL;
522 if ( _nodeSearcher ) delete _nodeSearcher; _nodeSearcher = 0;
524 virtual int FindElementsByPoint(const gp_Pnt& point,
525 SMDSAbs_ElementType type,
526 std::vector< const SMDS_MeshElement* >& foundElements);
527 virtual TopAbs_State GetPointState(const gp_Pnt& point);
528 virtual const SMDS_MeshElement* FindClosestTo( const gp_Pnt& point,
529 SMDSAbs_ElementType type );
531 virtual void GetElementsNearLine( const gp_Ax1& line,
532 SMDSAbs_ElementType type,
533 std::vector< const SMDS_MeshElement* >& foundElems);
534 virtual void GetElementsInSphere( const gp_XYZ& center,
536 SMDSAbs_ElementType type,
537 std::vector< const SMDS_MeshElement* >& foundElems);
538 virtual void GetElementsInBox( const Bnd_B3d& box,
539 SMDSAbs_ElementType type,
540 std::vector< const SMDS_MeshElement* >& foundElems);
541 virtual gp_XYZ Project(const gp_Pnt& point,
542 SMDSAbs_ElementType type,
543 const SMDS_MeshElement** closestElem);
544 double getTolerance();
545 bool getIntersParamOnLine(const gp_Lin& line, const SMDS_MeshElement* face,
546 const double tolerance, double & param);
547 void findOuterBoundary(const SMDS_MeshElement* anyOuterFace);
548 bool isOuterBoundary(const SMDS_MeshElement* face) const
550 return _outerFaces.empty() || _outerFaces.count(face);
554 if ( _ebbTreeHeight[ _elementType ] < 0 )
555 _ebbTreeHeight[ _elementType ] = _ebbTree[ _elementType ]->getHeight();
556 return _ebbTreeHeight[ _elementType ];
559 struct TInters //!< data of intersection of the line and the mesh face (used in GetPointState())
561 const SMDS_MeshElement* _face;
563 bool _coincides; //!< the line lays in face plane
564 TInters(const SMDS_MeshElement* face, const gp_Vec& faceNorm, bool coinc=false)
565 : _face(face), _faceNorm( faceNorm ), _coincides( coinc ) {}
567 struct TFaceLink //!< link and faces sharing it (used in findOuterBoundary())
570 TIDSortedElemSet _faces;
571 TFaceLink( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshElement* face)
572 : _link( n1, n2 ), _faces( &face, &face + 1) {}
576 ostream& operator<< (ostream& out, const SMESH_ElementSearcherImpl::TInters& i)
578 return out << "TInters(face=" << ( i._face ? i._face->GetID() : 0)
579 << ", _coincides="<<i._coincides << ")";
582 //=======================================================================
584 * \brief define tolerance for search
586 //=======================================================================
588 double SMESH_ElementSearcherImpl::getTolerance()
590 if ( _tolerance < 0 )
592 const SMDS_MeshInfo& meshInfo = _mesh->GetMeshInfo();
595 if ( _nodeSearcher && meshInfo.NbNodes() > 1 )
597 double boxSize = _nodeSearcher->getTree()->maxSize();
598 _tolerance = 1e-8 * boxSize/* / meshInfo.NbNodes()*/;
600 else if ( _ebbTree[_elementType] && meshInfo.NbElements() > 0 )
602 double boxSize = _ebbTree[_elementType]->maxSize();
603 _tolerance = 1e-8 * boxSize/* / meshInfo.NbElements()*/;
605 if ( _tolerance == 0 )
607 // define tolerance by size of a most complex element
608 int complexType = SMDSAbs_Volume;
609 while ( complexType > SMDSAbs_All &&
610 meshInfo.NbElements( SMDSAbs_ElementType( complexType )) < 1 )
612 if ( complexType == SMDSAbs_All ) return 0; // empty mesh
614 if ( complexType == int( SMDSAbs_Node ))
616 SMDS_NodeIteratorPtr nodeIt = _mesh->nodesIterator();
618 if ( meshInfo.NbNodes() > 2 )
619 elemSize = SMESH_TNodeXYZ( nodeIt->next() ).Distance( nodeIt->next() );
623 SMDS_ElemIteratorPtr elemIt = _mesh->elementsIterator( SMDSAbs_ElementType( complexType ));
624 const SMDS_MeshElement* elem = elemIt->next();
625 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
626 SMESH_TNodeXYZ n1( nodeIt->next() );
628 while ( nodeIt->more() )
630 double dist = n1.Distance( static_cast<const SMDS_MeshNode*>( nodeIt->next() ));
631 elemSize = std::max( dist, elemSize );
634 _tolerance = 1e-4 * elemSize;
640 //================================================================================
642 * \brief Find intersection of the line and an edge of face and return parameter on line
644 //================================================================================
646 bool SMESH_ElementSearcherImpl::getIntersParamOnLine(const gp_Lin& line,
647 const SMDS_MeshElement* face,
654 GeomAPI_ExtremaCurveCurve anExtCC;
655 Handle(Geom_Curve) lineCurve = new Geom_Line( line );
657 int nbNodes = face->IsQuadratic() ? face->NbNodes()/2 : face->NbNodes();
658 for ( int i = 0; i < nbNodes && nbInts < 2; ++i )
660 GC_MakeSegment edge( SMESH_TNodeXYZ( face->GetNode( i )),
661 SMESH_TNodeXYZ( face->GetNode( (i+1)%nbNodes) ));
662 anExtCC.Init( lineCurve, edge.Value() );
663 if ( anExtCC.NbExtrema() > 0 && anExtCC.LowerDistance() <= tol)
665 Standard_Real pl, pe;
666 anExtCC.LowerDistanceParameters( pl, pe );
672 if ( nbInts > 0 ) param /= nbInts;
675 //================================================================================
677 * \brief Find all faces belonging to the outer boundary of mesh
679 //================================================================================
681 void SMESH_ElementSearcherImpl::findOuterBoundary(const SMDS_MeshElement* outerFace)
683 if ( _outerFacesFound ) return;
685 // Collect all outer faces by passing from one outer face to another via their links
686 // and BTW find out if there are internal faces at all.
688 // checked links and links where outer boundary meets internal one
689 std::set< SMESH_TLink > visitedLinks, seamLinks;
691 // links to treat with already visited faces sharing them
692 std::list < TFaceLink > startLinks;
694 // load startLinks with the first outerFace
695 startLinks.push_back( TFaceLink( outerFace->GetNode(0), outerFace->GetNode(1), outerFace));
696 _outerFaces.insert( outerFace );
698 TIDSortedElemSet emptySet;
699 while ( !startLinks.empty() )
701 const SMESH_TLink& link = startLinks.front()._link;
702 TIDSortedElemSet& faces = startLinks.front()._faces;
704 outerFace = *faces.begin();
705 // find other faces sharing the link
706 const SMDS_MeshElement* f;
707 while (( f = SMESH_MeshAlgos::FindFaceInSet(link.node1(), link.node2(), emptySet, faces )))
710 // select another outer face among the found
711 const SMDS_MeshElement* outerFace2 = 0;
712 if ( faces.size() == 2 )
714 outerFace2 = (outerFace == *faces.begin() ? *faces.rbegin() : *faces.begin());
716 else if ( faces.size() > 2 )
718 seamLinks.insert( link );
720 // link direction within the outerFace
721 gp_Vec n1n2( SMESH_TNodeXYZ( link.node1()),
722 SMESH_TNodeXYZ( link.node2()));
723 int i1 = outerFace->GetNodeIndex( link.node1() );
724 int i2 = outerFace->GetNodeIndex( link.node2() );
725 bool rev = ( abs(i2-i1) == 1 ? i1 > i2 : i2 > i1 );
726 if ( rev ) n1n2.Reverse();
728 gp_XYZ ofNorm, fNorm;
729 if ( SMESH_MeshAlgos::FaceNormal( outerFace, ofNorm, /*normalized=*/false ))
731 // direction from the link inside outerFace
732 gp_Vec dirInOF = gp_Vec( ofNorm ) ^ n1n2;
733 // sort all other faces by angle with the dirInOF
734 std::map< double, const SMDS_MeshElement* > angle2Face;
735 std::set< const SMDS_MeshElement*, TIDCompare >::const_iterator face = faces.begin();
736 for ( ; face != faces.end(); ++face )
738 if ( *face == outerFace ) continue;
739 if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false ))
741 gp_Vec dirInF = gp_Vec( fNorm ) ^ n1n2;
742 double angle = dirInOF.AngleWithRef( dirInF, n1n2 );
743 if ( angle < 0 ) angle += 2. * M_PI;
744 angle2Face.insert( std::make_pair( angle, *face ));
746 if ( !angle2Face.empty() )
747 outerFace2 = angle2Face.begin()->second;
750 // store the found outer face and add its links to continue searching from
753 _outerFaces.insert( outerFace2 );
754 int nbNodes = outerFace2->NbCornerNodes();
755 for ( int i = 0; i < nbNodes; ++i )
757 SMESH_TLink link2( outerFace2->GetNode(i), outerFace2->GetNode((i+1)%nbNodes));
758 if ( visitedLinks.insert( link2 ).second )
759 startLinks.push_back( TFaceLink( link2.node1(), link2.node2(), outerFace2 ));
762 startLinks.pop_front();
764 _outerFacesFound = true;
766 if ( !seamLinks.empty() )
768 // There are internal boundaries touching the outher one,
769 // find all faces of internal boundaries in order to find
770 // faces of boundaries of holes, if any.
779 //=======================================================================
781 * \brief Find elements of given type where the given point is IN or ON.
782 * Returns nb of found elements and elements them-selves.
784 * 'ALL' type means elements of any type excluding nodes, balls and 0D elements
786 //=======================================================================
788 int SMESH_ElementSearcherImpl::
789 FindElementsByPoint(const gp_Pnt& point,
790 SMDSAbs_ElementType type,
791 std::vector< const SMDS_MeshElement* >& foundElements)
793 foundElements.clear();
796 double tolerance = getTolerance();
798 // =================================================================================
799 if ( type == SMDSAbs_Node || type == SMDSAbs_0DElement || type == SMDSAbs_Ball)
801 if ( !_nodeSearcher )
804 _nodeSearcher = new SMESH_NodeSearcherImpl( 0, _meshPartIt );
806 _nodeSearcher = new SMESH_NodeSearcherImpl( _mesh );
808 std::vector< const SMDS_MeshNode* > foundNodes;
809 _nodeSearcher->FindNearPoint( point, tolerance, foundNodes );
811 if ( type == SMDSAbs_Node )
813 foundElements.assign( foundNodes.begin(), foundNodes.end() );
817 for ( size_t i = 0; i < foundNodes.size(); ++i )
819 SMDS_ElemIteratorPtr elemIt = foundNodes[i]->GetInverseElementIterator( type );
820 while ( elemIt->more() )
821 foundElements.push_back( elemIt->next() );
825 // =================================================================================
826 else // elements more complex than 0D
828 if ( !_ebbTree[type] )
830 _ebbTree[_elementType] = new ElementBndBoxTree( *_mesh, type, _meshPartIt, tolerance );
832 ElementBndBoxTree::TElemSeq suspectElems;
833 _ebbTree[ type ]->getElementsNearPoint( point, suspectElems );
834 ElementBndBoxTree::TElemSeq::iterator elem = suspectElems.begin();
835 for ( ; elem != suspectElems.end(); ++elem )
836 if ( !SMESH_MeshAlgos::IsOut( *elem, point, tolerance ))
837 foundElements.push_back( *elem );
839 return foundElements.size();
842 //=======================================================================
844 * \brief Find an element of given type most close to the given point
846 * WARNING: Only face search is implemeneted so far
848 //=======================================================================
850 const SMDS_MeshElement*
851 SMESH_ElementSearcherImpl::FindClosestTo( const gp_Pnt& point,
852 SMDSAbs_ElementType type )
854 const SMDS_MeshElement* closestElem = 0;
857 if ( type == SMDSAbs_Face ||
858 type == SMDSAbs_Volume ||
859 type == SMDSAbs_Edge )
861 ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
863 ebbTree = new ElementBndBoxTree( *_mesh, type, _meshPartIt );
865 ElementBndBoxTree::TElemSeq suspectElems;
866 ebbTree->getElementsNearPoint( point, suspectElems );
868 if ( suspectElems.empty() && ebbTree->maxSize() > 0 )
870 gp_Pnt boxCenter = 0.5 * ( ebbTree->getBox()->CornerMin() +
871 ebbTree->getBox()->CornerMax() );
873 if ( ebbTree->getBox()->IsOut( point.XYZ() ))
874 radius = point.Distance( boxCenter ) - 0.5 * ebbTree->maxSize();
876 radius = ebbTree->maxSize() / pow( 2., getTreeHeight()) / 2;
877 while ( suspectElems.empty() )
879 ebbTree->getElementsInSphere( point.XYZ(), radius, suspectElems );
883 double minDist = std::numeric_limits<double>::max();
884 std::multimap< double, const SMDS_MeshElement* > dist2face;
885 ElementBndBoxTree::TElemSeq::iterator elem = suspectElems.begin();
886 for ( ; elem != suspectElems.end(); ++elem )
888 double dist = SMESH_MeshAlgos::GetDistance( *elem, point );
889 if ( dist < minDist + 1e-10)
892 dist2face.insert( dist2face.begin(), std::make_pair( dist, *elem ));
895 if ( !dist2face.empty() )
897 std::multimap< double, const SMDS_MeshElement* >::iterator d2f = dist2face.begin();
898 closestElem = d2f->second;
899 // if there are several elements at the same distance, select one
900 // with GC closest to the point
901 typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
902 double minDistToGC = 0;
903 for ( ++d2f; d2f != dist2face.end() && fabs( d2f->first - minDist ) < 1e-10; ++d2f )
905 if ( minDistToGC == 0 )
908 gc = accumulate( TXyzIterator(closestElem->nodesIterator()),
909 TXyzIterator(), gc ) / closestElem->NbNodes();
910 minDistToGC = point.SquareDistance( gc );
913 gc = accumulate( TXyzIterator( d2f->second->nodesIterator()),
914 TXyzIterator(), gc ) / d2f->second->NbNodes();
915 double d = point.SquareDistance( gc );
916 if ( d < minDistToGC )
919 closestElem = d2f->second;
922 // cout << "FindClosestTo( " <<point.X()<<", "<<point.Y()<<", "<<point.Z()<<" ) FACE "
923 // <<closestElem->GetID() << " DIST " << minDist << endl;
928 // NOT IMPLEMENTED SO FAR
934 //================================================================================
936 * \brief Classify the given point in the closed 2D mesh
938 //================================================================================
940 TopAbs_State SMESH_ElementSearcherImpl::GetPointState(const gp_Pnt& point)
942 _elementType = SMDSAbs_Face;
944 double tolerance = getTolerance();
946 ElementBndBoxTree*& ebbTree = _ebbTree[ SMDSAbs_Face ];
948 ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
950 // Algo: analyse transition of a line starting at the point through mesh boundary;
951 // try three lines parallel to axis of the coordinate system and perform rough
952 // analysis. If solution is not clear perform thorough analysis.
954 const int nbAxes = 3;
955 gp_Dir axisDir[ nbAxes ] = { gp::DX(), gp::DY(), gp::DZ() };
956 std::map< double, TInters > paramOnLine2TInters[ nbAxes ];
957 std::list< TInters > tangentInters[ nbAxes ]; // of faces whose plane includes the line
958 std::multimap< int, int > nbInt2Axis; // to find the simplest case
959 for ( int axis = 0; axis < nbAxes; ++axis )
961 gp_Ax1 lineAxis( point, axisDir[axis]);
962 gp_Lin line ( lineAxis );
964 ElementBndBoxTree::TElemSeq suspectFaces; // faces possibly intersecting the line
965 ebbTree->getElementsNearLine( lineAxis, suspectFaces );
967 // Intersect faces with the line
969 std::map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
970 ElementBndBoxTree::TElemSeq::iterator face = suspectFaces.begin();
971 for ( ; face != suspectFaces.end(); ++face )
975 if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false)) continue;
976 gp_Pln facePlane( SMESH_TNodeXYZ( (*face)->GetNode(0)), fNorm );
978 // perform intersection
979 IntAna_IntConicQuad intersection( line, IntAna_Quadric( facePlane ));
980 if ( !intersection.IsDone() )
982 if ( intersection.IsInQuadric() )
984 tangentInters[ axis ].push_back( TInters( *face, fNorm, true ));
986 else if ( ! intersection.IsParallel() && intersection.NbPoints() > 0 )
988 double tol = 1e-4 * Sqrt( fNorm.Modulus() );
989 gp_Pnt intersectionPoint = intersection.Point(1);
990 if ( !SMESH_MeshAlgos::IsOut( *face, intersectionPoint, tol ))
991 u2inters.insert( std::make_pair( intersection.ParamOnConic(1), TInters( *face, fNorm )));
994 // Analyse intersections roughly
996 int nbInter = u2inters.size();
1000 double f = u2inters.begin()->first, l = u2inters.rbegin()->first;
1001 if ( nbInter == 1 ) // not closed mesh
1002 return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
1004 if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
1007 if ( (f<0) == (l<0) )
1010 int nbIntBeforePoint = std::distance( u2inters.begin(), u2inters.lower_bound(0));
1011 int nbIntAfterPoint = nbInter - nbIntBeforePoint;
1012 if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
1015 nbInt2Axis.insert( std::make_pair( std::min( nbIntBeforePoint, nbIntAfterPoint ), axis ));
1017 if ( _outerFacesFound ) break; // pass to thorough analysis
1019 } // three attempts - loop on CS axes
1021 // Analyse intersections thoroughly.
1022 // We make two loops maximum, on the first one we only exclude touching intersections,
1023 // on the second, if situation is still unclear, we gather and use information on
1024 // position of faces (internal or outer). If faces position is already gathered,
1025 // we make the second loop right away.
1027 for ( int hasPositionInfo = _outerFacesFound; hasPositionInfo < 2; ++hasPositionInfo )
1029 std::multimap< int, int >::const_iterator nb_axis = nbInt2Axis.begin();
1030 for ( ; nb_axis != nbInt2Axis.end(); ++nb_axis )
1032 int axis = nb_axis->second;
1033 std::map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
1035 gp_Ax1 lineAxis( point, axisDir[axis]);
1036 gp_Lin line ( lineAxis );
1038 // add tangent intersections to u2inters
1040 std::list< TInters >::const_iterator tgtInt = tangentInters[ axis ].begin();
1041 for ( ; tgtInt != tangentInters[ axis ].end(); ++tgtInt )
1042 if ( getIntersParamOnLine( line, tgtInt->_face, tolerance, param ))
1043 u2inters.insert( std::make_pair( param, *tgtInt ));
1044 tangentInters[ axis ].clear();
1046 // Count intersections before and after the point excluding touching ones.
1047 // If hasPositionInfo we count intersections of outer boundary only
1049 int nbIntBeforePoint = 0, nbIntAfterPoint = 0;
1050 double f = std::numeric_limits<double>::max(), l = -std::numeric_limits<double>::max();
1051 std::map< double, TInters >::iterator u_int1 = u2inters.begin(), u_int2 = u_int1;
1052 bool ok = ! u_int1->second._coincides;
1053 while ( ok && u_int1 != u2inters.end() )
1055 double u = u_int1->first;
1056 bool touchingInt = false;
1057 if ( ++u_int2 != u2inters.end() )
1059 // skip intersections at the same point (if the line passes through edge or node)
1061 while ( u_int2 != u2inters.end() && fabs( u_int2->first - u ) < tolerance )
1067 // skip tangent intersections
1069 if ( u_int2 != u2inters.end() )
1071 const SMDS_MeshElement* prevFace = u_int1->second._face;
1072 while ( ok && u_int2->second._coincides )
1074 if ( SMESH_MeshAlgos::GetCommonNodes(prevFace , u_int2->second._face).empty() )
1080 ok = ( u_int2 != u2inters.end() );
1086 // skip intersections at the same point after tangent intersections
1089 double u2 = u_int2->first;
1091 while ( u_int2 != u2inters.end() && fabs( u_int2->first - u2 ) < tolerance )
1097 // decide if we skipped a touching intersection
1098 if ( nbSamePnt + nbTgt > 0 )
1100 double minDot = std::numeric_limits<double>::max(), maxDot = -minDot;
1101 std::map< double, TInters >::iterator u_int = u_int1;
1102 for ( ; u_int != u_int2; ++u_int )
1104 if ( u_int->second._coincides ) continue;
1105 double dot = u_int->second._faceNorm * line.Direction();
1106 if ( dot > maxDot ) maxDot = dot;
1107 if ( dot < minDot ) minDot = dot;
1109 touchingInt = ( minDot*maxDot < 0 );
1114 if ( !hasPositionInfo || isOuterBoundary( u_int1->second._face ))
1125 u_int1 = u_int2; // to next intersection
1127 } // loop on intersections with one line
1131 if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
1134 if ( nbIntBeforePoint == 0 || nbIntAfterPoint == 0)
1137 if ( nbIntBeforePoint + nbIntAfterPoint == 1 ) // not closed mesh
1138 return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
1140 if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
1143 if ( (f<0) == (l<0) )
1146 if ( hasPositionInfo )
1147 return nbIntBeforePoint % 2 ? TopAbs_IN : TopAbs_OUT;
1149 } // loop on intersections of the tree lines - thorough analysis
1151 if ( !hasPositionInfo )
1153 // gather info on faces position - is face in the outer boundary or not
1154 std::map< double, TInters > & u2inters = paramOnLine2TInters[ 0 ];
1155 findOuterBoundary( u2inters.begin()->second._face );
1158 } // two attempts - with and w/o faces position info in the mesh
1160 return TopAbs_UNKNOWN;
1163 //=======================================================================
1165 * \brief Return elements possibly intersecting the line
1167 //=======================================================================
1169 void SMESH_ElementSearcherImpl::
1170 GetElementsNearLine( const gp_Ax1& line,
1171 SMDSAbs_ElementType type,
1172 std::vector< const SMDS_MeshElement* >& foundElems)
1174 _elementType = type;
1175 ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
1177 ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
1179 ElementBndBoxTree::TElemSeq elems;
1180 ebbTree->getElementsNearLine( line, elems );
1182 foundElems.insert( foundElems.end(), elems.begin(), elems.end() );
1185 //=======================================================================
1187 * Return elements whose bounding box intersects a sphere
1189 //=======================================================================
1191 void SMESH_ElementSearcherImpl::
1192 GetElementsInSphere( const gp_XYZ& center,
1193 const double radius,
1194 SMDSAbs_ElementType type,
1195 std::vector< const SMDS_MeshElement* >& foundElems)
1197 _elementType = type;
1198 ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
1200 ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
1202 ElementBndBoxTree::TElemSeq elems;
1203 ebbTree->getElementsInSphere( center, radius, elems );
1205 foundElems.insert( foundElems.end(), elems.begin(), elems.end() );
1208 //=======================================================================
1210 * Return elements whose bounding box intersects a given bounding box
1212 //=======================================================================
1214 void SMESH_ElementSearcherImpl::
1215 GetElementsInBox( const Bnd_B3d& box,
1216 SMDSAbs_ElementType type,
1217 std::vector< const SMDS_MeshElement* >& foundElems)
1219 _elementType = type;
1220 ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
1222 ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt, getTolerance() );
1224 ElementBndBoxTree::TElemSeq elems;
1225 ebbTree->getElementsInBox( box, elems );
1227 foundElems.insert( foundElems.end(), elems.begin(), elems.end() );
1230 //=======================================================================
1232 * \brief Return a projection of a given point to a mesh.
1233 * Optionally return the closest element
1235 //=======================================================================
1237 gp_XYZ SMESH_ElementSearcherImpl::Project(const gp_Pnt& point,
1238 SMDSAbs_ElementType type,
1239 const SMDS_MeshElement** closestElem)
1241 _elementType = type;
1242 if ( _mesh->GetMeshInfo().NbElements( _elementType ) == 0 )
1243 throw SALOME_Exception( LOCALIZED( "No elements of given type in the mesh" ));
1245 ElementBndBoxTree*& ebbTree = _ebbTree[ _elementType ];
1247 ebbTree = new ElementBndBoxTree( *_mesh, _elementType );
1249 gp_XYZ p = point.XYZ();
1250 ElementBndBoxTree* ebbLeaf = ebbTree->getLeafAtPoint( p );
1251 const Bnd_B3d* box = ebbLeaf->getBox();
1252 double radius = ( box->CornerMax() - box->CornerMin() ).Modulus();
1254 ElementBndBoxTree::TElemSeq elems;
1255 ebbTree->getElementsInSphere( p, radius, elems );
1256 while ( elems.empty() )
1259 ebbTree->getElementsInSphere( p, radius, elems );
1261 gp_XYZ proj, bestProj;
1262 const SMDS_MeshElement* elem = 0;
1263 double minDist = 2 * radius;
1264 ElementBndBoxTree::TElemSeq::iterator e = elems.begin();
1265 for ( ; e != elems.end(); ++e )
1267 double d = SMESH_MeshAlgos::GetDistance( *e, p, &proj );
1275 if ( closestElem ) *closestElem = elem;
1280 //=======================================================================
1282 * \brief Return true if the point is IN or ON of the element
1284 //=======================================================================
1286 bool SMESH_MeshAlgos::IsOut( const SMDS_MeshElement* element, const gp_Pnt& point, double tol )
1288 if ( element->GetType() == SMDSAbs_Volume)
1290 return SMDS_VolumeTool( element ).IsOut( point.X(), point.Y(), point.Z(), tol );
1293 // get ordered nodes
1295 std::vector< SMESH_TNodeXYZ > xyz; xyz.reserve( element->NbNodes()+1 );
1297 SMDS_ElemIteratorPtr nodeIt = element->interlacedNodesElemIterator();
1298 for ( int i = 0; nodeIt->more(); ++i )
1299 xyz.push_back( SMESH_TNodeXYZ( nodeIt->next() ));
1301 int i, nbNodes = (int) xyz.size(); // central node of biquadratic is missing
1303 if ( element->GetType() == SMDSAbs_Face ) // --------------------------------------------------
1305 // compute face normal
1306 gp_Vec faceNorm(0,0,0);
1307 xyz.push_back( xyz.front() );
1308 for ( i = 0; i < nbNodes; ++i )
1310 gp_Vec edge1( xyz[i+1], xyz[i]);
1311 gp_Vec edge2( xyz[i+1], xyz[(i+2)%nbNodes] );
1312 faceNorm += edge1 ^ edge2;
1314 double fNormSize = faceNorm.Magnitude();
1315 if ( fNormSize <= tol )
1317 // degenerated face: point is out if it is out of all face edges
1318 for ( i = 0; i < nbNodes; ++i )
1320 SMDS_LinearEdge edge( xyz[i]._node, xyz[i+1]._node );
1321 if ( !IsOut( &edge, point, tol ))
1326 faceNorm /= fNormSize;
1328 // check if the point lays on face plane
1329 gp_Vec n2p( xyz[0], point );
1330 double dot = n2p * faceNorm;
1331 if ( Abs( dot ) > tol ) // not on face plane
1334 if ( nbNodes > 3 ) // maybe the face is not planar
1336 double elemThick = 0;
1337 for ( i = 1; i < nbNodes; ++i )
1339 gp_Vec n2n( xyz[0], xyz[i] );
1340 elemThick = Max( elemThick, Abs( n2n * faceNorm ));
1342 isOut = Abs( dot ) > elemThick + tol;
1348 // check if point is out of face boundary:
1349 // define it by closest transition of a ray point->infinity through face boundary
1350 // on the face plane.
1351 // First, find normal of a plane perpendicular to face plane, to be used as a cutting tool
1352 // to find intersections of the ray with the boundary.
1354 gp_Vec plnNorm = ray ^ faceNorm;
1355 double n2pSize = plnNorm.Magnitude();
1356 if ( n2pSize <= tol ) return false; // point coincides with the first node
1357 if ( n2pSize * n2pSize > fNormSize * 100 ) return true; // point is very far
1359 // for each node of the face, compute its signed distance to the cutting plane
1360 std::vector<double> dist( nbNodes + 1);
1361 for ( i = 0; i < nbNodes; ++i )
1363 gp_Vec n2p( xyz[i], point );
1364 dist[i] = n2p * plnNorm;
1366 dist.back() = dist.front();
1367 // find the closest intersection
1369 double rClosest = 0, distClosest = 1e100;
1371 for ( i = 0; i < nbNodes; ++i )
1374 if ( fabs( dist[i] ) < tol )
1376 else if ( fabs( dist[i+1]) < tol )
1378 else if ( dist[i] * dist[i+1] < 0 )
1379 r = dist[i] / ( dist[i] - dist[i+1] );
1381 continue; // no intersection
1382 gp_Pnt pInt = xyz[i] * (1.-r) + xyz[i+1] * r;
1383 gp_Vec p2int( point, pInt);
1384 double intDist = p2int.SquareMagnitude();
1385 if ( intDist < distClosest )
1390 distClosest = intDist;
1394 return true; // no intesections - out
1396 // analyse transition
1397 gp_Vec edge( xyz[iClosest], xyz[iClosest+1] );
1398 gp_Vec edgeNorm = -( edge ^ faceNorm ); // normal to intersected edge pointing out of face
1399 gp_Vec p2int ( point, pClosest );
1400 bool out = (edgeNorm * p2int) < -tol;
1401 if ( rClosest > 0. && rClosest < 1. ) // not node intersection
1404 // the ray passes through a face node; analyze transition through an adjacent edge
1405 gp_Pnt p1 = xyz[ (rClosest == 0.) ? ((iClosest+nbNodes-1) % nbNodes) : (iClosest+1) ];
1406 gp_Pnt p2 = xyz[ (rClosest == 0.) ? iClosest : ((iClosest+2) % nbNodes) ];
1407 gp_Vec edgeAdjacent( p1, p2 );
1408 gp_Vec edgeNorm2 = -( edgeAdjacent ^ faceNorm );
1409 bool out2 = (edgeNorm2 * p2int) < -tol;
1411 bool covexCorner = ( edgeNorm * edgeAdjacent * (rClosest==1. ? 1. : -1.)) < 0;
1412 return covexCorner ? (out || out2) : (out && out2);
1415 if ( element->GetType() == SMDSAbs_Edge ) // --------------------------------------------------
1417 // point is out of edge if it is NOT ON any straight part of edge
1418 // (we consider quadratic edge as being composed of two straight parts)
1419 for ( i = 1; i < nbNodes; ++i )
1421 gp_Vec edge( xyz[i-1], xyz[i] );
1422 gp_Vec n1p ( xyz[i-1], point );
1423 double u = ( edge * n1p ) / edge.SquareMagnitude(); // param [0,1] on the edge
1425 if ( n1p.SquareMagnitude() < tol * tol )
1430 if ( point.SquareDistance( xyz[i] ) < tol * tol )
1434 gp_XYZ proj = ( 1. - u ) * xyz[i-1] + u * xyz[i]; // projection of the point on the edge
1435 double dist2 = point.SquareDistance( proj );
1436 if ( dist2 > tol * tol )
1438 return false; // point is ON this part
1443 // Node or 0D element -------------------------------------------------------------------------
1445 gp_Vec n2p ( xyz[0], point );
1446 return n2p.SquareMagnitude() > tol * tol;
1451 //=======================================================================
1454 // Position of a point relative to a segment
1458 // VERTEX 1 o----ON-----> VERTEX 2
1462 enum PositionName { POS_LEFT = 1, POS_VERTEX = 2, POS_RIGHT = 4, //POS_ON = 8,
1463 POS_ALL = POS_LEFT | POS_RIGHT | POS_VERTEX };
1467 int _index; // index of vertex or segment
1469 PointPos( PositionName n, int i=-1 ): _name(n), _index(i) {}
1470 bool operator < (const PointPos& other ) const
1472 if ( _name == other._name )
1473 return ( _index < 0 || other._index < 0 ) ? false : _index < other._index;
1474 return _name < other._name;
1478 //================================================================================
1480 * \brief Return of a point relative to a segment
1481 * \param point2D - the point to analyze position of
1482 * \param xyVec - end points of segments
1483 * \param index0 - 0-based index of the first point of segment
1484 * \param posToFindOut - flags of positions to detect
1485 * \retval PointPos - point position
1487 //================================================================================
1489 PointPos getPointPosition( const gp_XY& point2D,
1490 const gp_XY* segEnds,
1491 const int index0 = 0,
1492 const int posToFindOut = POS_ALL)
1494 const gp_XY& p1 = segEnds[ index0 ];
1495 const gp_XY& p2 = segEnds[ index0+1 ];
1496 const gp_XY grad = p2 - p1;
1498 if ( posToFindOut & POS_VERTEX )
1500 // check if the point2D is at "vertex 1" zone
1501 gp_XY pp1[2] = { p1, gp_XY( p1.X() - grad.Y(),
1502 p1.Y() + grad.X() ) };
1503 if ( getPointPosition( point2D, pp1, 0, POS_LEFT|POS_RIGHT )._name == POS_LEFT )
1504 return PointPos( POS_VERTEX, index0 );
1506 // check if the point2D is at "vertex 2" zone
1507 gp_XY pp2[2] = { p2, gp_XY( p2.X() - grad.Y(),
1508 p2.Y() + grad.X() ) };
1509 if ( getPointPosition( point2D, pp2, 0, POS_LEFT|POS_RIGHT )._name == POS_RIGHT )
1510 return PointPos( POS_VERTEX, index0 + 1);
1512 double edgeEquation =
1513 ( point2D.X() - p1.X() ) * grad.Y() - ( point2D.Y() - p1.Y() ) * grad.X();
1514 return PointPos( edgeEquation < 0 ? POS_LEFT : POS_RIGHT, index0 );
1518 //=======================================================================
1520 * \brief Return minimal distance from a point to an element
1522 * Currently we ignore non-planarity and 2nd order of face
1524 //=======================================================================
1526 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshElement* elem,
1527 const gp_Pnt& point,
1528 gp_XYZ* closestPnt )
1530 switch ( elem->GetType() )
1532 case SMDSAbs_Volume:
1533 return GetDistance( dynamic_cast<const SMDS_MeshVolume*>( elem ), point, closestPnt );
1535 return GetDistance( dynamic_cast<const SMDS_MeshFace*>( elem ), point, closestPnt );
1537 return GetDistance( dynamic_cast<const SMDS_MeshEdge*>( elem ), point, closestPnt );
1539 if ( closestPnt ) *closestPnt = SMESH_TNodeXYZ( elem );
1540 return point.Distance( SMESH_TNodeXYZ( elem ));
1546 //=======================================================================
1548 * \brief Return minimal distance from a point to a face
1550 * Currently we ignore non-planarity and 2nd order of face
1552 //=======================================================================
1554 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshFace* face,
1555 const gp_Pnt& point,
1556 gp_XYZ* closestPnt )
1558 const double badDistance = -1;
1559 if ( !face ) return badDistance;
1561 // coordinates of nodes (medium nodes, if any, ignored)
1562 typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
1563 std::vector<gp_XYZ> xyz( TXyzIterator( face->nodesIterator()), TXyzIterator() );
1564 xyz.resize( face->NbCornerNodes()+1 );
1566 // transformation to get xyz[0] lies on the origin, xyz[1] lies on the Z axis,
1567 // and xyz[2] lies in the XZ plane. This is to pass to 2D space on XZ plane.
1569 gp_Vec OZ ( xyz[0], xyz[1] );
1570 gp_Vec OX ( xyz[0], xyz[2] );
1571 if ( OZ.Magnitude() < std::numeric_limits<double>::min() )
1573 if ( xyz.size() < 4 ) return badDistance;
1574 OZ = gp_Vec ( xyz[0], xyz[2] );
1575 OX = gp_Vec ( xyz[0], xyz[3] );
1579 tgtCS = gp_Ax3( xyz[0], OZ, OX );
1581 catch ( Standard_Failure ) {
1584 trsf.SetTransformation( tgtCS );
1586 // move all the nodes to 2D
1587 std::vector<gp_XY> xy( xyz.size() );
1588 for ( size_t i = 0;i < xyz.size()-1; ++i )
1590 gp_XYZ p3d = xyz[i];
1591 trsf.Transforms( p3d );
1592 xy[i].SetCoord( p3d.X(), p3d.Z() );
1594 xyz.back() = xyz.front();
1595 xy.back() = xy.front();
1597 // // move the point in 2D
1598 gp_XYZ tmpPnt = point.XYZ();
1599 trsf.Transforms( tmpPnt );
1600 gp_XY point2D( tmpPnt.X(), tmpPnt.Z() );
1602 // loop on edges of the face to analyze point position ralative to the face
1603 std::set< PointPos > pntPosSet;
1604 for ( size_t i = 1; i < xy.size(); ++i )
1606 PointPos pos = getPointPosition( point2D, &xy[0], i-1 );
1607 pntPosSet.insert( pos );
1611 PointPos pos = *pntPosSet.begin();
1612 switch ( pos._name )
1616 // point is most close to an edge
1617 gp_Vec edge( xyz[ pos._index ], xyz[ pos._index+1 ]);
1618 gp_Vec n1p ( xyz[ pos._index ], point );
1619 double u = ( edge * n1p ) / edge.SquareMagnitude(); // param [0,1] on the edge
1620 // projection of the point on the edge
1621 gp_XYZ proj = xyz[ pos._index ] + u * edge.XYZ();
1622 if ( closestPnt ) *closestPnt = proj;
1623 return point.Distance( proj );
1627 // point is inside the face
1628 double distToFacePlane = Abs( tmpPnt.Y() );
1631 if ( distToFacePlane < std::numeric_limits<double>::min() ) {
1632 *closestPnt = point.XYZ();
1636 trsf.Inverted().Transforms( tmpPnt );
1637 *closestPnt = tmpPnt;
1640 return distToFacePlane;
1644 // point is most close to a node
1645 gp_Vec distVec( point, xyz[ pos._index ]);
1646 return distVec.Magnitude();
1653 //=======================================================================
1655 * \brief Return minimal distance from a point to an edge
1657 //=======================================================================
1659 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshEdge* seg,
1660 const gp_Pnt& point,
1661 gp_XYZ* closestPnt )
1663 double dist = Precision::Infinite();
1664 if ( !seg ) return dist;
1666 int i = 0, nbNodes = seg->NbNodes();
1668 std::vector< SMESH_TNodeXYZ > xyz( nbNodes );
1669 SMDS_ElemIteratorPtr nodeIt = seg->interlacedNodesElemIterator();
1670 while ( nodeIt->more() )
1671 xyz[ i++ ].Set( nodeIt->next() );
1673 for ( i = 1; i < nbNodes; ++i )
1675 gp_Vec edge( xyz[i-1], xyz[i] );
1676 gp_Vec n1p ( xyz[i-1], point );
1677 double d, u = ( edge * n1p ) / edge.SquareMagnitude(); // param [0,1] on the edge
1679 if (( d = n1p.SquareMagnitude() ) < dist ) {
1681 if ( closestPnt ) *closestPnt = xyz[i-1];
1684 else if ( u >= 1. ) {
1685 if (( d = point.SquareDistance( xyz[i] )) < dist ) {
1687 if ( closestPnt ) *closestPnt = xyz[i];
1691 gp_XYZ proj = xyz[i-1] + u * edge.XYZ(); // projection of the point on the edge
1692 if (( d = point.SquareDistance( proj )) < dist ) {
1694 if ( closestPnt ) *closestPnt = proj;
1698 return Sqrt( dist );
1701 //=======================================================================
1703 * \brief Return minimal distance from a point to a volume
1705 * Currently we ignore non-planarity and 2nd order
1707 //=======================================================================
1709 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshVolume* volume,
1710 const gp_Pnt& point,
1711 gp_XYZ* closestPnt )
1713 SMDS_VolumeTool vTool( volume );
1714 vTool.SetExternalNormal();
1715 const int iQ = volume->IsQuadratic() ? 2 : 1;
1718 double minDist = 1e100, dist;
1719 gp_XYZ closeP = point.XYZ();
1721 for ( int iF = 0; iF < vTool.NbFaces(); ++iF )
1723 // skip a facet with normal not "looking at" the point
1724 if ( !vTool.GetFaceNormal( iF, n[0], n[1], n[2] ) ||
1725 !vTool.GetFaceBaryCenter( iF, bc[0], bc[1], bc[2] ))
1727 gp_XYZ bcp = point.XYZ() - gp_XYZ( bc[0], bc[1], bc[2] );
1728 if ( gp_XYZ( n[0], n[1], n[2] ) * bcp < 1e-6 )
1731 // find distance to a facet
1732 const SMDS_MeshNode** nodes = vTool.GetFaceNodes( iF );
1733 switch ( vTool.NbFaceNodes( iF ) / iQ ) {
1736 SMDS_FaceOfNodes tmpFace( nodes[0], nodes[ 1*iQ ], nodes[ 2*iQ ] );
1737 dist = GetDistance( &tmpFace, point, closestPnt );
1742 SMDS_FaceOfNodes tmpFace( nodes[0], nodes[ 1*iQ ], nodes[ 2*iQ ], nodes[ 3*iQ ]);
1743 dist = GetDistance( &tmpFace, point, closestPnt );
1747 std::vector<const SMDS_MeshNode *> nvec( nodes, nodes + vTool.NbFaceNodes( iF ));
1748 SMDS_PolygonalFaceOfNodes tmpFace( nvec );
1749 dist = GetDistance( &tmpFace, point, closestPnt );
1751 if ( dist < minDist )
1755 if ( closestPnt ) closeP = *closestPnt;
1760 if ( closestPnt ) *closestPnt = closeP;
1764 return 0; // point is inside the volume
1767 //================================================================================
1769 * \brief Returns barycentric coordinates of a point within a triangle.
1770 * A not returned bc2 = 1. - bc0 - bc1.
1771 * The point lies within the triangle if ( bc0 >= 0 && bc1 >= 0 && bc0+bc1 <= 1 )
1773 //================================================================================
1775 void SMESH_MeshAlgos::GetBarycentricCoords( const gp_XY& p,
1782 const double // matrix 2x2
1783 T11 = t0.X()-t2.X(), T12 = t1.X()-t2.X(),
1784 T21 = t0.Y()-t2.Y(), T22 = t1.Y()-t2.Y();
1785 const double Tdet = T11*T22 - T12*T21; // matrix determinant
1786 if ( Abs( Tdet ) < std::numeric_limits<double>::min() )
1792 const double t11 = T22, t12 = -T12, t21 = -T21, t22 = T11;
1794 const double r11 = p.X()-t2.X(), r12 = p.Y()-t2.Y();
1795 // barycentric coordinates: mutiply matrix by vector
1796 bc0 = (t11 * r11 + t12 * r12)/Tdet;
1797 bc1 = (t21 * r11 + t22 * r12)/Tdet;
1800 //=======================================================================
1801 //function : FindFaceInSet
1802 //purpose : Return a face having linked nodes n1 and n2 and which is
1803 // - not in avoidSet,
1804 // - in elemSet provided that !elemSet.empty()
1805 // i1 and i2 optionally returns indices of n1 and n2
1806 //=======================================================================
1808 const SMDS_MeshElement*
1809 SMESH_MeshAlgos::FindFaceInSet(const SMDS_MeshNode* n1,
1810 const SMDS_MeshNode* n2,
1811 const TIDSortedElemSet& elemSet,
1812 const TIDSortedElemSet& avoidSet,
1818 const SMDS_MeshElement* face = 0;
1820 SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator(SMDSAbs_Face);
1821 while ( invElemIt->more() && !face ) // loop on inverse faces of n1
1823 const SMDS_MeshElement* elem = invElemIt->next();
1824 if (avoidSet.count( elem ))
1826 if ( !elemSet.empty() && !elemSet.count( elem ))
1829 i1 = elem->GetNodeIndex( n1 );
1830 // find a n2 linked to n1
1831 int nbN = elem->IsQuadratic() ? elem->NbNodes()/2 : elem->NbNodes();
1832 for ( int di = -1; di < 2 && !face; di += 2 )
1834 i2 = (i1+di+nbN) % nbN;
1835 if ( elem->GetNode( i2 ) == n2 )
1838 if ( !face && elem->IsQuadratic())
1840 // analysis for quadratic elements using all nodes
1841 SMDS_ElemIteratorPtr anIter = elem->interlacedNodesElemIterator();
1842 const SMDS_MeshNode* prevN = static_cast<const SMDS_MeshNode*>( anIter->next() );
1843 for ( i1 = -1, i2 = 0; anIter->more() && !face; i1++, i2++ )
1845 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( anIter->next() );
1846 if ( n1 == prevN && n2 == n )
1850 else if ( n2 == prevN && n1 == n )
1852 face = elem; std::swap( i1, i2 );
1858 if ( n1ind ) *n1ind = i1;
1859 if ( n2ind ) *n2ind = i2;
1863 //================================================================================
1865 * \brief Calculate normal of a mesh face
1867 //================================================================================
1869 bool SMESH_MeshAlgos::FaceNormal(const SMDS_MeshElement* F, gp_XYZ& normal, bool normalized)
1871 if ( !F || F->GetType() != SMDSAbs_Face )
1874 normal.SetCoord(0,0,0);
1875 int nbNodes = F->NbCornerNodes();
1876 for ( int i = 0; i < nbNodes-2; ++i )
1879 for ( int n = 0; n < 3; ++n )
1881 const SMDS_MeshNode* node = F->GetNode( i + n );
1882 p[n].SetCoord( node->X(), node->Y(), node->Z() );
1884 normal += ( p[2] - p[1] ) ^ ( p[0] - p[1] );
1886 double size2 = normal.SquareModulus();
1887 bool ok = ( size2 > std::numeric_limits<double>::min() * std::numeric_limits<double>::min());
1888 if ( normalized && ok )
1889 normal /= sqrt( size2 );
1894 //=======================================================================
1895 //function : GetCommonNodes
1896 //purpose : Return nodes common to two elements
1897 //=======================================================================
1899 std::vector< const SMDS_MeshNode*> SMESH_MeshAlgos::GetCommonNodes(const SMDS_MeshElement* e1,
1900 const SMDS_MeshElement* e2)
1902 std::vector< const SMDS_MeshNode*> common;
1903 for ( int i = 0 ; i < e1->NbNodes(); ++i )
1904 if ( e2->GetNodeIndex( e1->GetNode( i )) >= 0 )
1905 common.push_back( e1->GetNode( i ));
1908 //================================================================================
1910 * \brief Return true if node1 encounters first in the face and node2, after
1912 //================================================================================
1914 bool SMESH_MeshAlgos::IsRightOrder( const SMDS_MeshElement* face,
1915 const SMDS_MeshNode* node0,
1916 const SMDS_MeshNode* node1 )
1918 int i0 = face->GetNodeIndex( node0 );
1919 int i1 = face->GetNodeIndex( node1 );
1920 if ( face->IsQuadratic() )
1922 if ( face->IsMediumNode( node0 ))
1924 i0 -= ( face->NbNodes()/2 - 1 );
1929 i1 -= ( face->NbNodes()/2 - 1 );
1934 return ( diff == 1 ) || ( diff == -face->NbNodes()+1 );
1937 //=======================================================================
1939 * \brief Return SMESH_NodeSearcher
1941 //=======================================================================
1943 SMESH_NodeSearcher* SMESH_MeshAlgos::GetNodeSearcher(SMDS_Mesh& mesh)
1945 return new SMESH_NodeSearcherImpl( &mesh );
1948 //=======================================================================
1950 * \brief Return SMESH_NodeSearcher
1952 //=======================================================================
1954 SMESH_NodeSearcher* SMESH_MeshAlgos::GetNodeSearcher(SMDS_ElemIteratorPtr elemIt)
1956 return new SMESH_NodeSearcherImpl( 0, elemIt );
1959 //=======================================================================
1961 * \brief Return SMESH_ElementSearcher
1963 //=======================================================================
1965 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh& mesh,
1968 return new SMESH_ElementSearcherImpl( mesh, tolerance );
1971 //=======================================================================
1973 * \brief Return SMESH_ElementSearcher acting on a sub-set of elements
1975 //=======================================================================
1977 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh& mesh,
1978 SMDS_ElemIteratorPtr elemIt,
1981 return new SMESH_ElementSearcherImpl( mesh, tolerance, elemIt );