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