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