1 // Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : SMESH_MeshAlgos.hxx
23 // Created : Tue Apr 30 18:00:36 2013
24 // Author : Edward AGAPOV (eap)
26 // This file holds some low level algorithms extracted from SMESH_MeshEditor
27 // to make them accessible from Controls package
29 #include "SMESH_MeshAlgos.hxx"
31 #include "SMDS_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"
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>
51 //=======================================================================
53 * \brief Implementation of search for the node closest to point
55 //=======================================================================
57 struct SMESH_NodeSearcherImpl: public SMESH_NodeSearcher
59 //---------------------------------------------------------------------
63 SMESH_NodeSearcherImpl( const SMDS_Mesh* theMesh = 0,
64 SMDS_ElemIteratorPtr theElemIt = SMDS_ElemIteratorPtr() )
66 myMesh = ( SMDS_Mesh* ) theMesh;
68 TIDSortedNodeSet nodes;
70 SMDS_NodeIteratorPtr nIt = theMesh->nodesIterator(/*idInceasingOrder=*/true);
72 nodes.insert( nodes.end(), nIt->next() );
76 while ( theElemIt->more() )
78 const SMDS_MeshElement* e = theElemIt->next();
79 nodes.insert( e->begin_nodes(), e->end_nodes() );
82 myOctreeNode = new SMESH_OctreeNode(nodes) ;
84 // get max size of a leaf box
85 SMESH_OctreeNode* tree = myOctreeNode;
86 while ( !tree->isLeaf() )
88 SMESH_OctreeNodeIteratorPtr cIt = tree->GetChildrenIterator();
92 myHalfLeafSize = tree->maxSize() / 2.;
95 //---------------------------------------------------------------------
97 * \brief Move node and update myOctreeNode accordingly
99 void MoveNode( const SMDS_MeshNode* node, const gp_Pnt& toPnt )
101 myOctreeNode->UpdateByMoveNode( node, toPnt );
102 myMesh->MoveNode( node, toPnt.X(), toPnt.Y(), toPnt.Z() );
105 //---------------------------------------------------------------------
109 const SMDS_MeshNode* FindClosestTo( const gp_Pnt& thePnt )
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 );
118 double minSqDist = DBL_MAX;
119 if ( nodes.empty() ) // get all nodes of OctreeNode's closest to thePnt
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 );
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)
132 SMESH_OctreeNode* tree = *trIt;
133 if ( !tree->isLeaf() ) // put children to the queue
135 if ( pointInside && !tree->isInside( pointNode, myHalfLeafSize )) continue;
136 SMESH_OctreeNodeIteratorPtr cIt = tree->GetChildrenIterator();
137 while ( cIt->more() )
138 treeList.push_back( cIt->next() );
140 else if ( tree->NbNodes() ) // put a tree to the treeMap
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 ));
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;
158 // get all nodes from trees
159 for ( ; sqDist_tree != treeMap.end(); ++sqDist_tree) {
160 if ( sqDist_tree->first > sqLimit )
162 SMESH_OctreeNode* tree = sqDist_tree->second;
163 tree->NodesAround( tree->GetNodeIterator()->next(), &nodes );
166 // find closest among nodes
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 ) {
180 //---------------------------------------------------------------------
182 * \brief Finds nodes located within a tolerance near a point
184 int FindNearPoint(const gp_Pnt& point,
185 const double tolerance,
186 std::vector< const SMDS_MeshNode* >& foundNodes)
188 myOctreeNode->NodesAround( point.Coord(), foundNodes, tolerance );
189 return foundNodes.size();
192 //---------------------------------------------------------------------
196 ~SMESH_NodeSearcherImpl() { delete myOctreeNode; }
198 //---------------------------------------------------------------------
200 * \brief Return the node tree
202 const SMESH_OctreeNode* getTree() const { return myOctreeNode; }
205 SMESH_OctreeNode* myOctreeNode;
207 double myHalfLeafSize; // max size of a leaf box
210 // ========================================================================
211 namespace // Utils used in SMESH_ElementSearcherImpl::FindElementsByPoint()
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
217 //=======================================================================
219 * \brief Octal tree of bounding boxes of elements
221 //=======================================================================
223 class ElementBndBoxTree : public SMESH_Octree
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();
239 ElementBndBoxTree():_size(0) {}
240 SMESH_Octree* newChild() const { return new ElementBndBoxTree; }
241 void buildChildrenData();
242 Bnd_B3d* buildRootBox();
244 //!< Bounding box of element
245 struct ElementBox : public Bnd_B3d
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);
251 vector< ElementBox* > _elements;
255 //================================================================================
257 * \brief ElementBndBoxTree creation
259 //================================================================================
261 ElementBndBoxTree::ElementBndBoxTree(const SMDS_Mesh& mesh, SMDSAbs_ElementType elemType, SMDS_ElemIteratorPtr theElemIt, double tolerance)
262 :SMESH_Octree( new SMESH_TreeLimit( MaxLevel, /*minSize=*/0. ))
264 int nbElems = mesh.GetMeshInfo().NbElements( elemType );
265 _elements.reserve( nbElems );
267 SMDS_ElemIteratorPtr elemIt = theElemIt ? theElemIt : mesh.elementsIterator( elemType );
268 while ( elemIt->more() )
269 _elements.push_back( new ElementBox( elemIt->next(),tolerance ));
274 //================================================================================
278 //================================================================================
280 ElementBndBoxTree::~ElementBndBoxTree()
282 for ( size_t i = 0; i < _elements.size(); ++i )
283 if ( --_elements[i]->_refCount <= 0 )
287 //================================================================================
289 * \brief Return the maximal box
291 //================================================================================
293 Bnd_B3d* ElementBndBoxTree::buildRootBox()
295 Bnd_B3d* box = new Bnd_B3d;
296 for ( size_t i = 0; i < _elements.size(); ++i )
297 box->Add( *_elements[i] );
301 //================================================================================
303 * \brief Redistrubute element boxes among children
305 //================================================================================
307 void ElementBndBoxTree::buildChildrenData()
309 for ( size_t i = 0; i < _elements.size(); ++i )
311 for (int j = 0; j < 8; j++)
313 if ( !_elements[i]->IsOut( *myChildren[j]->getBox() ))
315 _elements[i]->_refCount++;
316 ((ElementBndBoxTree*)myChildren[j])->_elements.push_back( _elements[i]);
319 _elements[i]->_refCount--;
321 _size = _elements.size();
322 SMESHUtils::FreeVector( _elements ); // = _elements.clear() + free memory
324 for (int j = 0; j < 8; j++)
326 ElementBndBoxTree* child = static_cast<ElementBndBoxTree*>( myChildren[j]);
327 if ((int) child->_elements.size() <= MaxNbElemsInLeaf )
328 child->myIsLeaf = true;
330 if ( child->_elements.capacity() - child->_elements.size() > 1000 )
331 SMESHUtils::CompactVector( child->_elements );
335 //================================================================================
337 * \brief Return elements which can include the point
339 //================================================================================
341 void ElementBndBoxTree::getElementsNearPoint( const gp_Pnt& point,
342 TIDSortedElemSet& foundElems)
344 if ( getBox()->IsOut( point.XYZ() ))
349 for ( size_t i = 0; i < _elements.size(); ++i )
350 if ( !_elements[i]->IsOut( point.XYZ() ))
351 foundElems.insert( _elements[i]->_element );
355 for (int i = 0; i < 8; i++)
356 ((ElementBndBoxTree*) myChildren[i])->getElementsNearPoint( point, foundElems );
360 //================================================================================
362 * \brief Return elements which can be intersected by the line
364 //================================================================================
366 void ElementBndBoxTree::getElementsNearLine( const gp_Ax1& line,
367 TIDSortedElemSet& foundElems)
369 if ( getBox()->IsOut( line ))
374 for ( size_t i = 0; i < _elements.size(); ++i )
375 if ( !_elements[i]->IsOut( line ))
376 foundElems.insert( _elements[i]->_element );
380 for (int i = 0; i < 8; i++)
381 ((ElementBndBoxTree*) myChildren[i])->getElementsNearLine( line, foundElems );
385 //================================================================================
387 * \brief Return elements from leaves intersecting the sphere
389 //================================================================================
391 void ElementBndBoxTree::getElementsInSphere ( const gp_XYZ& center,
393 TIDSortedElemSet& foundElems)
395 if ( getBox()->IsOut( center, radius ))
400 for ( size_t i = 0; i < _elements.size(); ++i )
401 if ( !_elements[i]->IsOut( center, radius ))
402 foundElems.insert( _elements[i]->_element );
406 for (int i = 0; i < 8; i++)
407 ((ElementBndBoxTree*) myChildren[i])->getElementsInSphere( center, radius, foundElems );
411 //================================================================================
413 * \brief Construct the element box
415 //================================================================================
417 ElementBndBoxTree::ElementBox::ElementBox(const SMDS_MeshElement* elem, double tolerance)
421 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
422 while ( nIt->more() )
423 Add( SMESH_TNodeXYZ( nIt->next() ));
424 Enlarge( tolerance );
429 //=======================================================================
431 * \brief Implementation of search for the elements by point and
432 * of classification of point in 2D mesh
434 //=======================================================================
436 SMESH_ElementSearcher::~SMESH_ElementSearcher()
440 struct SMESH_ElementSearcherImpl: public SMESH_ElementSearcher
443 SMDS_ElemIteratorPtr _meshPartIt;
444 ElementBndBoxTree* _ebbTree;
445 SMESH_NodeSearcherImpl* _nodeSearcher;
446 SMDSAbs_ElementType _elementType;
448 bool _outerFacesFound;
449 set<const SMDS_MeshElement*> _outerFaces; // empty means "no internal faces at all"
451 SMESH_ElementSearcherImpl( SMDS_Mesh& mesh,
453 SMDS_ElemIteratorPtr elemIt=SMDS_ElemIteratorPtr())
454 : _mesh(&mesh),_meshPartIt(elemIt),_ebbTree(0),_nodeSearcher(0),_tolerance(tol),_outerFacesFound(false) {}
455 virtual ~SMESH_ElementSearcherImpl()
457 if ( _ebbTree ) delete _ebbTree; _ebbTree = 0;
458 if ( _nodeSearcher ) delete _nodeSearcher; _nodeSearcher = 0;
460 virtual int FindElementsByPoint(const gp_Pnt& point,
461 SMDSAbs_ElementType type,
462 vector< const SMDS_MeshElement* >& foundElements);
463 virtual TopAbs_State GetPointState(const gp_Pnt& point);
464 virtual const SMDS_MeshElement* FindClosestTo( const gp_Pnt& point,
465 SMDSAbs_ElementType type );
467 void GetElementsNearLine( const gp_Ax1& line,
468 SMDSAbs_ElementType type,
469 vector< const SMDS_MeshElement* >& foundElems);
470 void GetElementsInSphere( const gp_XYZ& center,
472 SMDSAbs_ElementType type,
473 vector< const SMDS_MeshElement* >& foundElems);
474 double getTolerance();
475 bool getIntersParamOnLine(const gp_Lin& line, const SMDS_MeshElement* face,
476 const double tolerance, double & param);
477 void findOuterBoundary(const SMDS_MeshElement* anyOuterFace);
478 bool isOuterBoundary(const SMDS_MeshElement* face) const
480 return _outerFaces.empty() || _outerFaces.count(face);
483 struct TInters //!< data of intersection of the line and the mesh face (used in GetPointState())
485 const SMDS_MeshElement* _face;
487 bool _coincides; //!< the line lays in face plane
488 TInters(const SMDS_MeshElement* face, const gp_Vec& faceNorm, bool coinc=false)
489 : _face(face), _faceNorm( faceNorm ), _coincides( coinc ) {}
491 struct TFaceLink //!< link and faces sharing it (used in findOuterBoundary())
494 TIDSortedElemSet _faces;
495 TFaceLink( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshElement* face)
496 : _link( n1, n2 ), _faces( &face, &face + 1) {}
500 ostream& operator<< (ostream& out, const SMESH_ElementSearcherImpl::TInters& i)
502 return out << "TInters(face=" << ( i._face ? i._face->GetID() : 0)
503 << ", _coincides="<<i._coincides << ")";
506 //=======================================================================
508 * \brief define tolerance for search
510 //=======================================================================
512 double SMESH_ElementSearcherImpl::getTolerance()
514 if ( _tolerance < 0 )
516 const SMDS_MeshInfo& meshInfo = _mesh->GetMeshInfo();
519 if ( _nodeSearcher && meshInfo.NbNodes() > 1 )
521 double boxSize = _nodeSearcher->getTree()->maxSize();
522 _tolerance = 1e-8 * boxSize/* / meshInfo.NbNodes()*/;
524 else if ( _ebbTree && meshInfo.NbElements() > 0 )
526 double boxSize = _ebbTree->maxSize();
527 _tolerance = 1e-8 * boxSize/* / meshInfo.NbElements()*/;
529 if ( _tolerance == 0 )
531 // define tolerance by size of a most complex element
532 int complexType = SMDSAbs_Volume;
533 while ( complexType > SMDSAbs_All &&
534 meshInfo.NbElements( SMDSAbs_ElementType( complexType )) < 1 )
536 if ( complexType == SMDSAbs_All ) return 0; // empty mesh
538 if ( complexType == int( SMDSAbs_Node ))
540 SMDS_NodeIteratorPtr nodeIt = _mesh->nodesIterator();
542 if ( meshInfo.NbNodes() > 2 )
543 elemSize = SMESH_TNodeXYZ( nodeIt->next() ).Distance( nodeIt->next() );
547 SMDS_ElemIteratorPtr elemIt =
548 _mesh->elementsIterator( SMDSAbs_ElementType( complexType ));
549 const SMDS_MeshElement* elem = elemIt->next();
550 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
551 SMESH_TNodeXYZ n1( nodeIt->next() );
553 while ( nodeIt->more() )
555 double dist = n1.Distance( static_cast<const SMDS_MeshNode*>( nodeIt->next() ));
556 elemSize = max( dist, elemSize );
559 _tolerance = 1e-4 * elemSize;
565 //================================================================================
567 * \brief Find intersection of the line and an edge of face and return parameter on line
569 //================================================================================
571 bool SMESH_ElementSearcherImpl::getIntersParamOnLine(const gp_Lin& line,
572 const SMDS_MeshElement* face,
579 GeomAPI_ExtremaCurveCurve anExtCC;
580 Handle(Geom_Curve) lineCurve = new Geom_Line( line );
582 int nbNodes = face->IsQuadratic() ? face->NbNodes()/2 : face->NbNodes();
583 for ( int i = 0; i < nbNodes && nbInts < 2; ++i )
585 GC_MakeSegment edge( SMESH_TNodeXYZ( face->GetNode( i )),
586 SMESH_TNodeXYZ( face->GetNode( (i+1)%nbNodes) ));
587 anExtCC.Init( lineCurve, edge.Value() );
588 if ( anExtCC.NbExtrema() > 0 && anExtCC.LowerDistance() <= tol)
590 Quantity_Parameter pl, pe;
591 anExtCC.LowerDistanceParameters( pl, pe );
597 if ( nbInts > 0 ) param /= nbInts;
600 //================================================================================
602 * \brief Find all faces belonging to the outer boundary of mesh
604 //================================================================================
606 void SMESH_ElementSearcherImpl::findOuterBoundary(const SMDS_MeshElement* outerFace)
608 if ( _outerFacesFound ) return;
610 // Collect all outer faces by passing from one outer face to another via their links
611 // and BTW find out if there are internal faces at all.
613 // checked links and links where outer boundary meets internal one
614 set< SMESH_TLink > visitedLinks, seamLinks;
616 // links to treat with already visited faces sharing them
617 list < TFaceLink > startLinks;
619 // load startLinks with the first outerFace
620 startLinks.push_back( TFaceLink( outerFace->GetNode(0), outerFace->GetNode(1), outerFace));
621 _outerFaces.insert( outerFace );
623 TIDSortedElemSet emptySet;
624 while ( !startLinks.empty() )
626 const SMESH_TLink& link = startLinks.front()._link;
627 TIDSortedElemSet& faces = startLinks.front()._faces;
629 outerFace = *faces.begin();
630 // find other faces sharing the link
631 const SMDS_MeshElement* f;
632 while (( f = SMESH_MeshAlgos::FindFaceInSet(link.node1(), link.node2(), emptySet, faces )))
635 // select another outer face among the found
636 const SMDS_MeshElement* outerFace2 = 0;
637 if ( faces.size() == 2 )
639 outerFace2 = (outerFace == *faces.begin() ? *faces.rbegin() : *faces.begin());
641 else if ( faces.size() > 2 )
643 seamLinks.insert( link );
645 // link direction within the outerFace
646 gp_Vec n1n2( SMESH_TNodeXYZ( link.node1()),
647 SMESH_TNodeXYZ( link.node2()));
648 int i1 = outerFace->GetNodeIndex( link.node1() );
649 int i2 = outerFace->GetNodeIndex( link.node2() );
650 bool rev = ( abs(i2-i1) == 1 ? i1 > i2 : i2 > i1 );
651 if ( rev ) n1n2.Reverse();
653 gp_XYZ ofNorm, fNorm;
654 if ( SMESH_MeshAlgos::FaceNormal( outerFace, ofNorm, /*normalized=*/false ))
656 // direction from the link inside outerFace
657 gp_Vec dirInOF = gp_Vec( ofNorm ) ^ n1n2;
658 // sort all other faces by angle with the dirInOF
659 map< double, const SMDS_MeshElement* > angle2Face;
660 set< const SMDS_MeshElement*, TIDCompare >::const_iterator face = faces.begin();
661 for ( ; face != faces.end(); ++face )
663 if ( *face == outerFace ) continue;
664 if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false ))
666 gp_Vec dirInF = gp_Vec( fNorm ) ^ n1n2;
667 double angle = dirInOF.AngleWithRef( dirInF, n1n2 );
668 if ( angle < 0 ) angle += 2. * M_PI;
669 angle2Face.insert( make_pair( angle, *face ));
671 if ( !angle2Face.empty() )
672 outerFace2 = angle2Face.begin()->second;
675 // store the found outer face and add its links to continue seaching from
678 _outerFaces.insert( outerFace2 );
679 int nbNodes = outerFace2->NbCornerNodes();
680 for ( int i = 0; i < nbNodes; ++i )
682 SMESH_TLink link2( outerFace2->GetNode(i), outerFace2->GetNode((i+1)%nbNodes));
683 if ( visitedLinks.insert( link2 ).second )
684 startLinks.push_back( TFaceLink( link2.node1(), link2.node2(), outerFace2 ));
687 startLinks.pop_front();
689 _outerFacesFound = true;
691 if ( !seamLinks.empty() )
693 // There are internal boundaries touching the outher one,
694 // find all faces of internal boundaries in order to find
695 // faces of boundaries of holes, if any.
704 //=======================================================================
706 * \brief Find elements of given type where the given point is IN or ON.
707 * Returns nb of found elements and elements them-selves.
709 * 'ALL' type means elements of any type excluding nodes, balls and 0D elements
711 //=======================================================================
713 int SMESH_ElementSearcherImpl::
714 FindElementsByPoint(const gp_Pnt& point,
715 SMDSAbs_ElementType type,
716 vector< const SMDS_MeshElement* >& foundElements)
718 foundElements.clear();
720 double tolerance = getTolerance();
722 // =================================================================================
723 if ( type == SMDSAbs_Node || type == SMDSAbs_0DElement || type == SMDSAbs_Ball)
725 if ( !_nodeSearcher )
728 _nodeSearcher = new SMESH_NodeSearcherImpl( 0, _meshPartIt );
730 _nodeSearcher = new SMESH_NodeSearcherImpl( _mesh );
732 std::vector< const SMDS_MeshNode* > foundNodes;
733 _nodeSearcher->FindNearPoint( point, tolerance, foundNodes );
735 if ( type == SMDSAbs_Node )
737 foundElements.assign( foundNodes.begin(), foundNodes.end() );
741 for ( size_t i = 0; i < foundNodes.size(); ++i )
743 SMDS_ElemIteratorPtr elemIt = foundNodes[i]->GetInverseElementIterator( type );
744 while ( elemIt->more() )
745 foundElements.push_back( elemIt->next() );
749 // =================================================================================
750 else // elements more complex than 0D
752 if ( !_ebbTree || _elementType != type )
754 if ( _ebbTree ) delete _ebbTree;
755 _ebbTree = new ElementBndBoxTree( *_mesh, _elementType = type, _meshPartIt, tolerance );
757 TIDSortedElemSet suspectElems;
758 _ebbTree->getElementsNearPoint( point, suspectElems );
759 TIDSortedElemSet::iterator elem = suspectElems.begin();
760 for ( ; elem != suspectElems.end(); ++elem )
761 if ( !SMESH_MeshAlgos::IsOut( *elem, point, tolerance ))
762 foundElements.push_back( *elem );
764 return foundElements.size();
767 //=======================================================================
769 * \brief Find an element of given type most close to the given point
771 * WARNING: Only face search is implemeneted so far
773 //=======================================================================
775 const SMDS_MeshElement*
776 SMESH_ElementSearcherImpl::FindClosestTo( const gp_Pnt& point,
777 SMDSAbs_ElementType type )
779 const SMDS_MeshElement* closestElem = 0;
781 if ( type == SMDSAbs_Face || type == SMDSAbs_Volume )
783 if ( !_ebbTree || _elementType != type )
785 if ( _ebbTree ) delete _ebbTree;
786 _ebbTree = new ElementBndBoxTree( *_mesh, _elementType = type, _meshPartIt );
788 TIDSortedElemSet suspectElems;
789 _ebbTree->getElementsNearPoint( point, suspectElems );
791 if ( suspectElems.empty() && _ebbTree->maxSize() > 0 )
793 gp_Pnt boxCenter = 0.5 * ( _ebbTree->getBox()->CornerMin() +
794 _ebbTree->getBox()->CornerMax() );
796 if ( _ebbTree->getBox()->IsOut( point.XYZ() ))
797 radius = point.Distance( boxCenter ) - 0.5 * _ebbTree->maxSize();
799 radius = _ebbTree->maxSize() / pow( 2., _ebbTree->getHeight()) / 2;
800 while ( suspectElems.empty() )
802 _ebbTree->getElementsInSphere( point.XYZ(), radius, suspectElems );
806 double minDist = std::numeric_limits<double>::max();
807 multimap< double, const SMDS_MeshElement* > dist2face;
808 TIDSortedElemSet::iterator elem = suspectElems.begin();
809 for ( ; elem != suspectElems.end(); ++elem )
811 double dist = SMESH_MeshAlgos::GetDistance( *elem, point );
812 if ( dist < minDist + 1e-10)
815 dist2face.insert( dist2face.begin(), make_pair( dist, *elem ));
818 if ( !dist2face.empty() )
820 multimap< double, const SMDS_MeshElement* >::iterator d2f = dist2face.begin();
821 closestElem = d2f->second;
822 // if there are several elements at the same distance, select one
823 // with GC closest to the point
824 typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
825 double minDistToGC = 0;
826 for ( ++d2f; d2f != dist2face.end() && fabs( d2f->first - minDist ) < 1e-10; ++d2f )
828 if ( minDistToGC == 0 )
831 gc = accumulate( TXyzIterator(closestElem->nodesIterator()),
832 TXyzIterator(), gc ) / closestElem->NbNodes();
833 minDistToGC = point.SquareDistance( gc );
836 gc = accumulate( TXyzIterator( d2f->second->nodesIterator()),
837 TXyzIterator(), gc ) / d2f->second->NbNodes();
838 double d = point.SquareDistance( gc );
839 if ( d < minDistToGC )
842 closestElem = d2f->second;
845 // cout << "FindClosestTo( " <<point.X()<<", "<<point.Y()<<", "<<point.Z()<<" ) FACE "
846 // <<closestElem->GetID() << " DIST " << minDist << endl;
851 // NOT IMPLEMENTED SO FAR
857 //================================================================================
859 * \brief Classify the given point in the closed 2D mesh
861 //================================================================================
863 TopAbs_State SMESH_ElementSearcherImpl::GetPointState(const gp_Pnt& point)
865 double tolerance = getTolerance();
866 if ( !_ebbTree || _elementType != SMDSAbs_Face )
868 if ( _ebbTree ) delete _ebbTree;
869 _ebbTree = new ElementBndBoxTree( *_mesh, _elementType = SMDSAbs_Face, _meshPartIt );
871 // Algo: analyse transition of a line starting at the point through mesh boundary;
872 // try three lines parallel to axis of the coordinate system and perform rough
873 // analysis. If solution is not clear perform thorough analysis.
875 const int nbAxes = 3;
876 gp_Dir axisDir[ nbAxes ] = { gp::DX(), gp::DY(), gp::DZ() };
877 map< double, TInters > paramOnLine2TInters[ nbAxes ];
878 list< TInters > tangentInters[ nbAxes ]; // of faces whose plane includes the line
879 multimap< int, int > nbInt2Axis; // to find the simplest case
880 for ( int axis = 0; axis < nbAxes; ++axis )
882 gp_Ax1 lineAxis( point, axisDir[axis]);
883 gp_Lin line ( lineAxis );
885 TIDSortedElemSet suspectFaces; // faces possibly intersecting the line
886 _ebbTree->getElementsNearLine( lineAxis, suspectFaces );
888 // Intersect faces with the line
890 map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
891 TIDSortedElemSet::iterator face = suspectFaces.begin();
892 for ( ; face != suspectFaces.end(); ++face )
896 if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false)) continue;
897 gp_Pln facePlane( SMESH_TNodeXYZ( (*face)->GetNode(0)), fNorm );
899 // perform intersection
900 IntAna_IntConicQuad intersection( line, IntAna_Quadric( facePlane ));
901 if ( !intersection.IsDone() )
903 if ( intersection.IsInQuadric() )
905 tangentInters[ axis ].push_back( TInters( *face, fNorm, true ));
907 else if ( ! intersection.IsParallel() && intersection.NbPoints() > 0 )
909 double tol = 1e-4 * Sqrt( fNorm.Modulus() );
910 gp_Pnt intersectionPoint = intersection.Point(1);
911 if ( !SMESH_MeshAlgos::IsOut( *face, intersectionPoint, tol ))
912 u2inters.insert(make_pair( intersection.ParamOnConic(1), TInters( *face, fNorm )));
915 // Analyse intersections roughly
917 int nbInter = u2inters.size();
921 double f = u2inters.begin()->first, l = u2inters.rbegin()->first;
922 if ( nbInter == 1 ) // not closed mesh
923 return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
925 if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
928 if ( (f<0) == (l<0) )
931 int nbIntBeforePoint = std::distance( u2inters.begin(), u2inters.lower_bound(0));
932 int nbIntAfterPoint = nbInter - nbIntBeforePoint;
933 if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
936 nbInt2Axis.insert( make_pair( min( nbIntBeforePoint, nbIntAfterPoint ), axis ));
938 if ( _outerFacesFound ) break; // pass to thorough analysis
940 } // three attempts - loop on CS axes
942 // Analyse intersections thoroughly.
943 // We make two loops maximum, on the first one we only exclude touching intersections,
944 // on the second, if situation is still unclear, we gather and use information on
945 // position of faces (internal or outer). If faces position is already gathered,
946 // we make the second loop right away.
948 for ( int hasPositionInfo = _outerFacesFound; hasPositionInfo < 2; ++hasPositionInfo )
950 multimap< int, int >::const_iterator nb_axis = nbInt2Axis.begin();
951 for ( ; nb_axis != nbInt2Axis.end(); ++nb_axis )
953 int axis = nb_axis->second;
954 map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
956 gp_Ax1 lineAxis( point, axisDir[axis]);
957 gp_Lin line ( lineAxis );
959 // add tangent intersections to u2inters
961 list< TInters >::const_iterator tgtInt = tangentInters[ axis ].begin();
962 for ( ; tgtInt != tangentInters[ axis ].end(); ++tgtInt )
963 if ( getIntersParamOnLine( line, tgtInt->_face, tolerance, param ))
964 u2inters.insert(make_pair( param, *tgtInt ));
965 tangentInters[ axis ].clear();
967 // Count intersections before and after the point excluding touching ones.
968 // If hasPositionInfo we count intersections of outer boundary only
970 int nbIntBeforePoint = 0, nbIntAfterPoint = 0;
971 double f = numeric_limits<double>::max(), l = -numeric_limits<double>::max();
972 map< double, TInters >::iterator u_int1 = u2inters.begin(), u_int2 = u_int1;
973 bool ok = ! u_int1->second._coincides;
974 while ( ok && u_int1 != u2inters.end() )
976 double u = u_int1->first;
977 bool touchingInt = false;
978 if ( ++u_int2 != u2inters.end() )
980 // skip intersections at the same point (if the line passes through edge or node)
982 while ( u_int2 != u2inters.end() && fabs( u_int2->first - u ) < tolerance )
988 // skip tangent intersections
990 if ( u_int2 != u2inters.end() )
992 const SMDS_MeshElement* prevFace = u_int1->second._face;
993 while ( ok && u_int2->second._coincides )
995 if ( SMESH_MeshAlgos::GetCommonNodes(prevFace , u_int2->second._face).empty() )
1001 ok = ( u_int2 != u2inters.end() );
1007 // skip intersections at the same point after tangent intersections
1010 double u2 = u_int2->first;
1012 while ( u_int2 != u2inters.end() && fabs( u_int2->first - u2 ) < tolerance )
1018 // decide if we skipped a touching intersection
1019 if ( nbSamePnt + nbTgt > 0 )
1021 double minDot = numeric_limits<double>::max(), maxDot = -numeric_limits<double>::max();
1022 map< double, TInters >::iterator u_int = u_int1;
1023 for ( ; u_int != u_int2; ++u_int )
1025 if ( u_int->second._coincides ) continue;
1026 double dot = u_int->second._faceNorm * line.Direction();
1027 if ( dot > maxDot ) maxDot = dot;
1028 if ( dot < minDot ) minDot = dot;
1030 touchingInt = ( minDot*maxDot < 0 );
1035 if ( !hasPositionInfo || isOuterBoundary( u_int1->second._face ))
1046 u_int1 = u_int2; // to next intersection
1048 } // loop on intersections with one line
1052 if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
1055 if ( nbIntBeforePoint == 0 || nbIntAfterPoint == 0)
1058 if ( nbIntBeforePoint + nbIntAfterPoint == 1 ) // not closed mesh
1059 return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
1061 if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
1064 if ( (f<0) == (l<0) )
1067 if ( hasPositionInfo )
1068 return nbIntBeforePoint % 2 ? TopAbs_IN : TopAbs_OUT;
1070 } // loop on intersections of the tree lines - thorough analysis
1072 if ( !hasPositionInfo )
1074 // gather info on faces position - is face in the outer boundary or not
1075 map< double, TInters > & u2inters = paramOnLine2TInters[ 0 ];
1076 findOuterBoundary( u2inters.begin()->second._face );
1079 } // two attempts - with and w/o faces position info in the mesh
1081 return TopAbs_UNKNOWN;
1084 //=======================================================================
1086 * \brief Return elements possibly intersecting the line
1088 //=======================================================================
1090 void SMESH_ElementSearcherImpl::GetElementsNearLine( const gp_Ax1& line,
1091 SMDSAbs_ElementType type,
1092 vector< const SMDS_MeshElement* >& foundElems)
1094 if ( !_ebbTree || _elementType != type )
1096 if ( _ebbTree ) delete _ebbTree;
1097 _ebbTree = new ElementBndBoxTree( *_mesh, _elementType = type, _meshPartIt );
1099 TIDSortedElemSet suspectFaces; // elements possibly intersecting the line
1100 _ebbTree->getElementsNearLine( line, suspectFaces );
1101 foundElems.assign( suspectFaces.begin(), suspectFaces.end());
1104 //=======================================================================
1106 * Return elements whose bounding box intersects a sphere
1108 //=======================================================================
1110 void SMESH_ElementSearcherImpl::GetElementsInSphere( const gp_XYZ& center,
1111 const double radius,
1112 SMDSAbs_ElementType type,
1113 vector< const SMDS_MeshElement* >& foundElems)
1115 if ( !_ebbTree || _elementType != type )
1117 if ( _ebbTree ) delete _ebbTree;
1118 _ebbTree = new ElementBndBoxTree( *_mesh, _elementType = type, _meshPartIt );
1120 TIDSortedElemSet suspectFaces; // elements possibly intersecting the line
1121 _ebbTree->getElementsInSphere( center, radius, suspectFaces );
1122 foundElems.assign( suspectFaces.begin(), suspectFaces.end() );
1125 //=======================================================================
1127 * \brief Return true if the point is IN or ON of the element
1129 //=======================================================================
1131 bool SMESH_MeshAlgos::IsOut( const SMDS_MeshElement* element, const gp_Pnt& point, double tol )
1133 if ( element->GetType() == SMDSAbs_Volume)
1135 return SMDS_VolumeTool( element ).IsOut( point.X(), point.Y(), point.Z(), tol );
1138 // get ordered nodes
1140 vector< SMESH_TNodeXYZ > xyz; xyz.reserve( element->NbNodes()+1 );
1142 SMDS_ElemIteratorPtr nodeIt = element->interlacedNodesElemIterator();
1143 for ( int i = 0; nodeIt->more(); ++i )
1144 xyz.push_back( SMESH_TNodeXYZ( nodeIt->next() ));
1146 int i, nbNodes = (int) xyz.size(); // central node of biquadratic is missing
1148 if ( element->GetType() == SMDSAbs_Face ) // --------------------------------------------------
1150 // compute face normal
1151 gp_Vec faceNorm(0,0,0);
1152 xyz.push_back( xyz.front() );
1153 for ( i = 0; i < nbNodes; ++i )
1155 gp_Vec edge1( xyz[i+1], xyz[i]);
1156 gp_Vec edge2( xyz[i+1], xyz[(i+2)%nbNodes] );
1157 faceNorm += edge1 ^ edge2;
1159 double normSize = faceNorm.Magnitude();
1160 if ( normSize <= tol )
1162 // degenerated face: point is out if it is out of all face edges
1163 for ( i = 0; i < nbNodes; ++i )
1165 SMDS_LinearEdge edge( xyz[i]._node, xyz[i+1]._node );
1166 if ( !IsOut( &edge, point, tol ))
1171 faceNorm /= normSize;
1173 // check if the point lays on face plane
1174 gp_Vec n2p( xyz[0], point );
1175 double dot = n2p * faceNorm;
1176 if ( Abs( dot ) > tol ) // not on face plane
1179 if ( nbNodes > 3 ) // maybe the face is not planar
1181 double elemThick = 0;
1182 for ( i = 1; i < nbNodes; ++i )
1184 gp_Vec n2n( xyz[0], xyz[i] );
1185 elemThick = Max( elemThick, Abs( n2n * faceNorm ));
1187 isOut = Abs( dot ) > elemThick + tol;
1193 // check if point is out of face boundary:
1194 // define it by closest transition of a ray point->infinity through face boundary
1195 // on the face plane.
1196 // First, find normal of a plane perpendicular to face plane, to be used as a cutting tool
1197 // to find intersections of the ray with the boundary.
1199 gp_Vec plnNorm = ray ^ faceNorm;
1200 normSize = plnNorm.Magnitude();
1201 if ( normSize <= tol ) return false; // point coincides with the first node
1202 plnNorm /= normSize;
1203 // for each node of the face, compute its signed distance to the cutting plane
1204 vector<double> dist( nbNodes + 1);
1205 for ( i = 0; i < nbNodes; ++i )
1207 gp_Vec n2p( xyz[i], point );
1208 dist[i] = n2p * plnNorm;
1210 dist.back() = dist.front();
1211 // find the closest intersection
1213 double rClosest = 0, distClosest = 1e100;
1215 for ( i = 0; i < nbNodes; ++i )
1218 if ( fabs( dist[i] ) < tol )
1220 else if ( fabs( dist[i+1]) < tol )
1222 else if ( dist[i] * dist[i+1] < 0 )
1223 r = dist[i] / ( dist[i] - dist[i+1] );
1225 continue; // no intersection
1226 gp_Pnt pInt = xyz[i] * (1.-r) + xyz[i+1] * r;
1227 gp_Vec p2int( point, pInt);
1228 double intDist = p2int.SquareMagnitude();
1229 if ( intDist < distClosest )
1234 distClosest = intDist;
1238 return true; // no intesections - out
1240 // analyse transition
1241 gp_Vec edge( xyz[iClosest], xyz[iClosest+1] );
1242 gp_Vec edgeNorm = -( edge ^ faceNorm ); // normal to intersected edge pointing out of face
1243 gp_Vec p2int ( point, pClosest );
1244 bool out = (edgeNorm * p2int) < -tol;
1245 if ( rClosest > 0. && rClosest < 1. ) // not node intersection
1248 // ray pass through a face node; analyze transition through an adjacent edge
1249 gp_Pnt p1 = xyz[ (rClosest == 0.) ? ((iClosest+nbNodes-1) % nbNodes) : (iClosest+1) ];
1250 gp_Pnt p2 = xyz[ (rClosest == 0.) ? iClosest : ((iClosest+2) % nbNodes) ];
1251 gp_Vec edgeAdjacent( p1, p2 );
1252 gp_Vec edgeNorm2 = -( edgeAdjacent ^ faceNorm );
1253 bool out2 = (edgeNorm2 * p2int) < -tol;
1255 bool covexCorner = ( edgeNorm * edgeAdjacent * (rClosest==1. ? 1. : -1.)) < 0;
1256 return covexCorner ? (out || out2) : (out && out2);
1259 if ( element->GetType() == SMDSAbs_Edge ) // --------------------------------------------------
1261 // point is out of edge if it is NOT ON any straight part of edge
1262 // (we consider quadratic edge as being composed of two straight parts)
1263 for ( i = 1; i < nbNodes; ++i )
1265 gp_Vec edge( xyz[i-1], xyz[i] );
1266 gp_Vec n1p ( xyz[i-1], point );
1267 double u = ( edge * n1p ) / edge.SquareMagnitude(); // param [0,1] on the edge
1269 if ( n1p.SquareMagnitude() < tol * tol )
1274 if ( point.SquareDistance( xyz[i] ) < tol * tol )
1278 gp_XYZ proj = ( 1. - u ) * xyz[i-1] + u * xyz[i]; // projection of the point on the edge
1279 double dist2 = point.SquareDistance( proj );
1280 if ( dist2 > tol * tol )
1282 return false; // point is ON this part
1287 // Node or 0D element -------------------------------------------------------------------------
1289 gp_Vec n2p ( xyz[0], point );
1290 return n2p.SquareMagnitude() > tol * tol;
1295 //=======================================================================
1298 // Position of a point relative to a segment
1302 // VERTEX 1 o----ON-----> VERTEX 2
1306 enum PositionName { POS_LEFT = 1, POS_VERTEX = 2, POS_RIGHT = 4, //POS_ON = 8,
1307 POS_ALL = POS_LEFT | POS_RIGHT | POS_VERTEX };
1311 int _index; // index of vertex or segment
1313 PointPos( PositionName n, int i=-1 ): _name(n), _index(i) {}
1314 bool operator < (const PointPos& other ) const
1316 if ( _name == other._name )
1317 return ( _index < 0 || other._index < 0 ) ? false : _index < other._index;
1318 return _name < other._name;
1322 //================================================================================
1324 * \brief Return of a point relative to a segment
1325 * \param point2D - the point to analyze position of
1326 * \param xyVec - end points of segments
1327 * \param index0 - 0-based index of the first point of segment
1328 * \param posToFindOut - flags of positions to detect
1329 * \retval PointPos - point position
1331 //================================================================================
1333 PointPos getPointPosition( const gp_XY& point2D,
1334 const gp_XY* segEnds,
1335 const int index0 = 0,
1336 const int posToFindOut = POS_ALL)
1338 const gp_XY& p1 = segEnds[ index0 ];
1339 const gp_XY& p2 = segEnds[ index0+1 ];
1340 const gp_XY grad = p2 - p1;
1342 if ( posToFindOut & POS_VERTEX )
1344 // check if the point2D is at "vertex 1" zone
1345 gp_XY pp1[2] = { p1, gp_XY( p1.X() - grad.Y(),
1346 p1.Y() + grad.X() ) };
1347 if ( getPointPosition( point2D, pp1, 0, POS_LEFT|POS_RIGHT )._name == POS_LEFT )
1348 return PointPos( POS_VERTEX, index0 );
1350 // check if the point2D is at "vertex 2" zone
1351 gp_XY pp2[2] = { p2, gp_XY( p2.X() - grad.Y(),
1352 p2.Y() + grad.X() ) };
1353 if ( getPointPosition( point2D, pp2, 0, POS_LEFT|POS_RIGHT )._name == POS_RIGHT )
1354 return PointPos( POS_VERTEX, index0 + 1);
1356 double edgeEquation =
1357 ( point2D.X() - p1.X() ) * grad.Y() - ( point2D.Y() - p1.Y() ) * grad.X();
1358 return PointPos( edgeEquation < 0 ? POS_LEFT : POS_RIGHT, index0 );
1362 //=======================================================================
1364 * \brief Return minimal distance from a point to an element
1366 * Currently we ignore non-planarity and 2nd order of face
1368 //=======================================================================
1370 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshElement* elem,
1371 const gp_Pnt& point )
1373 switch ( elem->GetType() )
1375 case SMDSAbs_Volume:
1376 return GetDistance( dynamic_cast<const SMDS_MeshVolume*>( elem ), point);
1378 return GetDistance( dynamic_cast<const SMDS_MeshFace*>( elem ), point);
1380 return GetDistance( dynamic_cast<const SMDS_MeshEdge*>( elem ), point);
1382 return point.Distance( SMESH_TNodeXYZ( elem ));
1388 //=======================================================================
1390 * \brief Return minimal distance from a point to a face
1392 * Currently we ignore non-planarity and 2nd order of face
1394 //=======================================================================
1396 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshFace* face,
1397 const gp_Pnt& point )
1399 double badDistance = -1;
1400 if ( !face ) return badDistance;
1402 // coordinates of nodes (medium nodes, if any, ignored)
1403 typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
1404 vector<gp_XYZ> xyz( TXyzIterator( face->nodesIterator()), TXyzIterator() );
1405 xyz.resize( face->NbCornerNodes()+1 );
1407 // transformation to get xyz[0] lies on the origin, xyz[1] lies on the Z axis,
1408 // and xyz[2] lies in the XZ plane. This is to pass to 2D space on XZ plane.
1410 gp_Vec OZ ( xyz[0], xyz[1] );
1411 gp_Vec OX ( xyz[0], xyz[2] );
1412 if ( OZ.Magnitude() < std::numeric_limits<double>::min() )
1414 if ( xyz.size() < 4 ) return badDistance;
1415 OZ = gp_Vec ( xyz[0], xyz[2] );
1416 OX = gp_Vec ( xyz[0], xyz[3] );
1420 tgtCS = gp_Ax3( xyz[0], OZ, OX );
1422 catch ( Standard_Failure ) {
1425 trsf.SetTransformation( tgtCS );
1427 // move all the nodes to 2D
1428 vector<gp_XY> xy( xyz.size() );
1429 for ( size_t i = 0;i < xyz.size()-1; ++i )
1431 gp_XYZ p3d = xyz[i];
1432 trsf.Transforms( p3d );
1433 xy[i].SetCoord( p3d.X(), p3d.Z() );
1435 xyz.back() = xyz.front();
1436 xy.back() = xy.front();
1438 // // move the point in 2D
1439 gp_XYZ tmpPnt = point.XYZ();
1440 trsf.Transforms( tmpPnt );
1441 gp_XY point2D( tmpPnt.X(), tmpPnt.Z() );
1443 // loop on segments of the face to analyze point position ralative to the face
1444 set< PointPos > pntPosSet;
1445 for ( size_t i = 1; i < xy.size(); ++i )
1447 PointPos pos = getPointPosition( point2D, &xy[0], i-1 );
1448 pntPosSet.insert( pos );
1452 PointPos pos = *pntPosSet.begin();
1453 // cout << "Face " << face->GetID() << " DIST: ";
1454 switch ( pos._name )
1457 // point is most close to a segment
1458 gp_Vec p0p1( point, xyz[ pos._index ] );
1459 gp_Vec p1p2( xyz[ pos._index ], xyz[ pos._index+1 ]); // segment vector
1461 double projDist = p0p1 * p1p2; // distance projected to the segment
1462 gp_Vec projVec = p1p2 * projDist;
1463 gp_Vec distVec = p0p1 - projVec;
1464 // cout << distVec.Magnitude() << ", SEG " << face->GetNode(pos._index)->GetID()
1465 // << " - " << face->GetNodeWrap(pos._index+1)->GetID() << endl;
1466 return distVec.Magnitude();
1469 // point is inside the face
1470 double distToFacePlane = tmpPnt.Y();
1471 // cout << distToFacePlane << ", INSIDE " << endl;
1472 return Abs( distToFacePlane );
1475 // point is most close to a node
1476 gp_Vec distVec( point, xyz[ pos._index ]);
1477 // cout << distVec.Magnitude() << " VERTEX " << face->GetNode(pos._index)->GetID() << endl;
1478 return distVec.Magnitude();
1485 //=======================================================================
1487 * \brief Return minimal distance from a point to an edge
1489 //=======================================================================
1491 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshEdge* seg, const gp_Pnt& point )
1493 double dist = Precision::Infinite();
1494 if ( !seg ) return dist;
1496 int i = 0, nbNodes = seg->NbNodes();
1498 vector< SMESH_TNodeXYZ > xyz( nbNodes );
1499 SMDS_ElemIteratorPtr nodeIt = seg->interlacedNodesElemIterator();
1500 while ( nodeIt->more() )
1501 xyz[ i++ ].Set( nodeIt->next() );
1503 for ( i = 1; i < nbNodes; ++i )
1505 gp_Vec edge( xyz[i-1], xyz[i] );
1506 gp_Vec n1p ( xyz[i-1], point );
1507 double u = ( edge * n1p ) / edge.SquareMagnitude(); // param [0,1] on the edge
1509 dist = Min( dist, n1p.SquareMagnitude() );
1511 else if ( u >= 1. ) {
1512 dist = Min( dist, point.SquareDistance( xyz[i] ));
1515 gp_XYZ proj = ( 1. - u ) * xyz[i-1] + u * xyz[i]; // projection of the point on the edge
1516 dist = Min( dist, point.SquareDistance( proj ));
1519 return Sqrt( dist );
1522 //=======================================================================
1524 * \brief Return minimal distance from a point to a volume
1526 * Currently we ignore non-planarity and 2nd order
1528 //=======================================================================
1530 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshVolume* volume, const gp_Pnt& point )
1532 SMDS_VolumeTool vTool( volume );
1533 vTool.SetExternalNormal();
1534 const int iQ = volume->IsQuadratic() ? 2 : 1;
1537 double minDist = 1e100, dist;
1538 for ( int iF = 0; iF < vTool.NbFaces(); ++iF )
1540 // skip a facet with normal not "looking at" the point
1541 if ( !vTool.GetFaceNormal( iF, n[0], n[1], n[2] ) ||
1542 !vTool.GetFaceBaryCenter( iF, bc[0], bc[1], bc[2] ))
1544 gp_XYZ bcp = point.XYZ() - gp_XYZ( bc[0], bc[1], bc[2] );
1545 if ( gp_XYZ( n[0], n[1], n[2] ) * bcp < 1e-6 )
1548 // find distance to a facet
1549 const SMDS_MeshNode** nodes = vTool.GetFaceNodes( iF );
1550 switch ( vTool.NbFaceNodes( iF ) / iQ ) {
1553 SMDS_FaceOfNodes tmpFace( nodes[0], nodes[ 1*iQ ], nodes[ 2*iQ ] );
1554 dist = GetDistance( &tmpFace, point );
1559 SMDS_FaceOfNodes tmpFace( nodes[0], nodes[ 1*iQ ], nodes[ 2*iQ ], nodes[ 3*iQ ]);
1560 dist = GetDistance( &tmpFace, point );
1564 vector<const SMDS_MeshNode *> nvec( nodes, nodes + vTool.NbFaceNodes( iF ));
1565 SMDS_PolygonalFaceOfNodes tmpFace( nvec );
1566 dist = GetDistance( &tmpFace, point );
1568 minDist = Min( minDist, dist );
1573 //================================================================================
1575 * \brief Returns barycentric coordinates of a point within a triangle.
1576 * A not returned bc2 = 1. - bc0 - bc1.
1577 * The point lies within the triangle if ( bc0 >= 0 && bc1 >= 0 && bc0+bc1 <= 1 )
1579 //================================================================================
1581 void SMESH_MeshAlgos::GetBarycentricCoords( const gp_XY& p,
1588 const double // matrix 2x2
1589 T11 = t0.X()-t2.X(), T12 = t1.X()-t2.X(),
1590 T21 = t0.Y()-t2.Y(), T22 = t1.Y()-t2.Y();
1591 const double Tdet = T11*T22 - T12*T21; // matrix determinant
1592 if ( Abs( Tdet ) < std::numeric_limits<double>::min() )
1598 const double t11 = T22, t12 = -T12, t21 = -T21, t22 = T11;
1600 const double r11 = p.X()-t2.X(), r12 = p.Y()-t2.Y();
1601 // barycentric coordinates: mutiply matrix by vector
1602 bc0 = (t11 * r11 + t12 * r12)/Tdet;
1603 bc1 = (t21 * r11 + t22 * r12)/Tdet;
1606 //=======================================================================
1607 //function : FindFaceInSet
1608 //purpose : Return a face having linked nodes n1 and n2 and which is
1609 // - not in avoidSet,
1610 // - in elemSet provided that !elemSet.empty()
1611 // i1 and i2 optionally returns indices of n1 and n2
1612 //=======================================================================
1614 const SMDS_MeshElement*
1615 SMESH_MeshAlgos::FindFaceInSet(const SMDS_MeshNode* n1,
1616 const SMDS_MeshNode* n2,
1617 const TIDSortedElemSet& elemSet,
1618 const TIDSortedElemSet& avoidSet,
1624 const SMDS_MeshElement* face = 0;
1626 SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator(SMDSAbs_Face);
1627 while ( invElemIt->more() && !face ) // loop on inverse faces of n1
1629 const SMDS_MeshElement* elem = invElemIt->next();
1630 if (avoidSet.count( elem ))
1632 if ( !elemSet.empty() && !elemSet.count( elem ))
1635 i1 = elem->GetNodeIndex( n1 );
1636 // find a n2 linked to n1
1637 int nbN = elem->IsQuadratic() ? elem->NbNodes()/2 : elem->NbNodes();
1638 for ( int di = -1; di < 2 && !face; di += 2 )
1640 i2 = (i1+di+nbN) % nbN;
1641 if ( elem->GetNode( i2 ) == n2 )
1644 if ( !face && elem->IsQuadratic())
1646 // analysis for quadratic elements using all nodes
1647 SMDS_ElemIteratorPtr anIter = elem->interlacedNodesElemIterator();
1648 const SMDS_MeshNode* prevN = static_cast<const SMDS_MeshNode*>( anIter->next() );
1649 for ( i1 = -1, i2 = 0; anIter->more() && !face; i1++, i2++ )
1651 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( anIter->next() );
1652 if ( n1 == prevN && n2 == n )
1656 else if ( n2 == prevN && n1 == n )
1658 face = elem; swap( i1, i2 );
1664 if ( n1ind ) *n1ind = i1;
1665 if ( n2ind ) *n2ind = i2;
1669 //================================================================================
1671 * \brief Calculate normal of a mesh face
1673 //================================================================================
1675 bool SMESH_MeshAlgos::FaceNormal(const SMDS_MeshElement* F, gp_XYZ& normal, bool normalized)
1677 if ( !F || F->GetType() != SMDSAbs_Face )
1680 normal.SetCoord(0,0,0);
1681 int nbNodes = F->NbCornerNodes();
1682 for ( int i = 0; i < nbNodes-2; ++i )
1685 for ( int n = 0; n < 3; ++n )
1687 const SMDS_MeshNode* node = F->GetNode( i + n );
1688 p[n].SetCoord( node->X(), node->Y(), node->Z() );
1690 normal += ( p[2] - p[1] ) ^ ( p[0] - p[1] );
1692 double size2 = normal.SquareModulus();
1693 bool ok = ( size2 > numeric_limits<double>::min() * numeric_limits<double>::min());
1694 if ( normalized && ok )
1695 normal /= sqrt( size2 );
1700 //=======================================================================
1701 //function : GetCommonNodes
1702 //purpose : Return nodes common to two elements
1703 //=======================================================================
1705 vector< const SMDS_MeshNode*> SMESH_MeshAlgos::GetCommonNodes(const SMDS_MeshElement* e1,
1706 const SMDS_MeshElement* e2)
1708 vector< const SMDS_MeshNode*> common;
1709 for ( int i = 0 ; i < e1->NbNodes(); ++i )
1710 if ( e2->GetNodeIndex( e1->GetNode( i )) >= 0 )
1711 common.push_back( e1->GetNode( i ));
1715 //=======================================================================
1717 * \brief Return SMESH_NodeSearcher
1719 //=======================================================================
1721 SMESH_NodeSearcher* SMESH_MeshAlgos::GetNodeSearcher(SMDS_Mesh& mesh)
1723 return new SMESH_NodeSearcherImpl( &mesh );
1726 //=======================================================================
1728 * \brief Return SMESH_NodeSearcher
1730 //=======================================================================
1732 SMESH_NodeSearcher* SMESH_MeshAlgos::GetNodeSearcher(SMDS_ElemIteratorPtr elemIt)
1734 return new SMESH_NodeSearcherImpl( 0, elemIt );
1737 //=======================================================================
1739 * \brief Return SMESH_ElementSearcher
1741 //=======================================================================
1743 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh& mesh,
1746 return new SMESH_ElementSearcherImpl( mesh, tolerance );
1749 //=======================================================================
1751 * \brief Return SMESH_ElementSearcher acting on a sub-set of elements
1753 //=======================================================================
1755 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh& mesh,
1756 SMDS_ElemIteratorPtr elemIt,
1759 return new SMESH_ElementSearcherImpl( mesh, tolerance, elemIt );