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