1 // Copyright (C) 2007-2011 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.
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 // SMESH SMESH : implementaion of SMESH idl descriptions
23 // File : SMESH_Algo.cxx
24 // Author : Paul RASCLE, EDF
27 #include "SMESH_Algo.hxx"
29 #include "SMDS_EdgePosition.hxx"
30 #include "SMDS_FacePosition.hxx"
31 #include "SMDS_MeshElement.hxx"
32 #include "SMDS_MeshNode.hxx"
33 #include "SMDS_VolumeTool.hxx"
34 #include "SMESHDS_Mesh.hxx"
35 #include "SMESHDS_SubMesh.hxx"
36 #include "SMESH_Comment.hxx"
37 #include "SMESH_Gen.hxx"
38 #include "SMESH_HypoFilter.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_TypeDefs.hxx"
42 #include <Basics_OCCTVersion.hxx>
44 #include <BRepAdaptor_Curve.hxx>
45 #include <BRepLProp.hxx>
46 #include <BRep_Tool.hxx>
47 #include <GCPnts_AbscissaPoint.hxx>
48 #include <GeomAdaptor_Curve.hxx>
49 #include <Geom_Surface.hxx>
51 #include <TopLoc_Location.hxx>
52 #include <TopTools_ListIteratorOfListOfShape.hxx>
53 #include <TopTools_ListOfShape.hxx>
55 #include <TopoDS_Edge.hxx>
56 #include <TopoDS_Face.hxx>
57 #include <TopoDS_Vertex.hxx>
59 #include <gp_Pnt2d.hxx>
62 #include <Standard_ErrorHandler.hxx>
63 #include <Standard_Failure.hxx>
65 #include "utilities.h"
72 //=============================================================================
76 //=============================================================================
78 SMESH_Algo::SMESH_Algo (int hypId, int studyId, SMESH_Gen * gen)
79 : SMESH_Hypothesis(hypId, studyId, gen)
81 gen->_mapAlgo[hypId] = this;
83 _onlyUnaryInput = _requireDescretBoundary = _requireShape = true;
84 _quadraticMesh = _supportSubmeshes = false;
88 //=============================================================================
92 //=============================================================================
94 SMESH_Algo::~SMESH_Algo()
98 //=============================================================================
100 * Usually an algoritm has nothing to save
102 //=============================================================================
104 ostream & SMESH_Algo::SaveTo(ostream & save) { return save; }
105 istream & SMESH_Algo::LoadFrom(istream & load) { return load; }
107 //=============================================================================
111 //=============================================================================
113 const vector < string > &SMESH_Algo::GetCompatibleHypothesis()
115 return _compatibleHypothesis;
118 //=============================================================================
120 * List the hypothesis used by the algorithm associated to the shape.
121 * Hypothesis associated to father shape -are- taken into account (see
122 * GetAppliedHypothesis). Relevant hypothesis have a name (type) listed in
123 * the algorithm. This method could be surcharged by specific algorithms, in
124 * case of several hypothesis simultaneously applicable.
126 //=============================================================================
128 const list <const SMESHDS_Hypothesis *> &
129 SMESH_Algo::GetUsedHypothesis(SMESH_Mesh & aMesh,
130 const TopoDS_Shape & aShape,
131 const bool ignoreAuxiliary)
133 _usedHypList.clear();
134 SMESH_HypoFilter filter;
135 if ( InitCompatibleHypoFilter( filter, ignoreAuxiliary ))
137 aMesh.GetHypotheses( aShape, filter, _usedHypList, true );
138 if ( ignoreAuxiliary && _usedHypList.size() > 1 )
139 _usedHypList.clear(); //only one compatible hypothesis allowed
144 //=============================================================================
146 * List the relevant hypothesis associated to the shape. Relevant hypothesis
147 * have a name (type) listed in the algorithm. Hypothesis associated to
148 * father shape -are not- taken into account (see GetUsedHypothesis)
150 //=============================================================================
152 const list<const SMESHDS_Hypothesis *> &
153 SMESH_Algo::GetAppliedHypothesis(SMESH_Mesh & aMesh,
154 const TopoDS_Shape & aShape,
155 const bool ignoreAuxiliary)
157 _appliedHypList.clear();
158 SMESH_HypoFilter filter;
159 if ( InitCompatibleHypoFilter( filter, ignoreAuxiliary ))
160 aMesh.GetHypotheses( aShape, filter, _appliedHypList, false );
162 return _appliedHypList;
165 //=============================================================================
167 * Compute length of an edge
169 //=============================================================================
171 double SMESH_Algo::EdgeLength(const TopoDS_Edge & E)
173 double UMin = 0, UMax = 0;
174 if (BRep_Tool::Degenerated(E))
177 Handle(Geom_Curve) C = BRep_Tool::Curve(E, L, UMin, UMax);
178 GeomAdaptor_Curve AdaptCurve(C, UMin, UMax); //range is important for periodic curves
179 double length = GCPnts_AbscissaPoint::Length(AdaptCurve, UMin, UMax);
183 //================================================================================
185 * \brief Calculate normal of a mesh face
187 //================================================================================
189 bool SMESH_Algo::FaceNormal(const SMDS_MeshElement* F, gp_XYZ& normal, bool normalized)
191 if ( !F || F->GetType() != SMDSAbs_Face )
194 normal.SetCoord(0,0,0);
195 int nbNodes = F->IsQuadratic() ? F->NbNodes()/2 : F->NbNodes();
196 for ( int i = 0; i < nbNodes-2; ++i )
199 for ( int n = 0; n < 3; ++n )
201 const SMDS_MeshNode* node = F->GetNode( i + n );
202 p[n].SetCoord( node->X(), node->Y(), node->Z() );
204 normal += ( p[2] - p[1] ) ^ ( p[0] - p[1] );
206 double size2 = normal.SquareModulus();
207 bool ok = ( size2 > numeric_limits<double>::min() * numeric_limits<double>::min());
208 if ( normalized && ok )
209 normal /= sqrt( size2 );
214 //================================================================================
216 * \brief Find out elements orientation on a geometrical face
217 * \param theFace - The face correctly oriented in the shape being meshed
218 * \param theMeshDS - The mesh data structure
219 * \retval bool - true if the face normal and the normal of first element
220 * in the correspoding submesh point in different directions
222 //================================================================================
224 bool SMESH_Algo::IsReversedSubMesh (const TopoDS_Face& theFace,
225 SMESHDS_Mesh* theMeshDS)
227 if ( theFace.IsNull() || !theMeshDS )
230 // find out orientation of a meshed face
231 int faceID = theMeshDS->ShapeToIndex( theFace );
232 TopoDS_Shape aMeshedFace = theMeshDS->IndexToShape( faceID );
233 bool isReversed = ( theFace.Orientation() != aMeshedFace.Orientation() );
235 const SMESHDS_SubMesh * aSubMeshDSFace = theMeshDS->MeshElements( faceID );
236 if ( !aSubMeshDSFace )
239 // find element with node located on face and get its normal
240 const SMDS_FacePosition* facePos = 0;
244 bool normalOK = false;
245 SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
246 while ( iteratorElem->more() ) // loop on elements on theFace
248 const SMDS_MeshElement* elem = iteratorElem->next();
249 if ( elem && elem->NbNodes() > 2 ) {
250 SMDS_ElemIteratorPtr nodesIt = elem->nodesIterator();
251 const SMDS_FacePosition* fPos = 0;
253 while ( nodesIt->more() ) { // loop on nodes
254 const SMDS_MeshNode* node
255 = static_cast<const SMDS_MeshNode *>(nodesIt->next());
257 nPnt[ i++ ].SetCoord( node->X(), node->Y(), node->Z() );
259 const SMDS_PositionPtr& pos = node->GetPosition();
260 if ( !pos ) continue;
261 if ( pos->GetTypeOfPosition() == SMDS_TOP_FACE ) {
262 fPos = dynamic_cast< const SMDS_FacePosition* >( pos );
264 else if ( pos->GetTypeOfPosition() == SMDS_TOP_VERTEX ) {
265 vID = node->getshapeId();
268 if ( fPos || ( !normalOK && vID )) {
270 gp_Vec v01( nPnt[0], nPnt[1] ), v02( nPnt[0], nPnt[2] );
271 if ( v01.SquareMagnitude() > RealSmall() &&
272 v02.SquareMagnitude() > RealSmall() )
275 normalOK = ( Ne.SquareMagnitude() > RealSmall() );
277 // we need position on theFace or at least on vertex
280 if ((facePos = fPos))
289 // node position on face
292 u = facePos->GetUParameter();
293 v = facePos->GetVParameter();
295 else if ( vertexID ) {
296 TopoDS_Shape V = theMeshDS->IndexToShape( vertexID );
297 if ( V.IsNull() || V.ShapeType() != TopAbs_VERTEX )
299 gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( V ), theFace );
308 // face normal at node position
310 Handle(Geom_Surface) surf = BRep_Tool::Surface( theFace, loc );
311 if ( surf.IsNull() || surf->Continuity() < GeomAbs_C1 ) return isReversed;
313 surf->D1( u, v, nPnt[0], d1u, d1v );
314 gp_Vec Nf = (d1u ^ d1v).Transformed( loc );
316 if ( theFace.Orientation() == TopAbs_REVERSED )
322 //================================================================================
324 * \brief Just return false as the algorithm does not hold parameters values
326 //================================================================================
328 bool SMESH_Algo::SetParametersByMesh(const SMESH_Mesh* /*theMesh*/,
329 const TopoDS_Shape& /*theShape*/)
333 bool SMESH_Algo::SetParametersByDefaults(const TDefaults& , const SMESH_Mesh*)
337 //================================================================================
339 * \brief Fill vector of node parameters on geometrical edge, including vertex nodes
340 * \param theMesh - The mesh containing nodes
341 * \param theEdge - The geometrical edge of interest
342 * \param theParams - The resulting vector of sorted node parameters
343 * \retval bool - false if not all parameters are OK
345 //================================================================================
347 bool SMESH_Algo::GetNodeParamOnEdge(const SMESHDS_Mesh* theMesh,
348 const TopoDS_Edge& theEdge,
349 vector< double > & theParams)
353 if ( !theMesh || theEdge.IsNull() )
356 SMESHDS_SubMesh * eSubMesh = theMesh->MeshElements( theEdge );
357 if ( !eSubMesh || !eSubMesh->GetElements()->more() )
358 return false; // edge is not meshed
360 //int nbEdgeNodes = 0;
361 set < double > paramSet;
364 // loop on nodes of an edge: sort them by param on edge
365 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
366 while ( nIt->more() )
368 const SMDS_MeshNode* node = nIt->next();
369 const SMDS_PositionPtr& pos = node->GetPosition();
370 if ( pos->GetTypeOfPosition() != SMDS_TOP_EDGE )
372 const SMDS_EdgePosition* epos =
373 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
374 if ( !paramSet.insert( epos->GetUParameter() ).second )
375 return false; // equal parameters
378 // add vertex nodes params
380 TopExp::Vertices( theEdge, V1, V2);
381 if ( VertexNode( V1, theMesh ) &&
382 !paramSet.insert( BRep_Tool::Parameter(V1,theEdge) ).second )
383 return false; // there are equal parameters
384 if ( VertexNode( V2, theMesh ) &&
385 !paramSet.insert( BRep_Tool::Parameter(V2,theEdge) ).second )
386 return false; // there are equal parameters
389 theParams.resize( paramSet.size() );
390 set < double >::iterator par = paramSet.begin();
391 vector< double >::iterator vecPar = theParams.begin();
392 for ( ; par != paramSet.end(); ++par, ++vecPar )
395 return theParams.size() > 1;
398 //================================================================================
400 * \brief Fill vector of node parameters on geometrical edge, including vertex nodes
401 * \param theMesh - The mesh containing nodes
402 * \param theEdge - The geometrical edge of interest
403 * \param theParams - The resulting vector of sorted node parameters
404 * \retval bool - false if not all parameters are OK
406 //================================================================================
408 bool SMESH_Algo::GetSortedNodesOnEdge(const SMESHDS_Mesh* theMesh,
409 const TopoDS_Edge& theEdge,
410 const bool ignoreMediumNodes,
411 map< double, const SMDS_MeshNode* > & theNodes)
415 if ( !theMesh || theEdge.IsNull() )
418 SMESHDS_SubMesh * eSubMesh = theMesh->MeshElements( theEdge );
419 if ( !eSubMesh || !eSubMesh->GetElements()->more() )
420 return false; // edge is not meshed
423 set < double > paramSet;
426 // loop on nodes of an edge: sort them by param on edge
427 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
428 while ( nIt->more() )
430 const SMDS_MeshNode* node = nIt->next();
431 if ( ignoreMediumNodes ) {
432 SMDS_ElemIteratorPtr elemIt = node->GetInverseElementIterator();
433 if ( elemIt->more() && elemIt->next()->IsMediumNode( node ))
436 const SMDS_PositionPtr& pos = node->GetPosition();
437 if ( pos->GetTypeOfPosition() != SMDS_TOP_EDGE )
439 const SMDS_EdgePosition* epos =
440 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
441 theNodes.insert( make_pair( epos->GetUParameter(), node ));
442 //MESSAGE("U " << epos->GetUParameter() << " ID " << node->GetID());
447 TopoDS_Vertex v1, v2;
448 TopExp::Vertices(theEdge, v1, v2);
449 const SMDS_MeshNode* n1 = VertexNode( v1, (SMESHDS_Mesh*) theMesh );
450 const SMDS_MeshNode* n2 = VertexNode( v2, (SMESHDS_Mesh*) theMesh );
451 //MESSAGE("Vertices ID " << n1->GetID() << " " << n2->GetID());
453 BRep_Tool::Range(theEdge, f, l);
454 if ( v1.Orientation() != TopAbs_FORWARD )
456 if ( n1 && ++nbNodes )
457 theNodes.insert( make_pair( f, n1 ));
458 if ( n2 && ++nbNodes )
459 theNodes.insert( make_pair( l, n2 ));
461 return theNodes.size() == nbNodes;
464 //================================================================================
466 * \brief Make filter recognize only compatible hypotheses
467 * \param theFilter - the filter to initialize
468 * \param ignoreAuxiliary - make filter ignore compatible auxiliary hypotheses
470 //================================================================================
472 bool SMESH_Algo::InitCompatibleHypoFilter( SMESH_HypoFilter & theFilter,
473 const bool ignoreAuxiliary) const
475 if ( !_compatibleHypothesis.empty() )
477 theFilter.Init( theFilter.HasName( _compatibleHypothesis[0] ));
478 for ( int i = 1; i < _compatibleHypothesis.size(); ++i )
479 theFilter.Or( theFilter.HasName( _compatibleHypothesis[ i ] ));
481 if ( ignoreAuxiliary )
482 theFilter.AndNot( theFilter.IsAuxiliary() );
489 //================================================================================
491 * \brief Return continuity of two edges
492 * \param E1 - the 1st edge
493 * \param E2 - the 2nd edge
494 * \retval GeomAbs_Shape - regularity at the junction between E1 and E2
496 //================================================================================
498 GeomAbs_Shape SMESH_Algo::Continuity(TopoDS_Edge E1,
501 //E1.Orientation(TopAbs_FORWARD), E2.Orientation(TopAbs_FORWARD); // avoid pb with internal edges
502 if (E1.Orientation() > TopAbs_REVERSED) // INTERNAL
503 E1.Orientation( TopAbs_FORWARD );
504 if (E2.Orientation() > TopAbs_REVERSED) // INTERNAL
505 E2.Orientation( TopAbs_FORWARD );
506 TopoDS_Vertex V = TopExp::LastVertex (E1, true);
507 if ( !V.IsSame( TopExp::FirstVertex(E2, true )))
508 if ( !TopExp::CommonVertex( E1, E2, V ))
510 Standard_Real u1 = BRep_Tool::Parameter( V, E1 );
511 Standard_Real u2 = BRep_Tool::Parameter( V, E2 );
512 BRepAdaptor_Curve C1( E1 ), C2( E2 );
513 Standard_Real tol = BRep_Tool::Tolerance( V );
514 Standard_Real angTol = 2e-3;
516 #if OCC_VERSION_LARGE > 0x06010000
519 return BRepLProp::Continuity(C1, C2, u1, u2, tol, angTol);
521 catch (Standard_Failure) {
526 //================================================================================
528 * \brief Return the node built on a vertex
529 * \param V - the vertex
530 * \param meshDS - mesh
531 * \retval const SMDS_MeshNode* - found node or NULL
533 //================================================================================
535 const SMDS_MeshNode* SMESH_Algo::VertexNode(const TopoDS_Vertex& V,
536 const SMESHDS_Mesh* meshDS)
538 if ( SMESHDS_SubMesh* sm = meshDS->MeshElements(V) ) {
539 SMDS_NodeIteratorPtr nIt= sm->GetNodes();
546 //=======================================================================
547 //function : GetCommonNodes
548 //purpose : Return nodes common to two elements
549 //=======================================================================
551 vector< const SMDS_MeshNode*> SMESH_Algo::GetCommonNodes(const SMDS_MeshElement* e1,
552 const SMDS_MeshElement* e2)
554 vector< const SMDS_MeshNode*> common;
555 for ( int i = 0 ; i < e1->NbNodes(); ++i )
556 if ( e2->GetNodeIndex( e1->GetNode( i )) >= 0 )
557 common.push_back( e1->GetNode( i ));
561 //=======================================================================
562 //function : GetMeshError
563 //purpose : Finds topological errors of a sub-mesh
564 //WARNING : 1D check is NOT implemented so far
565 //=======================================================================
567 SMESH_Algo::EMeshError SMESH_Algo::GetMeshError(SMESH_subMesh* subMesh)
569 EMeshError err = MEr_OK;
571 SMESHDS_SubMesh* smDS = subMesh->GetSubMeshDS();
575 switch ( subMesh->GetSubShape().ShapeType() )
577 case TopAbs_FACE: { // ====================== 2D =====================
579 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
583 // We check that olny links on EDGEs encouter once, the rest links, twice
584 set< SMESH_TLink > links;
585 while ( fIt->more() )
587 const SMDS_MeshElement* f = fIt->next();
588 int nbNodes = f->NbCornerNodes(); // ignore medium nodes
589 for ( int i = 0; i < nbNodes; ++i )
591 const SMDS_MeshNode* n1 = f->GetNode( i );
592 const SMDS_MeshNode* n2 = f->GetNode(( i+1 ) % nbNodes);
593 std::pair< set< SMESH_TLink >::iterator, bool > it_added =
594 links.insert( SMESH_TLink( n1, n2 ));
595 if ( !it_added.second )
596 // As we do NOT(!) check if mesh is manifold, we believe that a link can
597 // encounter once or twice only (not three times), we erase a link as soon
598 // as it encounters twice to speed up search in the <links> map.
599 links.erase( it_added.first );
602 // the links remaining in the <links> should all be on EDGE
603 set< SMESH_TLink >::iterator linkIt = links.begin();
604 for ( ; linkIt != links.end(); ++linkIt )
606 const SMESH_TLink& link = *linkIt;
607 if ( link.node1()->GetPosition()->GetTypeOfPosition() > SMDS_TOP_EDGE ||
608 link.node2()->GetPosition()->GetTypeOfPosition() > SMDS_TOP_EDGE )
611 // TODO: to check orientation
614 case TopAbs_SOLID: { // ====================== 3D =====================
616 SMDS_ElemIteratorPtr vIt = smDS->GetElements();
620 SMDS_VolumeTool vTool;
621 while ( !vIt->more() )
623 if (!vTool.Set( vIt->next() ))
626 for ( int iF = 0; iF < vTool.NbFaces(); ++iF )
627 if ( vTool.IsFreeFace( iF ))
629 int nbN = vTool.NbFaceNodes( iF );
630 const SMDS_MeshNode** nodes = vTool.GetFaceNodes( iF );
631 for ( int i = 0; i < nbN; ++i )
632 if ( nodes[i]->GetPosition()->GetTypeOfPosition() > SMDS_TOP_FACE )
643 //================================================================================
645 * \brief Sets event listener to submeshes if necessary
646 * \param subMesh - submesh where algo is set
648 * After being set, event listener is notified on each event of a submesh.
649 * By default non listener is set
651 //================================================================================
653 void SMESH_Algo::SetEventListener(SMESH_subMesh* /*subMesh*/)
657 //================================================================================
659 * \brief Allow algo to do something after persistent restoration
660 * \param subMesh - restored submesh
662 * This method is called only if a submesh has HYP_OK algo_state.
664 //================================================================================
666 void SMESH_Algo::SubmeshRestored(SMESH_subMesh* /*subMesh*/)
670 //================================================================================
672 * \brief Computes mesh without geometry
673 * \param aMesh - the mesh
674 * \param aHelper - helper that must be used for adding elements to \aaMesh
675 * \retval bool - is a success
677 //================================================================================
679 bool SMESH_Algo::Compute(SMESH_Mesh & /*aMesh*/, SMESH_MesherHelper* /*aHelper*/)
681 return error( COMPERR_BAD_INPUT_MESH, "Mesh built on shape expected");
684 #ifdef WITH_SMESH_CANCEL_COMPUTE
685 void SMESH_Algo::CancelCompute()
690 //================================================================================
692 * \brief store error and comment and then return ( error == COMPERR_OK )
694 //================================================================================
696 bool SMESH_Algo::error(int error, const SMESH_Comment& comment)
700 return ( error == COMPERR_OK );
703 //================================================================================
705 * \brief store error and return ( error == COMPERR_OK )
707 //================================================================================
709 bool SMESH_Algo::error(SMESH_ComputeErrorPtr error)
712 _error = error->myName;
713 _comment = error->myComment;
714 _badInputElements = error->myBadElements;
715 return error->IsOK();
720 //================================================================================
722 * \brief return compute error
724 //================================================================================
726 SMESH_ComputeErrorPtr SMESH_Algo::GetComputeError() const
728 SMESH_ComputeErrorPtr err = SMESH_ComputeError::New( _error, _comment, this );
729 // hope this method is called by only SMESH_subMesh after this->Compute()
730 err->myBadElements.splice( err->myBadElements.end(),
731 (list<const SMDS_MeshElement*>&) _badInputElements );
735 //================================================================================
737 * \brief initialize compute error
739 //================================================================================
741 void SMESH_Algo::InitComputeError()
745 list<const SMDS_MeshElement*>::iterator elem = _badInputElements.begin();
746 for ( ; elem != _badInputElements.end(); ++elem )
747 if ( (*elem)->GetID() < 1 )
749 _badInputElements.clear();
752 //================================================================================
754 * \brief store a bad input element preventing computation,
755 * which may be a temporary one i.e. not residing the mesh,
756 * then it will be deleted by InitComputeError()
758 //================================================================================
760 void SMESH_Algo::addBadInputElement(const SMDS_MeshElement* elem)
763 _badInputElements.push_back( elem );