Salome HOME
Merge branch 'V8_3_BR' into V8_4_BR
[modules/smesh.git] / src / SMESHUtils / SMESH_MeshAlgos.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
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.
10 //
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.
15 //
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
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 // File      : SMESH_MeshAlgos.hxx
23 // Created   : Tue Apr 30 18:00:36 2013
24 // Author    : Edward AGAPOV (eap)
25
26 // This file holds some low level algorithms extracted from SMESH_MeshEditor
27 // to make them accessible from Controls package
28
29 #include "SMESH_MeshAlgos.hxx"
30
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"
37
38 #include <GC_MakeSegment.hxx>
39 #include <GeomAPI_ExtremaCurveCurve.hxx>
40 #include <Geom_Line.hxx>
41 #include <IntAna_IntConicQuad.hxx>
42 #include <IntAna_Quadric.hxx>
43 #include <gp_Lin.hxx>
44 #include <gp_Pln.hxx>
45
46 #include <limits>
47 #include <numeric>
48
49 using namespace std;
50
51 //=======================================================================
52 /*!
53  * \brief Implementation of search for the node closest to point
54  */
55 //=======================================================================
56
57 struct SMESH_NodeSearcherImpl: public SMESH_NodeSearcher
58 {
59   //---------------------------------------------------------------------
60   /*!
61    * \brief Constructor
62    */
63   SMESH_NodeSearcherImpl( const SMDS_Mesh*     theMesh   = 0,
64                           SMDS_ElemIteratorPtr theElemIt = SMDS_ElemIteratorPtr() )
65   {
66     myMesh = ( SMDS_Mesh* ) theMesh;
67
68     TIDSortedNodeSet nodes;
69     if ( theMesh ) {
70       SMDS_NodeIteratorPtr nIt = theMesh->nodesIterator(/*idInceasingOrder=*/true);
71       while ( nIt->more() )
72         nodes.insert( nodes.end(), nIt->next() );
73     }
74     else if ( theElemIt )
75     {
76       while ( theElemIt->more() )
77       {
78         const SMDS_MeshElement* e = theElemIt->next();
79         nodes.insert( e->begin_nodes(), e->end_nodes() );
80       }
81     }
82     myOctreeNode = new SMESH_OctreeNode(nodes) ;
83
84     // get max size of a leaf box
85     SMESH_OctreeNode* tree = myOctreeNode;
86     while ( !tree->isLeaf() )
87     {
88       SMESH_OctreeNodeIteratorPtr cIt = tree->GetChildrenIterator();
89       if ( cIt->more() )
90         tree = cIt->next();
91     }
92     myHalfLeafSize = tree->maxSize() / 2.;
93   }
94
95   //---------------------------------------------------------------------
96   /*!
97    * \brief Move node and update myOctreeNode accordingly
98    */
99   void MoveNode( const SMDS_MeshNode* node, const gp_Pnt& toPnt )
100   {
101     myOctreeNode->UpdateByMoveNode( node, toPnt );
102     myMesh->MoveNode( node, toPnt.X(), toPnt.Y(), toPnt.Z() );
103   }
104
105   //---------------------------------------------------------------------
106   /*!
107    * \brief Do it's job
108    */
109   const SMDS_MeshNode* FindClosestTo( const gp_Pnt& thePnt )
110   {
111     map<double, const SMDS_MeshNode*> dist2Nodes;
112     myOctreeNode->NodesAround( thePnt.Coord(), dist2Nodes, myHalfLeafSize );
113     if ( !dist2Nodes.empty() )
114       return dist2Nodes.begin()->second;
115     list<const SMDS_MeshNode*> nodes;
116     //myOctreeNode->NodesAround( &tgtNode, &nodes, myHalfLeafSize );
117
118     double minSqDist = DBL_MAX;
119     if ( nodes.empty() )  // get all nodes of OctreeNode's closest to thePnt
120     {
121       // sort leafs by their distance from thePnt
122       typedef map< double, SMESH_OctreeNode* > TDistTreeMap;
123       TDistTreeMap treeMap;
124       list< SMESH_OctreeNode* > treeList;
125       list< SMESH_OctreeNode* >::iterator trIt;
126       treeList.push_back( myOctreeNode );
127
128       gp_XYZ pointNode( thePnt.X(), thePnt.Y(), thePnt.Z() );
129       bool pointInside = myOctreeNode->isInside( pointNode, myHalfLeafSize );
130       for ( trIt = treeList.begin(); trIt != treeList.end(); ++trIt)
131       {
132         SMESH_OctreeNode* tree = *trIt;
133         if ( !tree->isLeaf() ) // put children to the queue
134         {
135           if ( pointInside && !tree->isInside( pointNode, myHalfLeafSize )) continue;
136           SMESH_OctreeNodeIteratorPtr cIt = tree->GetChildrenIterator();
137           while ( cIt->more() )
138             treeList.push_back( cIt->next() );
139         }
140         else if ( tree->NbNodes() ) // put a tree to the treeMap
141         {
142           const Bnd_B3d& box = *tree->getBox();
143           double sqDist = thePnt.SquareDistance( 0.5 * ( box.CornerMin() + box.CornerMax() ));
144           pair<TDistTreeMap::iterator,bool> it_in = treeMap.insert( make_pair( sqDist, tree ));
145           if ( !it_in.second ) // not unique distance to box center
146             treeMap.insert( it_in.first, make_pair( sqDist + 1e-13*treeMap.size(), tree ));
147         }
148       }
149       // find distance after which there is no sense to check tree's
150       double sqLimit = DBL_MAX;
151       TDistTreeMap::iterator sqDist_tree = treeMap.begin();
152       if ( treeMap.size() > 5 ) {
153         SMESH_OctreeNode* closestTree = sqDist_tree->second;
154         const Bnd_B3d& box = *closestTree->getBox();
155         double limit = sqrt( sqDist_tree->first ) + sqrt ( box.SquareExtent() );
156         sqLimit = limit * limit;
157       }
158       // get all nodes from trees
159       for ( ; sqDist_tree != treeMap.end(); ++sqDist_tree) {
160         if ( sqDist_tree->first > sqLimit )
161           break;
162         SMESH_OctreeNode* tree = sqDist_tree->second;
163         tree->NodesAround( tree->GetNodeIterator()->next(), &nodes );
164       }
165     }
166     // find closest among nodes
167     minSqDist = DBL_MAX;
168     const SMDS_MeshNode* closestNode = 0;
169     list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
170     for ( ; nIt != nodes.end(); ++nIt ) {
171       double sqDist = thePnt.SquareDistance( SMESH_TNodeXYZ( *nIt ) );
172       if ( minSqDist > sqDist ) {
173         closestNode = *nIt;
174         minSqDist = sqDist;
175       }
176     }
177     return closestNode;
178   }
179
180   //---------------------------------------------------------------------
181   /*!
182    * \brief Finds nodes located within a tolerance near a point 
183    */
184   int FindNearPoint(const gp_Pnt&                        point,
185                     const double                         tolerance,
186                     std::vector< const SMDS_MeshNode* >& foundNodes)
187   {
188     myOctreeNode->NodesAround( point.Coord(), foundNodes, tolerance );
189     return foundNodes.size();
190   }
191
192   //---------------------------------------------------------------------
193   /*!
194    * \brief Destructor
195    */
196   ~SMESH_NodeSearcherImpl() { delete myOctreeNode; }
197
198   //---------------------------------------------------------------------
199   /*!
200    * \brief Return the node tree
201    */
202   const SMESH_OctreeNode* getTree() const { return myOctreeNode; }
203
204 private:
205   SMESH_OctreeNode* myOctreeNode;
206   SMDS_Mesh*        myMesh;
207   double            myHalfLeafSize; // max size of a leaf box
208 };
209
210 // ========================================================================
211 namespace // Utils used in SMESH_ElementSearcherImpl::FindElementsByPoint()
212 {
213   const int MaxNbElemsInLeaf = 10; // maximal number of elements in a leaf of tree
214   const int MaxLevel         = 7;  // maximal tree height -> nb terminal boxes: 8^7 = 2097152
215   const double NodeRadius = 1e-9;  // to enlarge bnd box of element
216
217   //=======================================================================
218   /*!
219    * \brief Octal tree of bounding boxes of elements
220    */
221   //=======================================================================
222
223   class ElementBndBoxTree : public SMESH_Octree
224   {
225   public:
226
227     ElementBndBoxTree(const SMDS_Mesh&     mesh,
228                       SMDSAbs_ElementType  elemType,
229                       SMDS_ElemIteratorPtr theElemIt = SMDS_ElemIteratorPtr(),
230                       double               tolerance = NodeRadius );
231     void prepare(); // !!!call it before calling the following methods!!!
232     void getElementsNearPoint( const gp_Pnt& point, vector<const SMDS_MeshElement*>& foundElems );
233     void getElementsNearLine ( const gp_Ax1& line,  vector<const SMDS_MeshElement*>& foundElems);
234     void getElementsInSphere ( const gp_XYZ&                    center,
235                                const double                     radius,
236                                vector<const SMDS_MeshElement*>& foundElems);
237
238   protected:
239     ElementBndBoxTree() {}
240     SMESH_Octree* newChild() const { return new ElementBndBoxTree; }
241     void          buildChildrenData();
242     Bnd_B3d*      buildRootBox();
243   private:
244     //!< Bounding box of element
245     struct ElementBox : public Bnd_B3d
246     {
247       const SMDS_MeshElement* _element;
248       bool                    _isMarked;
249       void init(const SMDS_MeshElement* elem, double tolerance);
250     };
251     vector< ElementBox* > _elements;
252
253     typedef ObjectPool< ElementBox > TElementBoxPool;
254
255     //!< allocator of ElementBox's and SMESH_TreeLimit
256     struct LimitAndPool : public SMESH_TreeLimit
257     {
258       TElementBoxPool            _elBoPool;
259       std::vector< ElementBox* > _markedElems;
260       LimitAndPool():SMESH_TreeLimit( MaxLevel, /*minSize=*/0. ) {}
261     };
262     LimitAndPool* getLimitAndPool() const
263     {
264       SMESH_TreeLimit* limitAndPool = const_cast< SMESH_TreeLimit* >( myLimit );
265       return static_cast< LimitAndPool* >( limitAndPool );
266     }
267   };
268
269   //================================================================================
270   /*!
271    * \brief ElementBndBoxTree creation
272    */
273   //================================================================================
274
275   ElementBndBoxTree::ElementBndBoxTree(const SMDS_Mesh&     mesh,
276                                        SMDSAbs_ElementType  elemType,
277                                        SMDS_ElemIteratorPtr theElemIt,
278                                        double               tolerance)
279     :SMESH_Octree( new LimitAndPool() )
280   {
281     int nbElems = mesh.GetMeshInfo().NbElements( elemType );
282     _elements.reserve( nbElems );
283
284     TElementBoxPool& elBoPool = getLimitAndPool()->_elBoPool;
285
286     SMDS_ElemIteratorPtr elemIt = theElemIt ? theElemIt : mesh.elementsIterator( elemType );
287     while ( elemIt->more() )
288     {
289       ElementBox* eb = elBoPool.getNew();
290       eb->init( elemIt->next(), tolerance );
291       _elements.push_back( eb );
292     }
293     compute();
294   }
295
296   //================================================================================
297   /*!
298    * \brief Return the maximal box
299    */
300   //================================================================================
301
302   Bnd_B3d* ElementBndBoxTree::buildRootBox()
303   {
304     Bnd_B3d* box = new Bnd_B3d;
305     for ( size_t i = 0; i < _elements.size(); ++i )
306       box->Add( *_elements[i] );
307     return box;
308   }
309
310   //================================================================================
311   /*!
312    * \brief Redistrubute element boxes among children
313    */
314   //================================================================================
315
316   void ElementBndBoxTree::buildChildrenData()
317   {
318     for ( size_t i = 0; i < _elements.size(); ++i )
319     {
320       for (int j = 0; j < 8; j++)
321       {
322         if ( !_elements[i]->IsOut( *myChildren[j]->getBox() ))
323           ((ElementBndBoxTree*)myChildren[j])->_elements.push_back( _elements[i]);
324       }
325     }
326     //_size = _elements.size();
327     SMESHUtils::FreeVector( _elements ); // = _elements.clear() + free memory
328
329     for (int j = 0; j < 8; j++)
330     {
331       ElementBndBoxTree* child = static_cast<ElementBndBoxTree*>( myChildren[j]);
332       if ((int) child->_elements.size() <= MaxNbElemsInLeaf )
333         child->myIsLeaf = true;
334
335       if ( child->isLeaf() && child->_elements.capacity() > child->_elements.size() )
336         SMESHUtils::CompactVector( child->_elements );
337     }
338   }
339
340   //================================================================================
341   /*!
342    * \brief Un-mark all elements
343    */
344   //================================================================================
345
346   void ElementBndBoxTree::prepare()
347   {
348     // TElementBoxPool& elBoPool = getElementBoxPool();
349     // for ( size_t i = 0; i < elBoPool.nbElements(); ++i )
350     //   const_cast< ElementBox* >( elBoPool[ i ])->_isMarked = false;
351   }
352
353   //================================================================================
354   /*!
355    * \brief Return elements which can include the point
356    */
357   //================================================================================
358
359   void ElementBndBoxTree::getElementsNearPoint( const gp_Pnt&                    point,
360                                                 vector<const SMDS_MeshElement*>& foundElems)
361   {
362     if ( getBox()->IsOut( point.XYZ() ))
363       return;
364
365     if ( isLeaf() )
366     {
367       LimitAndPool* pool = getLimitAndPool();
368
369       for ( size_t i = 0; i < _elements.size(); ++i )
370         if ( !_elements[i]->IsOut( point.XYZ() ) &&
371              !_elements[i]->_isMarked )
372         {
373           foundElems.push_back( _elements[i]->_element );
374           _elements[i]->_isMarked = true;
375           pool->_markedElems.push_back( _elements[i] );
376         }
377     }
378     else
379     {
380       for (int i = 0; i < 8; i++)
381         ((ElementBndBoxTree*) myChildren[i])->getElementsNearPoint( point, foundElems );
382
383       if ( level() == 0 )
384       {
385         LimitAndPool* pool = getLimitAndPool();
386         for ( size_t i = 0; i < pool->_markedElems.size(); ++i )
387           pool->_markedElems[i]->_isMarked = false;
388         pool->_markedElems.clear();
389       }
390     }
391   }
392
393   //================================================================================
394   /*!
395    * \brief Return elements which can be intersected by the line
396    */
397   //================================================================================
398
399   void ElementBndBoxTree::getElementsNearLine( const gp_Ax1&                    line,
400                                                vector<const SMDS_MeshElement*>& foundElems)
401   {
402     if ( getBox()->IsOut( line ))
403       return;
404
405     if ( isLeaf() )
406     {
407       LimitAndPool* pool = getLimitAndPool();
408
409       for ( size_t i = 0; i < _elements.size(); ++i )
410         if ( !_elements[i]->IsOut( line ) &&
411              !_elements[i]->_isMarked )
412         {
413           foundElems.push_back( _elements[i]->_element );
414           _elements[i]->_isMarked = true;
415           pool->_markedElems.push_back( _elements[i] );
416         }
417     }
418     else
419     {
420       for (int i = 0; i < 8; i++)
421         ((ElementBndBoxTree*) myChildren[i])->getElementsNearLine( line, foundElems );
422
423       if ( level() == 0 )
424       {
425         LimitAndPool* pool = getLimitAndPool();
426         for ( size_t i = 0; i < pool->_markedElems.size(); ++i )
427           pool->_markedElems[i]->_isMarked = false;
428         pool->_markedElems.clear();
429       }
430     }
431   }
432
433   //================================================================================
434   /*!
435    * \brief Return elements from leaves intersecting the sphere
436    */
437   //================================================================================
438
439   void ElementBndBoxTree::getElementsInSphere ( const gp_XYZ&                    center,
440                                                 const double                     radius,
441                                                 vector<const SMDS_MeshElement*>& foundElems)
442   {
443     if ( getBox()->IsOut( center, radius ))
444       return;
445
446     if ( isLeaf() )
447     {
448       LimitAndPool* pool = getLimitAndPool();
449
450       for ( size_t i = 0; i < _elements.size(); ++i )
451         if ( !_elements[i]->IsOut( center, radius ) &&
452              !_elements[i]->_isMarked )
453         {
454           foundElems.push_back( _elements[i]->_element );
455           _elements[i]->_isMarked = true;
456           pool->_markedElems.push_back( _elements[i] );
457         }
458     }
459     else
460     {
461       for (int i = 0; i < 8; i++)
462         ((ElementBndBoxTree*) myChildren[i])->getElementsInSphere( center, radius, foundElems );
463
464       if ( level() == 0 )
465       {
466         LimitAndPool* pool = getLimitAndPool();
467         for ( size_t i = 0; i < pool->_markedElems.size(); ++i )
468           pool->_markedElems[i]->_isMarked = false;
469         pool->_markedElems.clear();
470       }
471     }
472   }
473
474   //================================================================================
475   /*!
476    * \brief Construct the element box
477    */
478   //================================================================================
479
480   void ElementBndBoxTree::ElementBox::init(const SMDS_MeshElement* elem, double tolerance)
481   {
482     _element  = elem;
483     _isMarked = false;
484     SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
485     while ( nIt->more() )
486       Add( SMESH_NodeXYZ( nIt->next() ));
487     Enlarge( tolerance );
488   }
489
490 } // namespace
491
492 //=======================================================================
493 /*!
494  * \brief Implementation of search for the elements by point and
495  *        of classification of point in 2D mesh
496  */
497 //=======================================================================
498
499 SMESH_ElementSearcher::~SMESH_ElementSearcher()
500 {
501 }
502
503 struct SMESH_ElementSearcherImpl: public SMESH_ElementSearcher
504 {
505   SMDS_Mesh*                   _mesh;
506   SMDS_ElemIteratorPtr         _meshPartIt;
507   ElementBndBoxTree*           _ebbTree      [SMDSAbs_NbElementTypes];
508   int                          _ebbTreeHeight[SMDSAbs_NbElementTypes];
509   SMESH_NodeSearcherImpl*      _nodeSearcher;
510   SMDSAbs_ElementType          _elementType;
511   double                       _tolerance;
512   bool                         _outerFacesFound;
513   set<const SMDS_MeshElement*> _outerFaces; // empty means "no internal faces at all"
514
515   SMESH_ElementSearcherImpl( SMDS_Mesh&           mesh,
516                              double               tol=-1,
517                              SMDS_ElemIteratorPtr elemIt=SMDS_ElemIteratorPtr())
518     : _mesh(&mesh),_meshPartIt(elemIt),_nodeSearcher(0),_tolerance(tol),_outerFacesFound(false)
519   {
520     for ( int i = 0; i < SMDSAbs_NbElementTypes; ++i )
521     {
522       _ebbTree[i] = NULL;
523       _ebbTreeHeight[i] = -1;
524     }
525     _elementType = SMDSAbs_All;
526   }
527   virtual ~SMESH_ElementSearcherImpl()
528   {
529     for ( int i = 0; i < SMDSAbs_NbElementTypes; ++i )
530     {
531       delete _ebbTree[i]; _ebbTree[i] = NULL;
532     }
533     if ( _nodeSearcher ) delete _nodeSearcher; _nodeSearcher = 0;
534   }
535   virtual int FindElementsByPoint(const gp_Pnt&                      point,
536                                   SMDSAbs_ElementType                type,
537                                   vector< const SMDS_MeshElement* >& foundElements);
538   virtual TopAbs_State GetPointState(const gp_Pnt& point);
539   virtual const SMDS_MeshElement* FindClosestTo( const gp_Pnt&       point,
540                                                  SMDSAbs_ElementType type );
541
542   void GetElementsNearLine( const gp_Ax1&                      line,
543                             SMDSAbs_ElementType                type,
544                             vector< const SMDS_MeshElement* >& foundElems);
545   void GetElementsInSphere( const gp_XYZ&                      center,
546                             const double                       radius,
547                             SMDSAbs_ElementType                type,
548                             vector< const SMDS_MeshElement* >& foundElems);
549   double getTolerance();
550   bool getIntersParamOnLine(const gp_Lin& line, const SMDS_MeshElement* face,
551                             const double tolerance, double & param);
552   void findOuterBoundary(const SMDS_MeshElement* anyOuterFace);
553   bool isOuterBoundary(const SMDS_MeshElement* face) const
554   {
555     return _outerFaces.empty() || _outerFaces.count(face);
556   }
557   int getTreeHeight()
558   {
559     if ( _ebbTreeHeight[ _elementType ] < 0 )
560       _ebbTreeHeight[ _elementType ] = _ebbTree[ _elementType ]->getHeight();
561     return _ebbTreeHeight[ _elementType ];
562   }
563
564   struct TInters //!< data of intersection of the line and the mesh face (used in GetPointState())
565   {
566     const SMDS_MeshElement* _face;
567     gp_Vec                  _faceNorm;
568     bool                    _coincides; //!< the line lays in face plane
569     TInters(const SMDS_MeshElement* face, const gp_Vec& faceNorm, bool coinc=false)
570       : _face(face), _faceNorm( faceNorm ), _coincides( coinc ) {}
571   };
572   struct TFaceLink //!< link and faces sharing it (used in findOuterBoundary())
573   {
574     SMESH_TLink      _link;
575     TIDSortedElemSet _faces;
576     TFaceLink( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshElement* face)
577       : _link( n1, n2 ), _faces( &face, &face + 1) {}
578   };
579 };
580
581 ostream& operator<< (ostream& out, const SMESH_ElementSearcherImpl::TInters& i)
582 {
583   return out << "TInters(face=" << ( i._face ? i._face->GetID() : 0)
584              << ", _coincides="<<i._coincides << ")";
585 }
586
587 //=======================================================================
588 /*!
589  * \brief define tolerance for search
590  */
591 //=======================================================================
592
593 double SMESH_ElementSearcherImpl::getTolerance()
594 {
595   if ( _tolerance < 0 )
596   {
597     const SMDS_MeshInfo& meshInfo = _mesh->GetMeshInfo();
598
599     _tolerance = 0;
600     if ( _nodeSearcher && meshInfo.NbNodes() > 1 )
601     {
602       double boxSize = _nodeSearcher->getTree()->maxSize();
603       _tolerance = 1e-8 * boxSize/* / meshInfo.NbNodes()*/;
604     }
605     else if ( _ebbTree[_elementType] && meshInfo.NbElements() > 0 )
606     {
607       double boxSize = _ebbTree[_elementType]->maxSize();
608       _tolerance = 1e-8 * boxSize/* / meshInfo.NbElements()*/;
609     }
610     if ( _tolerance == 0 )
611     {
612       // define tolerance by size of a most complex element
613       int complexType = SMDSAbs_Volume;
614       while ( complexType > SMDSAbs_All &&
615               meshInfo.NbElements( SMDSAbs_ElementType( complexType )) < 1 )
616         --complexType;
617       if ( complexType == SMDSAbs_All ) return 0; // empty mesh
618       double elemSize;
619       if ( complexType == int( SMDSAbs_Node ))
620       {
621         SMDS_NodeIteratorPtr nodeIt = _mesh->nodesIterator();
622         elemSize = 1;
623         if ( meshInfo.NbNodes() > 2 )
624           elemSize = SMESH_TNodeXYZ( nodeIt->next() ).Distance( nodeIt->next() );
625       }
626       else
627       {
628         SMDS_ElemIteratorPtr  elemIt = _mesh->elementsIterator( SMDSAbs_ElementType( complexType ));
629         const SMDS_MeshElement* elem = elemIt->next();
630         SMDS_ElemIteratorPtr  nodeIt = elem->nodesIterator();
631         SMESH_TNodeXYZ n1( nodeIt->next() );
632         elemSize = 0;
633         while ( nodeIt->more() )
634         {
635           double dist = n1.Distance( static_cast<const SMDS_MeshNode*>( nodeIt->next() ));
636           elemSize = max( dist, elemSize );
637         }
638       }
639       _tolerance = 1e-4 * elemSize;
640     }
641   }
642   return _tolerance;
643 }
644
645 //================================================================================
646 /*!
647  * \brief Find intersection of the line and an edge of face and return parameter on line
648  */
649 //================================================================================
650
651 bool SMESH_ElementSearcherImpl::getIntersParamOnLine(const gp_Lin&           line,
652                                                      const SMDS_MeshElement* face,
653                                                      const double            tol,
654                                                      double &                param)
655 {
656   int nbInts = 0;
657   param = 0;
658
659   GeomAPI_ExtremaCurveCurve anExtCC;
660   Handle(Geom_Curve) lineCurve = new Geom_Line( line );
661
662   int nbNodes = face->IsQuadratic() ? face->NbNodes()/2 : face->NbNodes();
663   for ( int i = 0; i < nbNodes && nbInts < 2; ++i )
664   {
665     GC_MakeSegment edge( SMESH_TNodeXYZ( face->GetNode( i )),
666                          SMESH_TNodeXYZ( face->GetNode( (i+1)%nbNodes) ));
667     anExtCC.Init( lineCurve, edge.Value() );
668     if ( anExtCC.NbExtrema() > 0 && anExtCC.LowerDistance() <= tol)
669     {
670       Standard_Real pl, pe;
671       anExtCC.LowerDistanceParameters( pl, pe );
672       param += pl;
673       if ( ++nbInts == 2 )
674         break;
675     }
676   }
677   if ( nbInts > 0 ) param /= nbInts;
678   return nbInts > 0;
679 }
680 //================================================================================
681 /*!
682  * \brief Find all faces belonging to the outer boundary of mesh
683  */
684 //================================================================================
685
686 void SMESH_ElementSearcherImpl::findOuterBoundary(const SMDS_MeshElement* outerFace)
687 {
688   if ( _outerFacesFound ) return;
689
690   // Collect all outer faces by passing from one outer face to another via their links
691   // and BTW find out if there are internal faces at all.
692
693   // checked links and links where outer boundary meets internal one
694   set< SMESH_TLink > visitedLinks, seamLinks;
695
696   // links to treat with already visited faces sharing them
697   list < TFaceLink > startLinks;
698
699   // load startLinks with the first outerFace
700   startLinks.push_back( TFaceLink( outerFace->GetNode(0), outerFace->GetNode(1), outerFace));
701   _outerFaces.insert( outerFace );
702
703   TIDSortedElemSet emptySet;
704   while ( !startLinks.empty() )
705   {
706     const SMESH_TLink& link  = startLinks.front()._link;
707     TIDSortedElemSet&  faces = startLinks.front()._faces;
708
709     outerFace = *faces.begin();
710     // find other faces sharing the link
711     const SMDS_MeshElement* f;
712     while (( f = SMESH_MeshAlgos::FindFaceInSet(link.node1(), link.node2(), emptySet, faces )))
713       faces.insert( f );
714
715     // select another outer face among the found
716     const SMDS_MeshElement* outerFace2 = 0;
717     if ( faces.size() == 2 )
718     {
719       outerFace2 = (outerFace == *faces.begin() ? *faces.rbegin() : *faces.begin());
720     }
721     else if ( faces.size() > 2 )
722     {
723       seamLinks.insert( link );
724
725       // link direction within the outerFace
726       gp_Vec n1n2( SMESH_TNodeXYZ( link.node1()),
727                    SMESH_TNodeXYZ( link.node2()));
728       int i1 = outerFace->GetNodeIndex( link.node1() );
729       int i2 = outerFace->GetNodeIndex( link.node2() );
730       bool rev = ( abs(i2-i1) == 1 ? i1 > i2 : i2 > i1 );
731       if ( rev ) n1n2.Reverse();
732       // outerFace normal
733       gp_XYZ ofNorm, fNorm;
734       if ( SMESH_MeshAlgos::FaceNormal( outerFace, ofNorm, /*normalized=*/false ))
735       {
736         // direction from the link inside outerFace
737         gp_Vec dirInOF = gp_Vec( ofNorm ) ^ n1n2;
738         // sort all other faces by angle with the dirInOF
739         map< double, const SMDS_MeshElement* > angle2Face;
740         set< const SMDS_MeshElement*, TIDCompare >::const_iterator face = faces.begin();
741         for ( ; face != faces.end(); ++face )
742         {
743           if ( *face == outerFace ) continue;
744           if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false ))
745             continue;
746           gp_Vec dirInF = gp_Vec( fNorm ) ^ n1n2;
747           double angle = dirInOF.AngleWithRef( dirInF, n1n2 );
748           if ( angle < 0 ) angle += 2. * M_PI;
749           angle2Face.insert( make_pair( angle, *face ));
750         }
751         if ( !angle2Face.empty() )
752           outerFace2 = angle2Face.begin()->second;
753       }
754     }
755     // store the found outer face and add its links to continue searching from
756     if ( outerFace2 )
757     {
758       _outerFaces.insert( outerFace2 );
759       int nbNodes = outerFace2->NbCornerNodes();
760       for ( int i = 0; i < nbNodes; ++i )
761       {
762         SMESH_TLink link2( outerFace2->GetNode(i), outerFace2->GetNode((i+1)%nbNodes));
763         if ( visitedLinks.insert( link2 ).second )
764           startLinks.push_back( TFaceLink( link2.node1(), link2.node2(), outerFace2 ));
765       }
766     }
767     startLinks.pop_front();
768   }
769   _outerFacesFound = true;
770
771   if ( !seamLinks.empty() )
772   {
773     // There are internal boundaries touching the outher one,
774     // find all faces of internal boundaries in order to find
775     // faces of boundaries of holes, if any.
776
777   }
778   else
779   {
780     _outerFaces.clear();
781   }
782 }
783
784 //=======================================================================
785 /*!
786  * \brief Find elements of given type where the given point is IN or ON.
787  *        Returns nb of found elements and elements them-selves.
788  *
789  * 'ALL' type means elements of any type excluding nodes, balls and 0D elements
790  */
791 //=======================================================================
792
793 int SMESH_ElementSearcherImpl::
794 FindElementsByPoint(const gp_Pnt&                      point,
795                     SMDSAbs_ElementType                type,
796                     vector< const SMDS_MeshElement* >& foundElements)
797 {
798   foundElements.clear();
799   _elementType = type;
800
801   double tolerance = getTolerance();
802
803   // =================================================================================
804   if ( type == SMDSAbs_Node || type == SMDSAbs_0DElement || type == SMDSAbs_Ball)
805   {
806     if ( !_nodeSearcher )
807     {
808       if ( _meshPartIt )
809         _nodeSearcher = new SMESH_NodeSearcherImpl( 0, _meshPartIt );
810       else
811         _nodeSearcher = new SMESH_NodeSearcherImpl( _mesh );
812     }
813     std::vector< const SMDS_MeshNode* > foundNodes;
814     _nodeSearcher->FindNearPoint( point, tolerance, foundNodes );
815
816     if ( type == SMDSAbs_Node )
817     {
818       foundElements.assign( foundNodes.begin(), foundNodes.end() );
819     }
820     else
821     {
822       for ( size_t i = 0; i < foundNodes.size(); ++i )
823       {
824         SMDS_ElemIteratorPtr elemIt = foundNodes[i]->GetInverseElementIterator( type );
825         while ( elemIt->more() )
826           foundElements.push_back( elemIt->next() );
827       }
828     }
829   }
830   // =================================================================================
831   else // elements more complex than 0D
832   {
833     if ( !_ebbTree[type] )
834     {
835       _ebbTree[_elementType] = new ElementBndBoxTree( *_mesh, type, _meshPartIt, tolerance );
836     }
837     else
838     {
839       _ebbTree[ type ]->prepare();
840     }
841     vector< const SMDS_MeshElement* > suspectElems;
842     _ebbTree[ type ]->getElementsNearPoint( point, suspectElems );
843     vector< const SMDS_MeshElement* >::iterator elem = suspectElems.begin();
844     for ( ; elem != suspectElems.end(); ++elem )
845       if ( !SMESH_MeshAlgos::IsOut( *elem, point, tolerance ))
846         foundElements.push_back( *elem );
847   }
848   return foundElements.size();
849 }
850
851 //=======================================================================
852 /*!
853  * \brief Find an element of given type most close to the given point
854  *
855  * WARNING: Only face search is implemeneted so far
856  */
857 //=======================================================================
858
859 const SMDS_MeshElement*
860 SMESH_ElementSearcherImpl::FindClosestTo( const gp_Pnt&       point,
861                                           SMDSAbs_ElementType type )
862 {
863   const SMDS_MeshElement* closestElem = 0;
864   _elementType = type;
865
866   if ( type == SMDSAbs_Face || type == SMDSAbs_Volume )
867   {
868     ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
869     if ( !ebbTree )
870       ebbTree = new ElementBndBoxTree( *_mesh, type, _meshPartIt );
871     else
872       ebbTree->prepare();
873
874     vector<const SMDS_MeshElement*> suspectElems;
875     ebbTree->getElementsNearPoint( point, suspectElems );
876
877     if ( suspectElems.empty() && ebbTree->maxSize() > 0 )
878     {
879       gp_Pnt boxCenter = 0.5 * ( ebbTree->getBox()->CornerMin() +
880                                  ebbTree->getBox()->CornerMax() );
881       double radius = -1;
882       if ( ebbTree->getBox()->IsOut( point.XYZ() ))
883         radius = point.Distance( boxCenter ) - 0.5 * ebbTree->maxSize();
884       if ( radius < 0 )
885         radius = ebbTree->maxSize() / pow( 2., getTreeHeight()) / 2;
886       while ( suspectElems.empty() )
887       {
888         ebbTree->prepare();
889         ebbTree->getElementsInSphere( point.XYZ(), radius, suspectElems );
890         radius *= 1.1;
891       }
892     }
893     double minDist = std::numeric_limits<double>::max();
894     multimap< double, const SMDS_MeshElement* > dist2face;
895     vector<const SMDS_MeshElement*>::iterator elem = suspectElems.begin();
896     for ( ; elem != suspectElems.end(); ++elem )
897     {
898       double dist = SMESH_MeshAlgos::GetDistance( *elem, point );
899       if ( dist < minDist + 1e-10)
900       {
901         minDist = dist;
902         dist2face.insert( dist2face.begin(), make_pair( dist, *elem ));
903       }
904     }
905     if ( !dist2face.empty() )
906     {
907       multimap< double, const SMDS_MeshElement* >::iterator d2f = dist2face.begin();
908       closestElem = d2f->second;
909       // if there are several elements at the same distance, select one
910       // with GC closest to the point
911       typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
912       double minDistToGC = 0;
913       for ( ++d2f; d2f != dist2face.end() && fabs( d2f->first - minDist ) < 1e-10; ++d2f )
914       {
915         if ( minDistToGC == 0 )
916         {
917           gp_XYZ gc(0,0,0);
918           gc = accumulate( TXyzIterator(closestElem->nodesIterator()),
919                            TXyzIterator(), gc ) / closestElem->NbNodes();
920           minDistToGC = point.SquareDistance( gc );
921         }
922         gp_XYZ gc(0,0,0);
923         gc = accumulate( TXyzIterator( d2f->second->nodesIterator()),
924                          TXyzIterator(), gc ) / d2f->second->NbNodes();
925         double d = point.SquareDistance( gc );
926         if ( d < minDistToGC )
927         {
928           minDistToGC = d;
929           closestElem = d2f->second;
930         }
931       }
932       // cout << "FindClosestTo( " <<point.X()<<", "<<point.Y()<<", "<<point.Z()<<" ) FACE "
933       //      <<closestElem->GetID() << " DIST " << minDist << endl;
934     }
935   }
936   else
937   {
938     // NOT IMPLEMENTED SO FAR
939   }
940   return closestElem;
941 }
942
943
944 //================================================================================
945 /*!
946  * \brief Classify the given point in the closed 2D mesh
947  */
948 //================================================================================
949
950 TopAbs_State SMESH_ElementSearcherImpl::GetPointState(const gp_Pnt& point)
951 {
952   _elementType = SMDSAbs_Face;
953
954   double tolerance = getTolerance();
955
956   ElementBndBoxTree*& ebbTree = _ebbTree[ SMDSAbs_Face ];
957   if ( !ebbTree )
958     ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
959   else
960     ebbTree->prepare();
961
962   // Algo: analyse transition of a line starting at the point through mesh boundary;
963   // try three lines parallel to axis of the coordinate system and perform rough
964   // analysis. If solution is not clear perform thorough analysis.
965
966   const int nbAxes = 3;
967   gp_Dir axisDir[ nbAxes ] = { gp::DX(), gp::DY(), gp::DZ() };
968   map< double, TInters >   paramOnLine2TInters[ nbAxes ];
969   list< TInters > tangentInters[ nbAxes ]; // of faces whose plane includes the line
970   multimap< int, int > nbInt2Axis; // to find the simplest case
971   for ( int axis = 0; axis < nbAxes; ++axis )
972   {
973     gp_Ax1 lineAxis( point, axisDir[axis]);
974     gp_Lin line    ( lineAxis );
975
976     vector<const SMDS_MeshElement*> suspectFaces; // faces possibly intersecting the line
977     if ( axis > 0 ) ebbTree->prepare();
978     ebbTree->getElementsNearLine( lineAxis, suspectFaces );
979
980     // Intersect faces with the line
981
982     map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
983     vector<const SMDS_MeshElement*>::iterator face = suspectFaces.begin();
984     for ( ; face != suspectFaces.end(); ++face )
985     {
986       // get face plane
987       gp_XYZ fNorm;
988       if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false)) continue;
989       gp_Pln facePlane( SMESH_TNodeXYZ( (*face)->GetNode(0)), fNorm );
990
991       // perform intersection
992       IntAna_IntConicQuad intersection( line, IntAna_Quadric( facePlane ));
993       if ( !intersection.IsDone() )
994         continue;
995       if ( intersection.IsInQuadric() )
996       {
997         tangentInters[ axis ].push_back( TInters( *face, fNorm, true ));
998       }
999       else if ( ! intersection.IsParallel() && intersection.NbPoints() > 0 )
1000       {
1001         double tol = 1e-4 * Sqrt( fNorm.Modulus() );
1002         gp_Pnt intersectionPoint = intersection.Point(1);
1003         if ( !SMESH_MeshAlgos::IsOut( *face, intersectionPoint, tol ))
1004           u2inters.insert(make_pair( intersection.ParamOnConic(1), TInters( *face, fNorm )));
1005       }
1006     }
1007     // Analyse intersections roughly
1008
1009     int nbInter = u2inters.size();
1010     if ( nbInter == 0 )
1011       return TopAbs_OUT;
1012
1013     double f = u2inters.begin()->first, l = u2inters.rbegin()->first;
1014     if ( nbInter == 1 ) // not closed mesh
1015       return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
1016
1017     if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
1018       return TopAbs_ON;
1019
1020     if ( (f<0) == (l<0) )
1021       return TopAbs_OUT;
1022
1023     int nbIntBeforePoint = std::distance( u2inters.begin(), u2inters.lower_bound(0));
1024     int nbIntAfterPoint  = nbInter - nbIntBeforePoint;
1025     if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
1026       return TopAbs_IN;
1027
1028     nbInt2Axis.insert( make_pair( min( nbIntBeforePoint, nbIntAfterPoint ), axis ));
1029
1030     if ( _outerFacesFound ) break; // pass to thorough analysis
1031
1032   } // three attempts - loop on CS axes
1033
1034   // Analyse intersections thoroughly.
1035   // We make two loops maximum, on the first one we only exclude touching intersections,
1036   // on the second, if situation is still unclear, we gather and use information on
1037   // position of faces (internal or outer). If faces position is already gathered,
1038   // we make the second loop right away.
1039
1040   for ( int hasPositionInfo = _outerFacesFound; hasPositionInfo < 2; ++hasPositionInfo )
1041   {
1042     multimap< int, int >::const_iterator nb_axis = nbInt2Axis.begin();
1043     for ( ; nb_axis != nbInt2Axis.end(); ++nb_axis )
1044     {
1045       int axis = nb_axis->second;
1046       map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
1047
1048       gp_Ax1 lineAxis( point, axisDir[axis]);
1049       gp_Lin line    ( lineAxis );
1050
1051       // add tangent intersections to u2inters
1052       double param;
1053       list< TInters >::const_iterator tgtInt = tangentInters[ axis ].begin();
1054       for ( ; tgtInt != tangentInters[ axis ].end(); ++tgtInt )
1055         if ( getIntersParamOnLine( line, tgtInt->_face, tolerance, param ))
1056           u2inters.insert(make_pair( param, *tgtInt ));
1057       tangentInters[ axis ].clear();
1058
1059       // Count intersections before and after the point excluding touching ones.
1060       // If hasPositionInfo we count intersections of outer boundary only
1061
1062       int nbIntBeforePoint = 0, nbIntAfterPoint = 0;
1063       double f = numeric_limits<double>::max(), l = -numeric_limits<double>::max();
1064       map< double, TInters >::iterator u_int1 = u2inters.begin(), u_int2 = u_int1;
1065       bool ok = ! u_int1->second._coincides;
1066       while ( ok && u_int1 != u2inters.end() )
1067       {
1068         double u = u_int1->first;
1069         bool touchingInt = false;
1070         if ( ++u_int2 != u2inters.end() )
1071         {
1072           // skip intersections at the same point (if the line passes through edge or node)
1073           int nbSamePnt = 0;
1074           while ( u_int2 != u2inters.end() && fabs( u_int2->first - u ) < tolerance )
1075           {
1076             ++nbSamePnt;
1077             ++u_int2;
1078           }
1079
1080           // skip tangent intersections
1081           int nbTgt = 0;
1082           if ( u_int2 != u2inters.end() )
1083           {
1084             const SMDS_MeshElement* prevFace = u_int1->second._face;
1085             while ( ok && u_int2->second._coincides )
1086             {
1087               if ( SMESH_MeshAlgos::GetCommonNodes(prevFace , u_int2->second._face).empty() )
1088                 ok = false;
1089               else
1090               {
1091                 nbTgt++;
1092                 u_int2++;
1093                 ok = ( u_int2 != u2inters.end() );
1094               }
1095             }
1096           }
1097           if ( !ok ) break;
1098
1099           // skip intersections at the same point after tangent intersections
1100           if ( nbTgt > 0 )
1101           {
1102             double u2 = u_int2->first;
1103             ++u_int2;
1104             while ( u_int2 != u2inters.end() && fabs( u_int2->first - u2 ) < tolerance )
1105             {
1106               ++nbSamePnt;
1107               ++u_int2;
1108             }
1109           }
1110           // decide if we skipped a touching intersection
1111           if ( nbSamePnt + nbTgt > 0 )
1112           {
1113             double minDot = numeric_limits<double>::max(), maxDot = -numeric_limits<double>::max();
1114             map< double, TInters >::iterator u_int = u_int1;
1115             for ( ; u_int != u_int2; ++u_int )
1116             {
1117               if ( u_int->second._coincides ) continue;
1118               double dot = u_int->second._faceNorm * line.Direction();
1119               if ( dot > maxDot ) maxDot = dot;
1120               if ( dot < minDot ) minDot = dot;
1121             }
1122             touchingInt = ( minDot*maxDot < 0 );
1123           }
1124         }
1125         if ( !touchingInt )
1126         {
1127           if ( !hasPositionInfo || isOuterBoundary( u_int1->second._face ))
1128           {
1129             if ( u < 0 )
1130               ++nbIntBeforePoint;
1131             else
1132               ++nbIntAfterPoint;
1133           }
1134           if ( u < f ) f = u;
1135           if ( u > l ) l = u;
1136         }
1137
1138         u_int1 = u_int2; // to next intersection
1139
1140       } // loop on intersections with one line
1141
1142       if ( ok )
1143       {
1144         if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
1145           return TopAbs_ON;
1146
1147         if ( nbIntBeforePoint == 0  || nbIntAfterPoint == 0)
1148           return TopAbs_OUT;
1149
1150         if ( nbIntBeforePoint + nbIntAfterPoint == 1 ) // not closed mesh
1151           return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
1152
1153         if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
1154           return TopAbs_IN;
1155
1156         if ( (f<0) == (l<0) )
1157           return TopAbs_OUT;
1158
1159         if ( hasPositionInfo )
1160           return nbIntBeforePoint % 2 ? TopAbs_IN : TopAbs_OUT;
1161       }
1162     } // loop on intersections of the tree lines - thorough analysis
1163
1164     if ( !hasPositionInfo )
1165     {
1166       // gather info on faces position - is face in the outer boundary or not
1167       map< double, TInters > & u2inters = paramOnLine2TInters[ 0 ];
1168       findOuterBoundary( u2inters.begin()->second._face );
1169     }
1170
1171   } // two attempts - with and w/o faces position info in the mesh
1172
1173   return TopAbs_UNKNOWN;
1174 }
1175
1176 //=======================================================================
1177 /*!
1178  * \brief Return elements possibly intersecting the line
1179  */
1180 //=======================================================================
1181
1182 void SMESH_ElementSearcherImpl::GetElementsNearLine( const gp_Ax1&                      line,
1183                                                      SMDSAbs_ElementType                type,
1184                                                      vector< const SMDS_MeshElement* >& foundElems)
1185 {
1186   _elementType = type;
1187   ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
1188   if ( !ebbTree )
1189     ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
1190   else
1191     ebbTree->prepare();
1192
1193   ebbTree->getElementsNearLine( line, foundElems );
1194 }
1195
1196 //=======================================================================
1197 /*
1198  * Return elements whose bounding box intersects a sphere
1199  */
1200 //=======================================================================
1201
1202 void SMESH_ElementSearcherImpl::GetElementsInSphere( const gp_XYZ&                      center,
1203                                                      const double                       radius,
1204                                                      SMDSAbs_ElementType                type,
1205                                                      vector< const SMDS_MeshElement* >& foundElems)
1206 {
1207   _elementType = type;
1208   ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
1209   if ( !ebbTree )
1210     ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
1211   else
1212     ebbTree->prepare();
1213
1214   ebbTree->getElementsInSphere( center, radius, foundElems );
1215 }
1216
1217 //=======================================================================
1218 /*!
1219  * \brief Return true if the point is IN or ON of the element
1220  */
1221 //=======================================================================
1222
1223 bool SMESH_MeshAlgos::IsOut( const SMDS_MeshElement* element, const gp_Pnt& point, double tol )
1224 {
1225   if ( element->GetType() == SMDSAbs_Volume)
1226   {
1227     return SMDS_VolumeTool( element ).IsOut( point.X(), point.Y(), point.Z(), tol );
1228   }
1229
1230   // get ordered nodes
1231
1232   vector< SMESH_TNodeXYZ > xyz; xyz.reserve( element->NbNodes()+1 );
1233
1234   SMDS_ElemIteratorPtr nodeIt = element->interlacedNodesElemIterator();
1235   for ( int i = 0; nodeIt->more(); ++i )
1236     xyz.push_back( SMESH_TNodeXYZ( nodeIt->next() ));
1237
1238   int i, nbNodes = (int) xyz.size(); // central node of biquadratic is missing
1239
1240   if ( element->GetType() == SMDSAbs_Face ) // --------------------------------------------------
1241   {
1242     // compute face normal
1243     gp_Vec faceNorm(0,0,0);
1244     xyz.push_back( xyz.front() );
1245     for ( i = 0; i < nbNodes; ++i )
1246     {
1247       gp_Vec edge1( xyz[i+1], xyz[i]);
1248       gp_Vec edge2( xyz[i+1], xyz[(i+2)%nbNodes] );
1249       faceNorm += edge1 ^ edge2;
1250     }
1251     double fNormSize = faceNorm.Magnitude();
1252     if ( fNormSize <= tol )
1253     {
1254       // degenerated face: point is out if it is out of all face edges
1255       for ( i = 0; i < nbNodes; ++i )
1256       {
1257         SMDS_LinearEdge edge( xyz[i]._node, xyz[i+1]._node );
1258         if ( !IsOut( &edge, point, tol ))
1259           return false;
1260       }
1261       return true;
1262     }
1263     faceNorm /= fNormSize;
1264
1265     // check if the point lays on face plane
1266     gp_Vec n2p( xyz[0], point );
1267     double dot = n2p * faceNorm;
1268     if ( Abs( dot ) > tol ) // not on face plane
1269     {
1270       bool isOut = true;
1271       if ( nbNodes > 3 ) // maybe the face is not planar
1272       {
1273         double elemThick = 0;
1274         for ( i = 1; i < nbNodes; ++i )
1275         {
1276           gp_Vec n2n( xyz[0], xyz[i] );
1277           elemThick = Max( elemThick, Abs( n2n * faceNorm ));
1278         }
1279         isOut = Abs( dot ) > elemThick + tol;
1280       }
1281       if ( isOut )
1282         return isOut;
1283     }
1284
1285     // check if point is out of face boundary:
1286     // define it by closest transition of a ray point->infinity through face boundary
1287     // on the face plane.
1288     // First, find normal of a plane perpendicular to face plane, to be used as a cutting tool
1289     // to find intersections of the ray with the boundary.
1290     gp_Vec ray = n2p;
1291     gp_Vec plnNorm = ray ^ faceNorm;
1292     double n2pSize = plnNorm.Magnitude();
1293     if ( n2pSize <= tol ) return false; // point coincides with the first node
1294     if ( n2pSize * n2pSize > fNormSize * 100 ) return true; // point is very far
1295     plnNorm /= n2pSize;
1296     // for each node of the face, compute its signed distance to the cutting plane
1297     vector<double> dist( nbNodes + 1);
1298     for ( i = 0; i < nbNodes; ++i )
1299     {
1300       gp_Vec n2p( xyz[i], point );
1301       dist[i] = n2p * plnNorm;
1302     }
1303     dist.back() = dist.front();
1304     // find the closest intersection
1305     int    iClosest = -1;
1306     double rClosest = 0, distClosest = 1e100;
1307     gp_Pnt pClosest;
1308     for ( i = 0; i < nbNodes; ++i )
1309     {
1310       double r;
1311       if ( fabs( dist[i] ) < tol )
1312         r = 0.;
1313       else if ( fabs( dist[i+1]) < tol )
1314         r = 1.;
1315       else if ( dist[i] * dist[i+1] < 0 )
1316         r = dist[i] / ( dist[i] - dist[i+1] );
1317       else
1318         continue; // no intersection
1319       gp_Pnt pInt = xyz[i] * (1.-r) + xyz[i+1] * r;
1320       gp_Vec p2int( point, pInt);
1321       double intDist = p2int.SquareMagnitude();
1322       if ( intDist < distClosest )
1323       {
1324         iClosest = i;
1325         rClosest = r;
1326         pClosest = pInt;
1327         distClosest = intDist;
1328       }
1329     }
1330     if ( iClosest < 0 )
1331       return true; // no intesections - out
1332
1333     // analyse transition
1334     gp_Vec edge( xyz[iClosest], xyz[iClosest+1] );
1335     gp_Vec edgeNorm = -( edge ^ faceNorm ); // normal to intersected edge pointing out of face
1336     gp_Vec p2int ( point, pClosest );
1337     bool out = (edgeNorm * p2int) < -tol;
1338     if ( rClosest > 0. && rClosest < 1. ) // not node intersection
1339       return out;
1340
1341     // the ray passes through a face node; analyze transition through an adjacent edge
1342     gp_Pnt p1 = xyz[ (rClosest == 0.) ? ((iClosest+nbNodes-1) % nbNodes) : (iClosest+1) ];
1343     gp_Pnt p2 = xyz[ (rClosest == 0.) ? iClosest : ((iClosest+2) % nbNodes) ];
1344     gp_Vec edgeAdjacent( p1, p2 );
1345     gp_Vec edgeNorm2 = -( edgeAdjacent ^ faceNorm );
1346     bool out2 = (edgeNorm2 * p2int) < -tol;
1347
1348     bool covexCorner = ( edgeNorm * edgeAdjacent * (rClosest==1. ? 1. : -1.)) < 0;
1349     return covexCorner ? (out || out2) : (out && out2);
1350   }
1351
1352   if ( element->GetType() == SMDSAbs_Edge ) // --------------------------------------------------
1353   {
1354     // point is out of edge if it is NOT ON any straight part of edge
1355     // (we consider quadratic edge as being composed of two straight parts)
1356     for ( i = 1; i < nbNodes; ++i )
1357     {
1358       gp_Vec edge( xyz[i-1], xyz[i] );
1359       gp_Vec n1p ( xyz[i-1], point  );
1360       double u = ( edge * n1p ) / edge.SquareMagnitude(); // param [0,1] on the edge
1361       if ( u <= 0. ) {
1362         if ( n1p.SquareMagnitude() < tol * tol )
1363           return false;
1364         continue;
1365       }
1366       if ( u >= 1. ) {
1367         if ( point.SquareDistance( xyz[i] ) < tol * tol )
1368           return false;
1369         continue;
1370       }
1371       gp_XYZ proj = ( 1. - u ) * xyz[i-1] + u * xyz[i]; // projection of the point on the edge
1372       double dist2 = point.SquareDistance( proj );
1373       if ( dist2 > tol * tol )
1374         continue;
1375       return false; // point is ON this part
1376     }
1377     return true;
1378   }
1379
1380   // Node or 0D element -------------------------------------------------------------------------
1381   {
1382     gp_Vec n2p ( xyz[0], point );
1383     return n2p.SquareMagnitude() > tol * tol;
1384   }
1385   return true;
1386 }
1387
1388 //=======================================================================
1389 namespace
1390 {
1391   // Position of a point relative to a segment
1392   //            .           .
1393   //            .  LEFT     .
1394   //            .           .
1395   //  VERTEX 1  o----ON----->  VERTEX 2
1396   //            .           .
1397   //            .  RIGHT    .
1398   //            .           .
1399   enum PositionName { POS_LEFT = 1, POS_VERTEX = 2, POS_RIGHT = 4, //POS_ON = 8,
1400                       POS_ALL = POS_LEFT | POS_RIGHT | POS_VERTEX };
1401   struct PointPos
1402   {
1403     PositionName _name;
1404     int          _index; // index of vertex or segment
1405
1406     PointPos( PositionName n, int i=-1 ): _name(n), _index(i) {}
1407     bool operator < (const PointPos& other ) const
1408     {
1409       if ( _name == other._name )
1410         return  ( _index < 0 || other._index < 0 ) ? false : _index < other._index;
1411       return _name < other._name;
1412     }
1413   };
1414
1415   //================================================================================
1416   /*!
1417    * \brief Return of a point relative to a segment
1418    *  \param point2D      - the point to analyze position of
1419    *  \param xyVec        - end points of segments
1420    *  \param index0       - 0-based index of the first point of segment
1421    *  \param posToFindOut - flags of positions to detect
1422    *  \retval PointPos - point position
1423    */
1424   //================================================================================
1425
1426   PointPos getPointPosition( const gp_XY& point2D,
1427                              const gp_XY* segEnds,
1428                              const int    index0 = 0,
1429                              const int    posToFindOut = POS_ALL)
1430   {
1431     const gp_XY& p1 = segEnds[ index0   ];
1432     const gp_XY& p2 = segEnds[ index0+1 ];
1433     const gp_XY grad = p2 - p1;
1434
1435     if ( posToFindOut & POS_VERTEX )
1436     {
1437       // check if the point2D is at "vertex 1" zone
1438       gp_XY pp1[2] = { p1, gp_XY( p1.X() - grad.Y(),
1439                                   p1.Y() + grad.X() ) };
1440       if ( getPointPosition( point2D, pp1, 0, POS_LEFT|POS_RIGHT )._name == POS_LEFT )
1441         return PointPos( POS_VERTEX, index0 );
1442
1443       // check if the point2D is at "vertex 2" zone
1444       gp_XY pp2[2] = { p2, gp_XY( p2.X() - grad.Y(),
1445                                   p2.Y() + grad.X() ) };
1446       if ( getPointPosition( point2D, pp2, 0, POS_LEFT|POS_RIGHT )._name == POS_RIGHT )
1447         return PointPos( POS_VERTEX, index0 + 1);
1448     }
1449     double edgeEquation =
1450       ( point2D.X() - p1.X() ) * grad.Y() - ( point2D.Y() - p1.Y() ) * grad.X();
1451     return PointPos( edgeEquation < 0 ? POS_LEFT : POS_RIGHT, index0 );
1452   }
1453 }
1454
1455 //=======================================================================
1456 /*!
1457  * \brief Return minimal distance from a point to an element
1458  *
1459  * Currently we ignore non-planarity and 2nd order of face
1460  */
1461 //=======================================================================
1462
1463 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshElement* elem,
1464                                      const gp_Pnt&           point )
1465 {
1466   switch ( elem->GetType() )
1467   {
1468   case SMDSAbs_Volume:
1469     return GetDistance( dynamic_cast<const SMDS_MeshVolume*>( elem ), point);
1470   case SMDSAbs_Face:
1471     return GetDistance( dynamic_cast<const SMDS_MeshFace*>( elem ), point);
1472   case SMDSAbs_Edge:
1473     return GetDistance( dynamic_cast<const SMDS_MeshEdge*>( elem ), point);
1474   case SMDSAbs_Node:
1475     return point.Distance( SMESH_TNodeXYZ( elem ));
1476   default:;
1477   }
1478   return -1;
1479 }
1480
1481 //=======================================================================
1482 /*!
1483  * \brief Return minimal distance from a point to a face
1484  *
1485  * Currently we ignore non-planarity and 2nd order of face
1486  */
1487 //=======================================================================
1488
1489 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshFace* face,
1490                                      const gp_Pnt&        point )
1491 {
1492   double badDistance = -1;
1493   if ( !face ) return badDistance;
1494
1495   // coordinates of nodes (medium nodes, if any, ignored)
1496   typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
1497   vector<gp_XYZ> xyz( TXyzIterator( face->nodesIterator()), TXyzIterator() );
1498   xyz.resize( face->NbCornerNodes()+1 );
1499
1500   // transformation to get xyz[0] lies on the origin, xyz[1] lies on the Z axis,
1501   // and xyz[2] lies in the XZ plane. This is to pass to 2D space on XZ plane.
1502   gp_Trsf trsf;
1503   gp_Vec OZ ( xyz[0], xyz[1] );
1504   gp_Vec OX ( xyz[0], xyz[2] );
1505   if ( OZ.Magnitude() < std::numeric_limits<double>::min() )
1506   {
1507     if ( xyz.size() < 4 ) return badDistance;
1508     OZ = gp_Vec ( xyz[0], xyz[2] );
1509     OX = gp_Vec ( xyz[0], xyz[3] );
1510   }
1511   gp_Ax3 tgtCS;
1512   try {
1513     tgtCS = gp_Ax3( xyz[0], OZ, OX );
1514   }
1515   catch ( Standard_Failure ) {
1516     return badDistance;
1517   }
1518   trsf.SetTransformation( tgtCS );
1519
1520   // move all the nodes to 2D
1521   vector<gp_XY> xy( xyz.size() );
1522   for ( size_t i = 0;i < xyz.size()-1; ++i )
1523   {
1524     gp_XYZ p3d = xyz[i];
1525     trsf.Transforms( p3d );
1526     xy[i].SetCoord( p3d.X(), p3d.Z() );
1527   }
1528   xyz.back() = xyz.front();
1529   xy.back() = xy.front();
1530
1531   // // move the point in 2D
1532   gp_XYZ tmpPnt = point.XYZ();
1533   trsf.Transforms( tmpPnt );
1534   gp_XY point2D( tmpPnt.X(), tmpPnt.Z() );
1535
1536   // loop on segments of the face to analyze point position ralative to the face
1537   set< PointPos > pntPosSet;
1538   for ( size_t i = 1; i < xy.size(); ++i )
1539   {
1540     PointPos pos = getPointPosition( point2D, &xy[0], i-1 );
1541     pntPosSet.insert( pos );
1542   }
1543
1544   // compute distance
1545   PointPos pos = *pntPosSet.begin();
1546   // cout << "Face " << face->GetID() << " DIST: ";
1547   switch ( pos._name )
1548   {
1549   case POS_LEFT: {
1550     // point is most close to a segment
1551     gp_Vec p0p1( point, xyz[ pos._index ] );
1552     gp_Vec p1p2( xyz[ pos._index ], xyz[ pos._index+1 ]); // segment vector
1553     p1p2.Normalize();
1554     double projDist = p0p1 * p1p2; // distance projected to the segment
1555     gp_Vec projVec = p1p2 * projDist;
1556     gp_Vec distVec = p0p1 - projVec;
1557     // cout << distVec.Magnitude()  << ", SEG " << face->GetNode(pos._index)->GetID()
1558     //      << " - " << face->GetNodeWrap(pos._index+1)->GetID() << endl;
1559     return distVec.Magnitude();
1560   }
1561   case POS_RIGHT: {
1562     // point is inside the face
1563     double distToFacePlane = tmpPnt.Y();
1564     // cout << distToFacePlane << ", INSIDE " << endl;
1565     return Abs( distToFacePlane );
1566   }
1567   case POS_VERTEX: {
1568     // point is most close to a node
1569     gp_Vec distVec( point, xyz[ pos._index ]);
1570     // cout << distVec.Magnitude()  << " VERTEX " << face->GetNode(pos._index)->GetID() << endl;
1571     return distVec.Magnitude();
1572   }
1573   default:;
1574   }
1575   return badDistance;
1576 }
1577
1578 //=======================================================================
1579 /*!
1580  * \brief Return minimal distance from a point to an edge
1581  */
1582 //=======================================================================
1583
1584 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshEdge* seg, const gp_Pnt& point )
1585 {
1586   double dist = Precision::Infinite();
1587   if ( !seg ) return dist;
1588
1589   int i = 0, nbNodes = seg->NbNodes();
1590
1591   vector< SMESH_TNodeXYZ > xyz( nbNodes );
1592   SMDS_ElemIteratorPtr nodeIt = seg->interlacedNodesElemIterator();
1593   while ( nodeIt->more() )
1594     xyz[ i++ ].Set( nodeIt->next() );
1595
1596   for ( i = 1; i < nbNodes; ++i )
1597   {
1598     gp_Vec edge( xyz[i-1], xyz[i] );
1599     gp_Vec n1p ( xyz[i-1], point  );
1600     double u = ( edge * n1p ) / edge.SquareMagnitude(); // param [0,1] on the edge
1601     if ( u <= 0. ) {
1602       dist = Min( dist, n1p.SquareMagnitude() );
1603     }
1604     else if ( u >= 1. ) {
1605       dist = Min( dist, point.SquareDistance( xyz[i] ));
1606     }
1607     else {
1608       gp_XYZ proj = ( 1. - u ) * xyz[i-1] + u * xyz[i]; // projection of the point on the edge
1609       dist = Min( dist, point.SquareDistance( proj ));
1610     }
1611   }
1612   return Sqrt( dist );
1613 }
1614
1615 //=======================================================================
1616 /*!
1617  * \brief Return minimal distance from a point to a volume
1618  *
1619  * Currently we ignore non-planarity and 2nd order
1620  */
1621 //=======================================================================
1622
1623 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshVolume* volume, const gp_Pnt& point )
1624 {
1625   SMDS_VolumeTool vTool( volume );
1626   vTool.SetExternalNormal();
1627   const int iQ = volume->IsQuadratic() ? 2 : 1;
1628
1629   double n[3], bc[3];
1630   double minDist = 1e100, dist;
1631   for ( int iF = 0; iF < vTool.NbFaces(); ++iF )
1632   {
1633     // skip a facet with normal not "looking at" the point
1634     if ( !vTool.GetFaceNormal( iF, n[0], n[1], n[2] ) ||
1635          !vTool.GetFaceBaryCenter( iF, bc[0], bc[1], bc[2] ))
1636       continue;
1637     gp_XYZ bcp = point.XYZ() - gp_XYZ( bc[0], bc[1], bc[2] );
1638     if ( gp_XYZ( n[0], n[1], n[2] ) * bcp < 1e-6 )
1639       continue;
1640
1641     // find distance to a facet
1642     const SMDS_MeshNode** nodes = vTool.GetFaceNodes( iF );
1643     switch ( vTool.NbFaceNodes( iF ) / iQ ) {
1644     case 3:
1645     {
1646       SMDS_FaceOfNodes tmpFace( nodes[0], nodes[ 1*iQ ], nodes[ 2*iQ ] );
1647       dist = GetDistance( &tmpFace, point );
1648       break;
1649     }
1650     case 4:
1651     {
1652       SMDS_FaceOfNodes tmpFace( nodes[0], nodes[ 1*iQ ], nodes[ 2*iQ ], nodes[ 3*iQ ]);
1653       dist = GetDistance( &tmpFace, point );
1654       break;
1655     }
1656     default:
1657       vector<const SMDS_MeshNode *> nvec( nodes, nodes + vTool.NbFaceNodes( iF ));
1658       SMDS_PolygonalFaceOfNodes tmpFace( nvec );
1659       dist = GetDistance( &tmpFace, point );
1660     }
1661     minDist = Min( minDist, dist );
1662   }
1663   return minDist;
1664 }
1665
1666 //================================================================================
1667 /*!
1668  * \brief Returns barycentric coordinates of a point within a triangle.
1669  *        A not returned bc2 = 1. - bc0 - bc1.
1670  *        The point lies within the triangle if ( bc0 >= 0 && bc1 >= 0 && bc0+bc1 <= 1 )
1671  */
1672 //================================================================================
1673
1674 void SMESH_MeshAlgos::GetBarycentricCoords( const gp_XY& p,
1675                                             const gp_XY& t0,
1676                                             const gp_XY& t1,
1677                                             const gp_XY& t2,
1678                                             double &     bc0,
1679                                             double &     bc1)
1680 {
1681   const double // matrix 2x2
1682     T11 = t0.X()-t2.X(), T12 = t1.X()-t2.X(),
1683     T21 = t0.Y()-t2.Y(), T22 = t1.Y()-t2.Y();
1684   const double Tdet = T11*T22 - T12*T21; // matrix determinant
1685   if ( Abs( Tdet ) < std::numeric_limits<double>::min() )
1686   {
1687     bc0 = bc1 = 2.;
1688     return;
1689   }
1690   // matrix inverse
1691   const double t11 = T22, t12 = -T12, t21 = -T21, t22 = T11;
1692   // vector
1693   const double r11 = p.X()-t2.X(), r12 = p.Y()-t2.Y();
1694   // barycentric coordinates: mutiply matrix by vector
1695   bc0 = (t11 * r11 + t12 * r12)/Tdet;
1696   bc1 = (t21 * r11 + t22 * r12)/Tdet;
1697 }
1698
1699 //=======================================================================
1700 //function : FindFaceInSet
1701 //purpose  : Return a face having linked nodes n1 and n2 and which is
1702 //           - not in avoidSet,
1703 //           - in elemSet provided that !elemSet.empty()
1704 //           i1 and i2 optionally returns indices of n1 and n2
1705 //=======================================================================
1706
1707 const SMDS_MeshElement*
1708 SMESH_MeshAlgos::FindFaceInSet(const SMDS_MeshNode*    n1,
1709                                const SMDS_MeshNode*    n2,
1710                                const TIDSortedElemSet& elemSet,
1711                                const TIDSortedElemSet& avoidSet,
1712                                int*                    n1ind,
1713                                int*                    n2ind)
1714
1715 {
1716   int i1 = 0, i2 = 0;
1717   const SMDS_MeshElement* face = 0;
1718
1719   SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator(SMDSAbs_Face);
1720   while ( invElemIt->more() && !face ) // loop on inverse faces of n1
1721   {
1722     const SMDS_MeshElement* elem = invElemIt->next();
1723     if (avoidSet.count( elem ))
1724       continue;
1725     if ( !elemSet.empty() && !elemSet.count( elem ))
1726       continue;
1727     // index of n1
1728     i1 = elem->GetNodeIndex( n1 );
1729     // find a n2 linked to n1
1730     int nbN = elem->IsQuadratic() ? elem->NbNodes()/2 : elem->NbNodes();
1731     for ( int di = -1; di < 2 && !face; di += 2 )
1732     {
1733       i2 = (i1+di+nbN) % nbN;
1734       if ( elem->GetNode( i2 ) == n2 )
1735         face = elem;
1736     }
1737     if ( !face && elem->IsQuadratic())
1738     {
1739       // analysis for quadratic elements using all nodes
1740       SMDS_ElemIteratorPtr anIter = elem->interlacedNodesElemIterator();
1741       const SMDS_MeshNode* prevN = static_cast<const SMDS_MeshNode*>( anIter->next() );
1742       for ( i1 = -1, i2 = 0; anIter->more() && !face; i1++, i2++ )
1743       {
1744         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( anIter->next() );
1745         if ( n1 == prevN && n2 == n )
1746         {
1747           face = elem;
1748         }
1749         else if ( n2 == prevN && n1 == n )
1750         {
1751           face = elem; swap( i1, i2 );
1752         }
1753         prevN = n;
1754       }
1755     }
1756   }
1757   if ( n1ind ) *n1ind = i1;
1758   if ( n2ind ) *n2ind = i2;
1759   return face;
1760 }
1761
1762 //================================================================================
1763 /*!
1764  * \brief Calculate normal of a mesh face
1765  */
1766 //================================================================================
1767
1768 bool SMESH_MeshAlgos::FaceNormal(const SMDS_MeshElement* F, gp_XYZ& normal, bool normalized)
1769 {
1770   if ( !F || F->GetType() != SMDSAbs_Face )
1771     return false;
1772
1773   normal.SetCoord(0,0,0);
1774   int nbNodes = F->NbCornerNodes();
1775   for ( int i = 0; i < nbNodes-2; ++i )
1776   {
1777     gp_XYZ p[3];
1778     for ( int n = 0; n < 3; ++n )
1779     {
1780       const SMDS_MeshNode* node = F->GetNode( i + n );
1781       p[n].SetCoord( node->X(), node->Y(), node->Z() );
1782     }
1783     normal += ( p[2] - p[1] ) ^ ( p[0] - p[1] );
1784   }
1785   double size2 = normal.SquareModulus();
1786   bool ok = ( size2 > numeric_limits<double>::min() * numeric_limits<double>::min());
1787   if ( normalized && ok )
1788     normal /= sqrt( size2 );
1789
1790   return ok;
1791 }
1792
1793 //=======================================================================
1794 //function : GetCommonNodes
1795 //purpose  : Return nodes common to two elements
1796 //=======================================================================
1797
1798 vector< const SMDS_MeshNode*> SMESH_MeshAlgos::GetCommonNodes(const SMDS_MeshElement* e1,
1799                                                               const SMDS_MeshElement* e2)
1800 {
1801   vector< const SMDS_MeshNode*> common;
1802   for ( int i = 0 ; i < e1->NbNodes(); ++i )
1803     if ( e2->GetNodeIndex( e1->GetNode( i )) >= 0 )
1804       common.push_back( e1->GetNode( i ));
1805   return common;
1806 }
1807
1808 //=======================================================================
1809 /*!
1810  * \brief Return SMESH_NodeSearcher
1811  */
1812 //=======================================================================
1813
1814 SMESH_NodeSearcher* SMESH_MeshAlgos::GetNodeSearcher(SMDS_Mesh& mesh)
1815 {
1816   return new SMESH_NodeSearcherImpl( &mesh );
1817 }
1818
1819 //=======================================================================
1820 /*!
1821  * \brief Return SMESH_NodeSearcher
1822  */
1823 //=======================================================================
1824
1825 SMESH_NodeSearcher* SMESH_MeshAlgos::GetNodeSearcher(SMDS_ElemIteratorPtr elemIt)
1826 {
1827   return new SMESH_NodeSearcherImpl( 0, elemIt );
1828 }
1829
1830 //=======================================================================
1831 /*!
1832  * \brief Return SMESH_ElementSearcher
1833  */
1834 //=======================================================================
1835
1836 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh& mesh,
1837                                                            double     tolerance)
1838 {
1839   return new SMESH_ElementSearcherImpl( mesh, tolerance );
1840 }
1841
1842 //=======================================================================
1843 /*!
1844  * \brief Return SMESH_ElementSearcher acting on a sub-set of elements
1845  */
1846 //=======================================================================
1847
1848 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh&           mesh,
1849                                                            SMDS_ElemIteratorPtr elemIt,
1850                                                            double               tolerance)
1851 {
1852   return new SMESH_ElementSearcherImpl( mesh, tolerance, elemIt );
1853 }