1 // Copyright (C) 2007-2013 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.
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_LinearEdge.hxx"
32 #include "SMDS_VolumeTool.hxx"
33 #include "SMDS_Mesh.hxx"
34 #include "SMESH_OctreeNode.hxx"
36 #include <GC_MakeSegment.hxx>
37 #include <GeomAPI_ExtremaCurveCurve.hxx>
38 #include <Geom_Line.hxx>
39 #include <IntAna_IntConicQuad.hxx>
40 #include <IntAna_Quadric.hxx>
49 //=======================================================================
51 * \brief Implementation of search for the node closest to point
53 //=======================================================================
55 struct SMESH_NodeSearcherImpl: public SMESH_NodeSearcher
57 //---------------------------------------------------------------------
61 SMESH_NodeSearcherImpl( const SMDS_Mesh* theMesh )
63 myMesh = ( SMDS_Mesh* ) theMesh;
65 TIDSortedNodeSet nodes;
67 SMDS_NodeIteratorPtr nIt = theMesh->nodesIterator(/*idInceasingOrder=*/true);
69 nodes.insert( nodes.end(), nIt->next() );
71 myOctreeNode = new SMESH_OctreeNode(nodes) ;
73 // get max size of a leaf box
74 SMESH_OctreeNode* tree = myOctreeNode;
75 while ( !tree->isLeaf() )
77 SMESH_OctreeNodeIteratorPtr cIt = tree->GetChildrenIterator();
81 myHalfLeafSize = tree->maxSize() / 2.;
84 //---------------------------------------------------------------------
86 * \brief Move node and update myOctreeNode accordingly
88 void MoveNode( const SMDS_MeshNode* node, const gp_Pnt& toPnt )
90 myOctreeNode->UpdateByMoveNode( node, toPnt );
91 myMesh->MoveNode( node, toPnt.X(), toPnt.Y(), toPnt.Z() );
94 //---------------------------------------------------------------------
98 const SMDS_MeshNode* FindClosestTo( const gp_Pnt& thePnt )
100 map<double, const SMDS_MeshNode*> dist2Nodes;
101 myOctreeNode->NodesAround( thePnt.Coord(), dist2Nodes, myHalfLeafSize );
102 if ( !dist2Nodes.empty() )
103 return dist2Nodes.begin()->second;
104 list<const SMDS_MeshNode*> nodes;
105 //myOctreeNode->NodesAround( &tgtNode, &nodes, myHalfLeafSize );
107 double minSqDist = DBL_MAX;
108 if ( nodes.empty() ) // get all nodes of OctreeNode's closest to thePnt
110 // sort leafs by their distance from thePnt
111 typedef map< double, SMESH_OctreeNode* > TDistTreeMap;
112 TDistTreeMap treeMap;
113 list< SMESH_OctreeNode* > treeList;
114 list< SMESH_OctreeNode* >::iterator trIt;
115 treeList.push_back( myOctreeNode );
117 gp_XYZ pointNode( thePnt.X(), thePnt.Y(), thePnt.Z() );
118 bool pointInside = myOctreeNode->isInside( pointNode, myHalfLeafSize );
119 for ( trIt = treeList.begin(); trIt != treeList.end(); ++trIt)
121 SMESH_OctreeNode* tree = *trIt;
122 if ( !tree->isLeaf() ) // put children to the queue
124 if ( pointInside && !tree->isInside( pointNode, myHalfLeafSize )) continue;
125 SMESH_OctreeNodeIteratorPtr cIt = tree->GetChildrenIterator();
126 while ( cIt->more() )
127 treeList.push_back( cIt->next() );
129 else if ( tree->NbNodes() ) // put a tree to the treeMap
131 const Bnd_B3d& box = *tree->getBox();
132 double sqDist = thePnt.SquareDistance( 0.5 * ( box.CornerMin() + box.CornerMax() ));
133 pair<TDistTreeMap::iterator,bool> it_in = treeMap.insert( make_pair( sqDist, tree ));
134 if ( !it_in.second ) // not unique distance to box center
135 treeMap.insert( it_in.first, make_pair( sqDist + 1e-13*treeMap.size(), tree ));
138 // find distance after which there is no sense to check tree's
139 double sqLimit = DBL_MAX;
140 TDistTreeMap::iterator sqDist_tree = treeMap.begin();
141 if ( treeMap.size() > 5 ) {
142 SMESH_OctreeNode* closestTree = sqDist_tree->second;
143 const Bnd_B3d& box = *closestTree->getBox();
144 double limit = sqrt( sqDist_tree->first ) + sqrt ( box.SquareExtent() );
145 sqLimit = limit * limit;
147 // get all nodes from trees
148 for ( ; sqDist_tree != treeMap.end(); ++sqDist_tree) {
149 if ( sqDist_tree->first > sqLimit )
151 SMESH_OctreeNode* tree = sqDist_tree->second;
152 tree->NodesAround( tree->GetNodeIterator()->next(), &nodes );
155 // find closest among nodes
157 const SMDS_MeshNode* closestNode = 0;
158 list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
159 for ( ; nIt != nodes.end(); ++nIt ) {
160 double sqDist = thePnt.SquareDistance( SMESH_TNodeXYZ( *nIt ) );
161 if ( minSqDist > sqDist ) {
169 //---------------------------------------------------------------------
173 ~SMESH_NodeSearcherImpl() { delete myOctreeNode; }
175 //---------------------------------------------------------------------
177 * \brief Return the node tree
179 const SMESH_OctreeNode* getTree() const { return myOctreeNode; }
182 SMESH_OctreeNode* myOctreeNode;
184 double myHalfLeafSize; // max size of a leaf box
187 // ========================================================================
188 namespace // Utils used in SMESH_ElementSearcherImpl::FindElementsByPoint()
190 const int MaxNbElemsInLeaf = 10; // maximal number of elements in a leaf of tree
191 const int MaxLevel = 7; // maximal tree height -> nb terminal boxes: 8^7 = 2097152
192 const double NodeRadius = 1e-9; // to enlarge bnd box of element
194 //=======================================================================
196 * \brief Octal tree of bounding boxes of elements
198 //=======================================================================
200 class ElementBndBoxTree : public SMESH_Octree
204 ElementBndBoxTree(const SMDS_Mesh& mesh,
205 SMDSAbs_ElementType elemType,
206 SMDS_ElemIteratorPtr theElemIt = SMDS_ElemIteratorPtr(),
207 double tolerance = NodeRadius );
208 void getElementsNearPoint( const gp_Pnt& point, TIDSortedElemSet& foundElems );
209 void getElementsNearLine ( const gp_Ax1& line, TIDSortedElemSet& foundElems);
210 void getElementsInSphere ( const gp_XYZ& center,
211 const double radius, TIDSortedElemSet& foundElems);
212 size_t getSize() { return std::max( _size, _elements.size() ); }
213 ~ElementBndBoxTree();
216 ElementBndBoxTree():_size(0) {}
217 SMESH_Octree* newChild() const { return new ElementBndBoxTree; }
218 void buildChildrenData();
219 Bnd_B3d* buildRootBox();
221 //!< Bounding box of element
222 struct ElementBox : public Bnd_B3d
224 const SMDS_MeshElement* _element;
225 int _refCount; // an ElementBox can be included in several tree branches
226 ElementBox(const SMDS_MeshElement* elem, double tolerance);
228 vector< ElementBox* > _elements;
232 //================================================================================
234 * \brief ElementBndBoxTree creation
236 //================================================================================
238 ElementBndBoxTree::ElementBndBoxTree(const SMDS_Mesh& mesh, SMDSAbs_ElementType elemType, SMDS_ElemIteratorPtr theElemIt, double tolerance)
239 :SMESH_Octree( new SMESH_TreeLimit( MaxLevel, /*minSize=*/0. ))
241 int nbElems = mesh.GetMeshInfo().NbElements( elemType );
242 _elements.reserve( nbElems );
244 SMDS_ElemIteratorPtr elemIt = theElemIt ? theElemIt : mesh.elementsIterator( elemType );
245 while ( elemIt->more() )
246 _elements.push_back( new ElementBox( elemIt->next(),tolerance ));
251 //================================================================================
255 //================================================================================
257 ElementBndBoxTree::~ElementBndBoxTree()
259 for ( int i = 0; i < _elements.size(); ++i )
260 if ( --_elements[i]->_refCount <= 0 )
264 //================================================================================
266 * \brief Return the maximal box
268 //================================================================================
270 Bnd_B3d* ElementBndBoxTree::buildRootBox()
272 Bnd_B3d* box = new Bnd_B3d;
273 for ( int i = 0; i < _elements.size(); ++i )
274 box->Add( *_elements[i] );
278 //================================================================================
280 * \brief Redistrubute element boxes among children
282 //================================================================================
284 void ElementBndBoxTree::buildChildrenData()
286 for ( int i = 0; i < _elements.size(); ++i )
288 for (int j = 0; j < 8; j++)
290 if ( !_elements[i]->IsOut( *myChildren[j]->getBox() ))
292 _elements[i]->_refCount++;
293 ((ElementBndBoxTree*)myChildren[j])->_elements.push_back( _elements[i]);
296 _elements[i]->_refCount--;
298 _size = _elements.size();
299 SMESHUtils::FreeVector( _elements ); // = _elements.clear() + free memory
301 for (int j = 0; j < 8; j++)
303 ElementBndBoxTree* child = static_cast<ElementBndBoxTree*>( myChildren[j]);
304 if ( child->_elements.size() <= MaxNbElemsInLeaf )
305 child->myIsLeaf = true;
307 if ( child->_elements.capacity() - child->_elements.size() > 1000 )
308 SMESHUtils::CompactVector( child->_elements );
312 //================================================================================
314 * \brief Return elements which can include the point
316 //================================================================================
318 void ElementBndBoxTree::getElementsNearPoint( const gp_Pnt& point,
319 TIDSortedElemSet& foundElems)
321 if ( getBox()->IsOut( point.XYZ() ))
326 for ( int i = 0; i < _elements.size(); ++i )
327 if ( !_elements[i]->IsOut( point.XYZ() ))
328 foundElems.insert( _elements[i]->_element );
332 for (int i = 0; i < 8; i++)
333 ((ElementBndBoxTree*) myChildren[i])->getElementsNearPoint( point, foundElems );
337 //================================================================================
339 * \brief Return elements which can be intersected by the line
341 //================================================================================
343 void ElementBndBoxTree::getElementsNearLine( const gp_Ax1& line,
344 TIDSortedElemSet& foundElems)
346 if ( getBox()->IsOut( line ))
351 for ( int i = 0; i < _elements.size(); ++i )
352 if ( !_elements[i]->IsOut( line ))
353 foundElems.insert( _elements[i]->_element );
357 for (int i = 0; i < 8; i++)
358 ((ElementBndBoxTree*) myChildren[i])->getElementsNearLine( line, foundElems );
362 //================================================================================
364 * \brief Return elements from leaves intersecting the sphere
366 //================================================================================
368 void ElementBndBoxTree::getElementsInSphere ( const gp_XYZ& center,
370 TIDSortedElemSet& foundElems)
372 if ( getBox()->IsOut( center, radius ))
377 for ( int i = 0; i < _elements.size(); ++i )
378 if ( !_elements[i]->IsOut( center, radius ))
379 foundElems.insert( _elements[i]->_element );
383 for (int i = 0; i < 8; i++)
384 ((ElementBndBoxTree*) myChildren[i])->getElementsInSphere( center, radius, foundElems );
388 //================================================================================
390 * \brief Construct the element box
392 //================================================================================
394 ElementBndBoxTree::ElementBox::ElementBox(const SMDS_MeshElement* elem, double tolerance)
398 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
399 while ( nIt->more() )
400 Add( SMESH_TNodeXYZ( nIt->next() ));
401 Enlarge( tolerance );
406 //=======================================================================
408 * \brief Implementation of search for the elements by point and
409 * of classification of point in 2D mesh
411 //=======================================================================
413 struct SMESH_ElementSearcherImpl: public SMESH_ElementSearcher
416 SMDS_ElemIteratorPtr _meshPartIt;
417 ElementBndBoxTree* _ebbTree;
418 SMESH_NodeSearcherImpl* _nodeSearcher;
419 SMDSAbs_ElementType _elementType;
421 bool _outerFacesFound;
422 set<const SMDS_MeshElement*> _outerFaces; // empty means "no internal faces at all"
424 SMESH_ElementSearcherImpl( SMDS_Mesh& mesh, SMDS_ElemIteratorPtr elemIt=SMDS_ElemIteratorPtr())
425 : _mesh(&mesh),_meshPartIt(elemIt),_ebbTree(0),_nodeSearcher(0),_tolerance(-1),_outerFacesFound(false) {}
426 ~SMESH_ElementSearcherImpl()
428 if ( _ebbTree ) delete _ebbTree; _ebbTree = 0;
429 if ( _nodeSearcher ) delete _nodeSearcher; _nodeSearcher = 0;
431 virtual int FindElementsByPoint(const gp_Pnt& point,
432 SMDSAbs_ElementType type,
433 vector< const SMDS_MeshElement* >& foundElements);
434 virtual TopAbs_State GetPointState(const gp_Pnt& point);
435 virtual const SMDS_MeshElement* FindClosestTo( const gp_Pnt& point,
436 SMDSAbs_ElementType type );
438 void GetElementsNearLine( const gp_Ax1& line,
439 SMDSAbs_ElementType type,
440 vector< const SMDS_MeshElement* >& foundElems);
441 double getTolerance();
442 bool getIntersParamOnLine(const gp_Lin& line, const SMDS_MeshElement* face,
443 const double tolerance, double & param);
444 void findOuterBoundary(const SMDS_MeshElement* anyOuterFace);
445 bool isOuterBoundary(const SMDS_MeshElement* face) const
447 return _outerFaces.empty() || _outerFaces.count(face);
449 struct TInters //!< data of intersection of the line and the mesh face (used in GetPointState())
451 const SMDS_MeshElement* _face;
453 bool _coincides; //!< the line lays in face plane
454 TInters(const SMDS_MeshElement* face, const gp_Vec& faceNorm, bool coinc=false)
455 : _face(face), _faceNorm( faceNorm ), _coincides( coinc ) {}
457 struct TFaceLink //!< link and faces sharing it (used in findOuterBoundary())
460 TIDSortedElemSet _faces;
461 TFaceLink( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshElement* face)
462 : _link( n1, n2 ), _faces( &face, &face + 1) {}
466 ostream& operator<< (ostream& out, const SMESH_ElementSearcherImpl::TInters& i)
468 return out << "TInters(face=" << ( i._face ? i._face->GetID() : 0)
469 << ", _coincides="<<i._coincides << ")";
472 //=======================================================================
474 * \brief define tolerance for search
476 //=======================================================================
478 double SMESH_ElementSearcherImpl::getTolerance()
480 if ( _tolerance < 0 )
482 const SMDS_MeshInfo& meshInfo = _mesh->GetMeshInfo();
485 if ( _nodeSearcher && meshInfo.NbNodes() > 1 )
487 double boxSize = _nodeSearcher->getTree()->maxSize();
488 _tolerance = 1e-8 * boxSize/* / meshInfo.NbNodes()*/;
490 else if ( _ebbTree && meshInfo.NbElements() > 0 )
492 double boxSize = _ebbTree->maxSize();
493 _tolerance = 1e-8 * boxSize/* / meshInfo.NbElements()*/;
495 if ( _tolerance == 0 )
497 // define tolerance by size of a most complex element
498 int complexType = SMDSAbs_Volume;
499 while ( complexType > SMDSAbs_All &&
500 meshInfo.NbElements( SMDSAbs_ElementType( complexType )) < 1 )
502 if ( complexType == SMDSAbs_All ) return 0; // empty mesh
504 if ( complexType == int( SMDSAbs_Node ))
506 SMDS_NodeIteratorPtr nodeIt = _mesh->nodesIterator();
508 if ( meshInfo.NbNodes() > 2 )
509 elemSize = SMESH_TNodeXYZ( nodeIt->next() ).Distance( nodeIt->next() );
513 SMDS_ElemIteratorPtr elemIt =
514 _mesh->elementsIterator( SMDSAbs_ElementType( complexType ));
515 const SMDS_MeshElement* elem = elemIt->next();
516 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
517 SMESH_TNodeXYZ n1( nodeIt->next() );
519 while ( nodeIt->more() )
521 double dist = n1.Distance( static_cast<const SMDS_MeshNode*>( nodeIt->next() ));
522 elemSize = max( dist, elemSize );
525 _tolerance = 1e-4 * elemSize;
531 //================================================================================
533 * \brief Find intersection of the line and an edge of face and return parameter on line
535 //================================================================================
537 bool SMESH_ElementSearcherImpl::getIntersParamOnLine(const gp_Lin& line,
538 const SMDS_MeshElement* face,
545 GeomAPI_ExtremaCurveCurve anExtCC;
546 Handle(Geom_Curve) lineCurve = new Geom_Line( line );
548 int nbNodes = face->IsQuadratic() ? face->NbNodes()/2 : face->NbNodes();
549 for ( int i = 0; i < nbNodes && nbInts < 2; ++i )
551 GC_MakeSegment edge( SMESH_TNodeXYZ( face->GetNode( i )),
552 SMESH_TNodeXYZ( face->GetNode( (i+1)%nbNodes) ));
553 anExtCC.Init( lineCurve, edge);
554 if ( anExtCC.NbExtrema() > 0 && anExtCC.LowerDistance() <= tol)
556 Quantity_Parameter pl, pe;
557 anExtCC.LowerDistanceParameters( pl, pe );
563 if ( nbInts > 0 ) param /= nbInts;
566 //================================================================================
568 * \brief Find all faces belonging to the outer boundary of mesh
570 //================================================================================
572 void SMESH_ElementSearcherImpl::findOuterBoundary(const SMDS_MeshElement* outerFace)
574 if ( _outerFacesFound ) return;
576 // Collect all outer faces by passing from one outer face to another via their links
577 // and BTW find out if there are internal faces at all.
579 // checked links and links where outer boundary meets internal one
580 set< SMESH_TLink > visitedLinks, seamLinks;
582 // links to treat with already visited faces sharing them
583 list < TFaceLink > startLinks;
585 // load startLinks with the first outerFace
586 startLinks.push_back( TFaceLink( outerFace->GetNode(0), outerFace->GetNode(1), outerFace));
587 _outerFaces.insert( outerFace );
589 TIDSortedElemSet emptySet;
590 while ( !startLinks.empty() )
592 const SMESH_TLink& link = startLinks.front()._link;
593 TIDSortedElemSet& faces = startLinks.front()._faces;
595 outerFace = *faces.begin();
596 // find other faces sharing the link
597 const SMDS_MeshElement* f;
598 while (( f = SMESH_MeshAlgos::FindFaceInSet(link.node1(), link.node2(), emptySet, faces )))
601 // select another outer face among the found
602 const SMDS_MeshElement* outerFace2 = 0;
603 if ( faces.size() == 2 )
605 outerFace2 = (outerFace == *faces.begin() ? *faces.rbegin() : *faces.begin());
607 else if ( faces.size() > 2 )
609 seamLinks.insert( link );
611 // link direction within the outerFace
612 gp_Vec n1n2( SMESH_TNodeXYZ( link.node1()),
613 SMESH_TNodeXYZ( link.node2()));
614 int i1 = outerFace->GetNodeIndex( link.node1() );
615 int i2 = outerFace->GetNodeIndex( link.node2() );
616 bool rev = ( abs(i2-i1) == 1 ? i1 > i2 : i2 > i1 );
617 if ( rev ) n1n2.Reverse();
619 gp_XYZ ofNorm, fNorm;
620 if ( SMESH_MeshAlgos::FaceNormal( outerFace, ofNorm, /*normalized=*/false ))
622 // direction from the link inside outerFace
623 gp_Vec dirInOF = gp_Vec( ofNorm ) ^ n1n2;
624 // sort all other faces by angle with the dirInOF
625 map< double, const SMDS_MeshElement* > angle2Face;
626 set< const SMDS_MeshElement*, TIDCompare >::const_iterator face = faces.begin();
627 for ( ; face != faces.end(); ++face )
629 if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false ))
631 gp_Vec dirInF = gp_Vec( fNorm ) ^ n1n2;
632 double angle = dirInOF.AngleWithRef( dirInF, n1n2 );
633 if ( angle < 0 ) angle += 2. * M_PI;
634 angle2Face.insert( make_pair( angle, *face ));
636 if ( !angle2Face.empty() )
637 outerFace2 = angle2Face.begin()->second;
640 // store the found outer face and add its links to continue seaching from
643 _outerFaces.insert( outerFace );
644 int nbNodes = outerFace2->NbNodes()/( outerFace2->IsQuadratic() ? 2 : 1 );
645 for ( int i = 0; i < nbNodes; ++i )
647 SMESH_TLink link2( outerFace2->GetNode(i), outerFace2->GetNode((i+1)%nbNodes));
648 if ( visitedLinks.insert( link2 ).second )
649 startLinks.push_back( TFaceLink( link2.node1(), link2.node2(), outerFace2 ));
652 startLinks.pop_front();
654 _outerFacesFound = true;
656 if ( !seamLinks.empty() )
658 // There are internal boundaries touching the outher one,
659 // find all faces of internal boundaries in order to find
660 // faces of boundaries of holes, if any.
669 //=======================================================================
671 * \brief Find elements of given type where the given point is IN or ON.
672 * Returns nb of found elements and elements them-selves.
674 * 'ALL' type means elements of any type excluding nodes, balls and 0D elements
676 //=======================================================================
678 int SMESH_ElementSearcherImpl::
679 FindElementsByPoint(const gp_Pnt& point,
680 SMDSAbs_ElementType type,
681 vector< const SMDS_MeshElement* >& foundElements)
683 foundElements.clear();
685 double tolerance = getTolerance();
687 // =================================================================================
688 if ( type == SMDSAbs_Node || type == SMDSAbs_0DElement || type == SMDSAbs_Ball)
690 if ( !_nodeSearcher )
691 _nodeSearcher = new SMESH_NodeSearcherImpl( _mesh );
693 const SMDS_MeshNode* closeNode = _nodeSearcher->FindClosestTo( point );
694 if ( !closeNode ) return foundElements.size();
696 if ( point.Distance( SMESH_TNodeXYZ( closeNode )) > tolerance )
697 return foundElements.size(); // to far from any node
699 if ( type == SMDSAbs_Node )
701 foundElements.push_back( closeNode );
705 SMDS_ElemIteratorPtr elemIt = closeNode->GetInverseElementIterator( type );
706 while ( elemIt->more() )
707 foundElements.push_back( elemIt->next() );
710 // =================================================================================
711 else // elements more complex than 0D
713 if ( !_ebbTree || _elementType != type )
715 if ( _ebbTree ) delete _ebbTree;
716 _ebbTree = new ElementBndBoxTree( *_mesh, _elementType = type, _meshPartIt, tolerance );
718 TIDSortedElemSet suspectElems;
719 _ebbTree->getElementsNearPoint( point, suspectElems );
720 TIDSortedElemSet::iterator elem = suspectElems.begin();
721 for ( ; elem != suspectElems.end(); ++elem )
722 if ( !SMESH_MeshAlgos::IsOut( *elem, point, tolerance ))
723 foundElements.push_back( *elem );
725 return foundElements.size();
728 //=======================================================================
730 * \brief Find an element of given type most close to the given point
732 * WARNING: Only face search is implemeneted so far
734 //=======================================================================
736 const SMDS_MeshElement*
737 SMESH_ElementSearcherImpl::FindClosestTo( const gp_Pnt& point,
738 SMDSAbs_ElementType type )
740 const SMDS_MeshElement* closestElem = 0;
742 if ( type == SMDSAbs_Face )
744 if ( !_ebbTree || _elementType != type )
746 if ( _ebbTree ) delete _ebbTree;
747 _ebbTree = new ElementBndBoxTree( *_mesh, _elementType = type, _meshPartIt );
749 TIDSortedElemSet suspectElems;
750 _ebbTree->getElementsNearPoint( point, suspectElems );
752 if ( suspectElems.empty() && _ebbTree->maxSize() > 0 )
754 gp_Pnt boxCenter = 0.5 * ( _ebbTree->getBox()->CornerMin() +
755 _ebbTree->getBox()->CornerMax() );
757 if ( _ebbTree->getBox()->IsOut( point.XYZ() ))
758 radius = point.Distance( boxCenter ) - 0.5 * _ebbTree->maxSize();
760 radius = _ebbTree->maxSize() / pow( 2., _ebbTree->getHeight()) / 2;
761 while ( suspectElems.empty() )
763 _ebbTree->getElementsInSphere( point.XYZ(), radius, suspectElems );
767 double minDist = std::numeric_limits<double>::max();
768 multimap< double, const SMDS_MeshElement* > dist2face;
769 TIDSortedElemSet::iterator elem = suspectElems.begin();
770 for ( ; elem != suspectElems.end(); ++elem )
772 double dist = SMESH_MeshAlgos::GetDistance( dynamic_cast<const SMDS_MeshFace*>(*elem),
774 if ( dist < minDist + 1e-10)
777 dist2face.insert( dist2face.begin(), make_pair( dist, *elem ));
780 if ( !dist2face.empty() )
782 multimap< double, const SMDS_MeshElement* >::iterator d2f = dist2face.begin();
783 closestElem = d2f->second;
784 // if there are several elements at the same distance, select one
785 // with GC closest to the point
786 typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
787 double minDistToGC = 0;
788 for ( ++d2f; d2f != dist2face.end() && fabs( d2f->first - minDist ) < 1e-10; ++d2f )
790 if ( minDistToGC == 0 )
793 gc = accumulate( TXyzIterator(closestElem->nodesIterator()),
794 TXyzIterator(), gc ) / closestElem->NbNodes();
795 minDistToGC = point.SquareDistance( gc );
798 gc = accumulate( TXyzIterator( d2f->second->nodesIterator()),
799 TXyzIterator(), gc ) / d2f->second->NbNodes();
800 double d = point.SquareDistance( gc );
801 if ( d < minDistToGC )
804 closestElem = d2f->second;
807 // cout << "FindClosestTo( " <<point.X()<<", "<<point.Y()<<", "<<point.Z()<<" ) FACE "
808 // <<closestElem->GetID() << " DIST " << minDist << endl;
813 // NOT IMPLEMENTED SO FAR
819 //================================================================================
821 * \brief Classify the given point in the closed 2D mesh
823 //================================================================================
825 TopAbs_State SMESH_ElementSearcherImpl::GetPointState(const gp_Pnt& point)
827 double tolerance = getTolerance();
828 if ( !_ebbTree || _elementType != SMDSAbs_Face )
830 if ( _ebbTree ) delete _ebbTree;
831 _ebbTree = new ElementBndBoxTree( *_mesh, _elementType = SMDSAbs_Face, _meshPartIt );
833 // Algo: analyse transition of a line starting at the point through mesh boundary;
834 // try three lines parallel to axis of the coordinate system and perform rough
835 // analysis. If solution is not clear perform thorough analysis.
837 const int nbAxes = 3;
838 gp_Dir axisDir[ nbAxes ] = { gp::DX(), gp::DY(), gp::DZ() };
839 map< double, TInters > paramOnLine2TInters[ nbAxes ];
840 list< TInters > tangentInters[ nbAxes ]; // of faces whose plane includes the line
841 multimap< int, int > nbInt2Axis; // to find the simplest case
842 for ( int axis = 0; axis < nbAxes; ++axis )
844 gp_Ax1 lineAxis( point, axisDir[axis]);
845 gp_Lin line ( lineAxis );
847 TIDSortedElemSet suspectFaces; // faces possibly intersecting the line
848 _ebbTree->getElementsNearLine( lineAxis, suspectFaces );
850 // Intersect faces with the line
852 map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
853 TIDSortedElemSet::iterator face = suspectFaces.begin();
854 for ( ; face != suspectFaces.end(); ++face )
858 if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false)) continue;
859 gp_Pln facePlane( SMESH_TNodeXYZ( (*face)->GetNode(0)), fNorm );
861 // perform intersection
862 IntAna_IntConicQuad intersection( line, IntAna_Quadric( facePlane ));
863 if ( !intersection.IsDone() )
865 if ( intersection.IsInQuadric() )
867 tangentInters[ axis ].push_back( TInters( *face, fNorm, true ));
869 else if ( ! intersection.IsParallel() && intersection.NbPoints() > 0 )
871 gp_Pnt intersectionPoint = intersection.Point(1);
872 if ( !SMESH_MeshAlgos::IsOut( *face, intersectionPoint, tolerance ))
873 u2inters.insert(make_pair( intersection.ParamOnConic(1), TInters( *face, fNorm )));
876 // Analyse intersections roughly
878 int nbInter = u2inters.size();
882 double f = u2inters.begin()->first, l = u2inters.rbegin()->first;
883 if ( nbInter == 1 ) // not closed mesh
884 return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
886 if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
889 if ( (f<0) == (l<0) )
892 int nbIntBeforePoint = std::distance( u2inters.begin(), u2inters.lower_bound(0));
893 int nbIntAfterPoint = nbInter - nbIntBeforePoint;
894 if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
897 nbInt2Axis.insert( make_pair( min( nbIntBeforePoint, nbIntAfterPoint ), axis ));
899 if ( _outerFacesFound ) break; // pass to thorough analysis
901 } // three attempts - loop on CS axes
903 // Analyse intersections thoroughly.
904 // We make two loops maximum, on the first one we only exclude touching intersections,
905 // on the second, if situation is still unclear, we gather and use information on
906 // position of faces (internal or outer). If faces position is already gathered,
907 // we make the second loop right away.
909 for ( int hasPositionInfo = _outerFacesFound; hasPositionInfo < 2; ++hasPositionInfo )
911 multimap< int, int >::const_iterator nb_axis = nbInt2Axis.begin();
912 for ( ; nb_axis != nbInt2Axis.end(); ++nb_axis )
914 int axis = nb_axis->second;
915 map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
917 gp_Ax1 lineAxis( point, axisDir[axis]);
918 gp_Lin line ( lineAxis );
920 // add tangent intersections to u2inters
922 list< TInters >::const_iterator tgtInt = tangentInters[ axis ].begin();
923 for ( ; tgtInt != tangentInters[ axis ].end(); ++tgtInt )
924 if ( getIntersParamOnLine( line, tgtInt->_face, tolerance, param ))
925 u2inters.insert(make_pair( param, *tgtInt ));
926 tangentInters[ axis ].clear();
928 // Count intersections before and after the point excluding touching ones.
929 // If hasPositionInfo we count intersections of outer boundary only
931 int nbIntBeforePoint = 0, nbIntAfterPoint = 0;
932 double f = numeric_limits<double>::max(), l = -numeric_limits<double>::max();
933 map< double, TInters >::iterator u_int1 = u2inters.begin(), u_int2 = u_int1;
934 bool ok = ! u_int1->second._coincides;
935 while ( ok && u_int1 != u2inters.end() )
937 double u = u_int1->first;
938 bool touchingInt = false;
939 if ( ++u_int2 != u2inters.end() )
941 // skip intersections at the same point (if the line passes through edge or node)
943 while ( u_int2 != u2inters.end() && fabs( u_int2->first - u ) < tolerance )
949 // skip tangent intersections
951 const SMDS_MeshElement* prevFace = u_int1->second._face;
952 while ( ok && u_int2->second._coincides )
954 if ( SMESH_MeshAlgos::GetCommonNodes(prevFace , u_int2->second._face).empty() )
960 ok = ( u_int2 != u2inters.end() );
965 // skip intersections at the same point after tangent intersections
968 double u2 = u_int2->first;
970 while ( u_int2 != u2inters.end() && fabs( u_int2->first - u2 ) < tolerance )
976 // decide if we skipped a touching intersection
977 if ( nbSamePnt + nbTgt > 0 )
979 double minDot = numeric_limits<double>::max(), maxDot = -numeric_limits<double>::max();
980 map< double, TInters >::iterator u_int = u_int1;
981 for ( ; u_int != u_int2; ++u_int )
983 if ( u_int->second._coincides ) continue;
984 double dot = u_int->second._faceNorm * line.Direction();
985 if ( dot > maxDot ) maxDot = dot;
986 if ( dot < minDot ) minDot = dot;
988 touchingInt = ( minDot*maxDot < 0 );
993 if ( !hasPositionInfo || isOuterBoundary( u_int1->second._face ))
1004 u_int1 = u_int2; // to next intersection
1006 } // loop on intersections with one line
1010 if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
1013 if ( nbIntBeforePoint == 0 || nbIntAfterPoint == 0)
1016 if ( nbIntBeforePoint + nbIntAfterPoint == 1 ) // not closed mesh
1017 return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
1019 if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
1022 if ( (f<0) == (l<0) )
1025 if ( hasPositionInfo )
1026 return nbIntBeforePoint % 2 ? TopAbs_IN : TopAbs_OUT;
1028 } // loop on intersections of the tree lines - thorough analysis
1030 if ( !hasPositionInfo )
1032 // gather info on faces position - is face in the outer boundary or not
1033 map< double, TInters > & u2inters = paramOnLine2TInters[ 0 ];
1034 findOuterBoundary( u2inters.begin()->second._face );
1037 } // two attempts - with and w/o faces position info in the mesh
1039 return TopAbs_UNKNOWN;
1042 //=======================================================================
1044 * \brief Return elements possibly intersecting the line
1046 //=======================================================================
1048 void SMESH_ElementSearcherImpl::GetElementsNearLine( const gp_Ax1& line,
1049 SMDSAbs_ElementType type,
1050 vector< const SMDS_MeshElement* >& foundElems)
1052 if ( !_ebbTree || _elementType != type )
1054 if ( _ebbTree ) delete _ebbTree;
1055 _ebbTree = new ElementBndBoxTree( *_mesh, _elementType = type, _meshPartIt );
1057 TIDSortedElemSet suspectFaces; // elements possibly intersecting the line
1058 _ebbTree->getElementsNearLine( line, suspectFaces );
1059 foundElems.assign( suspectFaces.begin(), suspectFaces.end());
1062 //=======================================================================
1064 * \brief Return true if the point is IN or ON of the element
1066 //=======================================================================
1068 bool SMESH_MeshAlgos::IsOut( const SMDS_MeshElement* element, const gp_Pnt& point, double tol )
1070 if ( element->GetType() == SMDSAbs_Volume)
1072 return SMDS_VolumeTool( element ).IsOut( point.X(), point.Y(), point.Z(), tol );
1075 // get ordered nodes
1077 vector< gp_XYZ > xyz;
1078 vector<const SMDS_MeshNode*> nodeList;
1080 SMDS_ElemIteratorPtr nodeIt = element->nodesIterator();
1081 if ( element->IsQuadratic() ) {
1082 nodeIt = element->interlacedNodesElemIterator();
1083 // if (const SMDS_VtkFace* f=dynamic_cast<const SMDS_VtkFace*>(element))
1084 // nodeIt = f->interlacedNodesElemIterator();
1085 // else if (const SMDS_VtkEdge* e =dynamic_cast<const SMDS_VtkEdge*>(element))
1086 // nodeIt = e->interlacedNodesElemIterator();
1088 while ( nodeIt->more() )
1090 SMESH_TNodeXYZ node = nodeIt->next();
1091 xyz.push_back( node );
1092 nodeList.push_back(node._node);
1095 int i, nbNodes = (int) nodeList.size(); // central node of biquadratic is missing
1097 if ( element->GetType() == SMDSAbs_Face ) // --------------------------------------------------
1099 // compute face normal
1100 gp_Vec faceNorm(0,0,0);
1101 xyz.push_back( xyz.front() );
1102 nodeList.push_back( nodeList.front() );
1103 for ( i = 0; i < nbNodes; ++i )
1105 gp_Vec edge1( xyz[i+1], xyz[i]);
1106 gp_Vec edge2( xyz[i+1], xyz[(i+2)%nbNodes] );
1107 faceNorm += edge1 ^ edge2;
1109 double normSize = faceNorm.Magnitude();
1110 if ( normSize <= tol )
1112 // degenerated face: point is out if it is out of all face edges
1113 for ( i = 0; i < nbNodes; ++i )
1115 SMDS_LinearEdge edge( nodeList[i], nodeList[i+1] );
1116 if ( !IsOut( &edge, point, tol ))
1121 faceNorm /= normSize;
1123 // check if the point lays on face plane
1124 gp_Vec n2p( xyz[0], point );
1125 if ( fabs( n2p * faceNorm ) > tol )
1126 return true; // not on face plane
1128 // check if point is out of face boundary:
1129 // define it by closest transition of a ray point->infinity through face boundary
1130 // on the face plane.
1131 // First, find normal of a plane perpendicular to face plane, to be used as a cutting tool
1132 // to find intersections of the ray with the boundary.
1134 gp_Vec plnNorm = ray ^ faceNorm;
1135 normSize = plnNorm.Magnitude();
1136 if ( normSize <= tol ) return false; // point coincides with the first node
1137 plnNorm /= normSize;
1138 // for each node of the face, compute its signed distance to the plane
1139 vector<double> dist( nbNodes + 1);
1140 for ( i = 0; i < nbNodes; ++i )
1142 gp_Vec n2p( xyz[i], point );
1143 dist[i] = n2p * plnNorm;
1145 dist.back() = dist.front();
1146 // find the closest intersection
1148 double rClosest, distClosest = 1e100;;
1150 for ( i = 0; i < nbNodes; ++i )
1153 if ( fabs( dist[i]) < tol )
1155 else if ( fabs( dist[i+1]) < tol )
1157 else if ( dist[i] * dist[i+1] < 0 )
1158 r = dist[i] / ( dist[i] - dist[i+1] );
1160 continue; // no intersection
1161 gp_Pnt pInt = xyz[i] * (1.-r) + xyz[i+1] * r;
1162 gp_Vec p2int ( point, pInt);
1163 if ( p2int * ray > -tol ) // right half-space
1165 double intDist = p2int.SquareMagnitude();
1166 if ( intDist < distClosest )
1171 distClosest = intDist;
1176 return true; // no intesections - out
1178 // analyse transition
1179 gp_Vec edge( xyz[iClosest], xyz[iClosest+1] );
1180 gp_Vec edgeNorm = -( edge ^ faceNorm ); // normal to intersected edge pointing out of face
1181 gp_Vec p2int ( point, pClosest );
1182 bool out = (edgeNorm * p2int) < -tol;
1183 if ( rClosest > 0. && rClosest < 1. ) // not node intersection
1186 // ray pass through a face node; analyze transition through an adjacent edge
1187 gp_Pnt p1 = xyz[ (rClosest == 0.) ? ((iClosest+nbNodes-1) % nbNodes) : (iClosest+1) ];
1188 gp_Pnt p2 = xyz[ (rClosest == 0.) ? iClosest : ((iClosest+2) % nbNodes) ];
1189 gp_Vec edgeAdjacent( p1, p2 );
1190 gp_Vec edgeNorm2 = -( edgeAdjacent ^ faceNorm );
1191 bool out2 = (edgeNorm2 * p2int) < -tol;
1193 bool covexCorner = ( edgeNorm * edgeAdjacent * (rClosest==1. ? 1. : -1.)) < 0;
1194 return covexCorner ? (out || out2) : (out && out2);
1196 if ( element->GetType() == SMDSAbs_Edge ) // --------------------------------------------------
1198 // point is out of edge if it is NOT ON any straight part of edge
1199 // (we consider quadratic edge as being composed of two straight parts)
1200 for ( i = 1; i < nbNodes; ++i )
1202 gp_Vec edge( xyz[i-1], xyz[i]);
1203 gp_Vec n1p ( xyz[i-1], point);
1204 double dist = ( edge ^ n1p ).Magnitude() / edge.Magnitude();
1207 gp_Vec n2p( xyz[i], point );
1208 if ( fabs( edge.Magnitude() - n1p.Magnitude() - n2p.Magnitude()) > tol )
1210 return false; // point is ON this part
1214 // Node or 0D element -------------------------------------------------------------------------
1216 gp_Vec n2p ( xyz[0], point );
1217 return n2p.Magnitude() <= tol;
1222 //=======================================================================
1225 // Position of a point relative to a segment
1229 // VERTEX 1 o----ON-----> VERTEX 2
1233 enum PositionName { POS_LEFT = 1, POS_VERTEX = 2, POS_RIGHT = 4, //POS_ON = 8,
1234 POS_ALL = POS_LEFT | POS_RIGHT | POS_VERTEX };
1238 int _index; // index of vertex or segment
1240 PointPos( PositionName n, int i=-1 ): _name(n), _index(i) {}
1241 bool operator < (const PointPos& other ) const
1243 if ( _name == other._name )
1244 return ( _index < 0 || other._index < 0 ) ? false : _index < other._index;
1245 return _name < other._name;
1249 //================================================================================
1251 * \brief Return of a point relative to a segment
1252 * \param point2D - the point to analyze position of
1253 * \param xyVec - end points of segments
1254 * \param index0 - 0-based index of the first point of segment
1255 * \param posToFindOut - flags of positions to detect
1256 * \retval PointPos - point position
1258 //================================================================================
1260 PointPos getPointPosition( const gp_XY& point2D,
1261 const gp_XY* segEnds,
1262 const int index0 = 0,
1263 const int posToFindOut = POS_ALL)
1265 const gp_XY& p1 = segEnds[ index0 ];
1266 const gp_XY& p2 = segEnds[ index0+1 ];
1267 const gp_XY grad = p2 - p1;
1269 if ( posToFindOut & POS_VERTEX )
1271 // check if the point2D is at "vertex 1" zone
1272 gp_XY pp1[2] = { p1, gp_XY( p1.X() - grad.Y(),
1273 p1.Y() + grad.X() ) };
1274 if ( getPointPosition( point2D, pp1, 0, POS_LEFT|POS_RIGHT )._name == POS_LEFT )
1275 return PointPos( POS_VERTEX, index0 );
1277 // check if the point2D is at "vertex 2" zone
1278 gp_XY pp2[2] = { p2, gp_XY( p2.X() - grad.Y(),
1279 p2.Y() + grad.X() ) };
1280 if ( getPointPosition( point2D, pp2, 0, POS_LEFT|POS_RIGHT )._name == POS_RIGHT )
1281 return PointPos( POS_VERTEX, index0 + 1);
1283 double edgeEquation =
1284 ( point2D.X() - p1.X() ) * grad.Y() - ( point2D.Y() - p1.Y() ) * grad.X();
1285 return PointPos( edgeEquation < 0 ? POS_LEFT : POS_RIGHT, index0 );
1289 //=======================================================================
1291 * \brief Return minimal distance from a point to a face
1293 * Currently we ignore non-planarity and 2nd order of face
1295 //=======================================================================
1297 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshFace* face,
1298 const gp_Pnt& point )
1300 double badDistance = -1;
1301 if ( !face ) return badDistance;
1303 // coordinates of nodes (medium nodes, if any, ignored)
1304 typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
1305 vector<gp_XYZ> xyz( TXyzIterator( face->nodesIterator()), TXyzIterator() );
1306 xyz.resize( face->NbCornerNodes()+1 );
1308 // transformation to get xyz[0] lies on the origin, xyz[1] lies on the Z axis,
1309 // and xyz[2] lies in the XZ plane. This is to pass to 2D space on XZ plane.
1311 gp_Vec OZ ( xyz[0], xyz[1] );
1312 gp_Vec OX ( xyz[0], xyz[2] );
1313 if ( OZ.Magnitude() < std::numeric_limits<double>::min() )
1315 if ( xyz.size() < 4 ) return badDistance;
1316 OZ = gp_Vec ( xyz[0], xyz[2] );
1317 OX = gp_Vec ( xyz[0], xyz[3] );
1321 tgtCS = gp_Ax3( xyz[0], OZ, OX );
1323 catch ( Standard_Failure ) {
1326 trsf.SetTransformation( tgtCS );
1328 // move all the nodes to 2D
1329 vector<gp_XY> xy( xyz.size() );
1330 for ( size_t i = 0;i < xyz.size()-1; ++i )
1332 gp_XYZ p3d = xyz[i];
1333 trsf.Transforms( p3d );
1334 xy[i].SetCoord( p3d.X(), p3d.Z() );
1336 xyz.back() = xyz.front();
1337 xy.back() = xy.front();
1339 // // move the point in 2D
1340 gp_XYZ tmpPnt = point.XYZ();
1341 trsf.Transforms( tmpPnt );
1342 gp_XY point2D( tmpPnt.X(), tmpPnt.Z() );
1344 // loop on segments of the face to analyze point position ralative to the face
1345 set< PointPos > pntPosSet;
1346 for ( size_t i = 1; i < xy.size(); ++i )
1348 PointPos pos = getPointPosition( point2D, &xy[0], i-1 );
1349 pntPosSet.insert( pos );
1353 PointPos pos = *pntPosSet.begin();
1354 // cout << "Face " << face->GetID() << " DIST: ";
1355 switch ( pos._name )
1358 // point is most close to a segment
1359 gp_Vec p0p1( point, xyz[ pos._index ] );
1360 gp_Vec p1p2( xyz[ pos._index ], xyz[ pos._index+1 ]); // segment vector
1362 double projDist = p0p1 * p1p2; // distance projected to the segment
1363 gp_Vec projVec = p1p2 * projDist;
1364 gp_Vec distVec = p0p1 - projVec;
1365 // cout << distVec.Magnitude() << ", SEG " << face->GetNode(pos._index)->GetID()
1366 // << " - " << face->GetNodeWrap(pos._index+1)->GetID() << endl;
1367 return distVec.Magnitude();
1370 // point is inside the face
1371 double distToFacePlane = tmpPnt.Y();
1372 // cout << distToFacePlane << ", INSIDE " << endl;
1373 return Abs( distToFacePlane );
1376 // point is most close to a node
1377 gp_Vec distVec( point, xyz[ pos._index ]);
1378 // cout << distVec.Magnitude() << " VERTEX " << face->GetNode(pos._index)->GetID() << endl;
1379 return distVec.Magnitude();
1385 //=======================================================================
1386 //function : FindFaceInSet
1387 //purpose : Return a face having linked nodes n1 and n2 and which is
1388 // - not in avoidSet,
1389 // - in elemSet provided that !elemSet.empty()
1390 // i1 and i2 optionally returns indices of n1 and n2
1391 //=======================================================================
1393 const SMDS_MeshElement*
1394 SMESH_MeshAlgos::FindFaceInSet(const SMDS_MeshNode* n1,
1395 const SMDS_MeshNode* n2,
1396 const TIDSortedElemSet& elemSet,
1397 const TIDSortedElemSet& avoidSet,
1403 const SMDS_MeshElement* face = 0;
1405 SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator(SMDSAbs_Face);
1406 //MESSAGE("n1->GetInverseElementIterator(SMDSAbs_Face) " << invElemIt);
1407 while ( invElemIt->more() && !face ) // loop on inverse faces of n1
1409 //MESSAGE("in while ( invElemIt->more() && !face )");
1410 const SMDS_MeshElement* elem = invElemIt->next();
1411 if (avoidSet.count( elem ))
1413 if ( !elemSet.empty() && !elemSet.count( elem ))
1416 i1 = elem->GetNodeIndex( n1 );
1417 // find a n2 linked to n1
1418 int nbN = elem->IsQuadratic() ? elem->NbNodes()/2 : elem->NbNodes();
1419 for ( int di = -1; di < 2 && !face; di += 2 )
1421 i2 = (i1+di+nbN) % nbN;
1422 if ( elem->GetNode( i2 ) == n2 )
1425 if ( !face && elem->IsQuadratic())
1427 // analysis for quadratic elements using all nodes
1428 // const SMDS_VtkFace* F = dynamic_cast<const SMDS_VtkFace*>(elem);
1429 // if (!F) throw SALOME_Exception(LOCALIZED("not an SMDS_VtkFace"));
1430 // use special nodes iterator
1431 SMDS_ElemIteratorPtr anIter = elem->interlacedNodesElemIterator();
1432 const SMDS_MeshNode* prevN = static_cast<const SMDS_MeshNode*>( anIter->next() );
1433 for ( i1 = -1, i2 = 0; anIter->more() && !face; i1++, i2++ )
1435 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( anIter->next() );
1436 if ( n1 == prevN && n2 == n )
1440 else if ( n2 == prevN && n1 == n )
1442 face = elem; swap( i1, i2 );
1448 if ( n1ind ) *n1ind = i1;
1449 if ( n2ind ) *n2ind = i2;
1453 //================================================================================
1455 * \brief Calculate normal of a mesh face
1457 //================================================================================
1459 bool SMESH_MeshAlgos::FaceNormal(const SMDS_MeshElement* F, gp_XYZ& normal, bool normalized)
1461 if ( !F || F->GetType() != SMDSAbs_Face )
1464 normal.SetCoord(0,0,0);
1465 int nbNodes = F->IsQuadratic() ? F->NbNodes()/2 : F->NbNodes();
1466 for ( int i = 0; i < nbNodes-2; ++i )
1469 for ( int n = 0; n < 3; ++n )
1471 const SMDS_MeshNode* node = F->GetNode( i + n );
1472 p[n].SetCoord( node->X(), node->Y(), node->Z() );
1474 normal += ( p[2] - p[1] ) ^ ( p[0] - p[1] );
1476 double size2 = normal.SquareModulus();
1477 bool ok = ( size2 > numeric_limits<double>::min() * numeric_limits<double>::min());
1478 if ( normalized && ok )
1479 normal /= sqrt( size2 );
1484 //=======================================================================
1485 //function : GetCommonNodes
1486 //purpose : Return nodes common to two elements
1487 //=======================================================================
1489 vector< const SMDS_MeshNode*> SMESH_MeshAlgos::GetCommonNodes(const SMDS_MeshElement* e1,
1490 const SMDS_MeshElement* e2)
1492 vector< const SMDS_MeshNode*> common;
1493 for ( int i = 0 ; i < e1->NbNodes(); ++i )
1494 if ( e2->GetNodeIndex( e1->GetNode( i )) >= 0 )
1495 common.push_back( e1->GetNode( i ));
1499 //=======================================================================
1501 * \brief Return SMESH_NodeSearcher
1503 //=======================================================================
1505 SMESH_NodeSearcher* SMESH_MeshAlgos::GetNodeSearcher(SMDS_Mesh& mesh)
1507 return new SMESH_NodeSearcherImpl( &mesh );
1510 //=======================================================================
1512 * \brief Return SMESH_ElementSearcher
1514 //=======================================================================
1516 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh& mesh)
1518 return new SMESH_ElementSearcherImpl( mesh );
1521 //=======================================================================
1523 * \brief Return SMESH_ElementSearcher acting on a sub-set of elements
1525 //=======================================================================
1527 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh& mesh,
1528 SMDS_ElemIteratorPtr elemIt)
1530 return new SMESH_ElementSearcherImpl( mesh, elemIt );