Salome HOME
Merge from BR_V5_DEV 16Feb09
[modules/smesh.git] / src / SMESH / SMESH_Algo.cxx
1 //  Copyright (C) 2007-2008  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.
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 //  SMESH SMESH : implementaion of SMESH idl descriptions
23 //  File   : SMESH_Algo.cxx
24 //  Author : Paul RASCLE, EDF
25 //  Module : SMESH
26 //
27
28 #include "SMESH_Algo.hxx"
29 #include "SMESH_Comment.hxx"
30 #include "SMESH_Gen.hxx"
31 #include "SMESH_Mesh.hxx"
32 #include "SMESH_HypoFilter.hxx"
33 #include "SMDS_FacePosition.hxx"
34 #include "SMDS_EdgePosition.hxx"
35 #include "SMDS_MeshElement.hxx"
36 #include "SMDS_MeshNode.hxx"
37 #include "SMESHDS_Mesh.hxx"
38 #include "SMESHDS_SubMesh.hxx"
39
40 #include <BRepAdaptor_Curve.hxx>
41 #include <BRepLProp.hxx>
42 #include <BRep_Tool.hxx>
43 #include <GCPnts_AbscissaPoint.hxx>
44 #include <GeomAdaptor_Curve.hxx>
45 #include <Geom_Surface.hxx>
46 #include <TopExp.hxx>
47 #include <TopLoc_Location.hxx>
48 #include <TopTools_ListIteratorOfListOfShape.hxx>
49 #include <TopTools_ListOfShape.hxx>
50 #include <TopoDS.hxx>
51 #include <TopoDS_Edge.hxx>
52 #include <TopoDS_Face.hxx>
53 #include <TopoDS_Vertex.hxx>
54 #include <gp_Pnt.hxx>
55 #include <gp_Pnt2d.hxx>
56 #include <gp_Vec.hxx>
57
58 #include <Standard_ErrorHandler.hxx>
59 #include <Standard_Failure.hxx>
60
61 #include "utilities.h"
62
63 #include <algorithm>
64
65 using namespace std;
66
67 //=============================================================================
68 /*!
69  *  
70  */
71 //=============================================================================
72
73 SMESH_Algo::SMESH_Algo (int hypId, int studyId, SMESH_Gen * gen)
74   : SMESH_Hypothesis(hypId, studyId, gen)
75 {
76   gen->_mapAlgo[hypId] = this;
77
78   _onlyUnaryInput = _requireDescretBoundary = _requireShape = true;
79   _quadraticMesh = false;
80   _error = COMPERR_OK;
81 }
82
83 //=============================================================================
84 /*!
85  *  
86  */
87 //=============================================================================
88
89 SMESH_Algo::~SMESH_Algo()
90 {
91 }
92
93 //=============================================================================
94 /*!
95  * Usually an algoritm has nothing to save
96  */
97 //=============================================================================
98
99 ostream & SMESH_Algo::SaveTo(ostream & save) { return save; }
100 istream & SMESH_Algo::LoadFrom(istream & load) { return load; }
101
102 //=============================================================================
103 /*!
104  *  
105  */
106 //=============================================================================
107
108 const vector < string > &SMESH_Algo::GetCompatibleHypothesis()
109 {
110   return _compatibleHypothesis;
111 }
112
113 //=============================================================================
114 /*!
115  *  List the hypothesis used by the algorithm associated to the shape.
116  *  Hypothesis associated to father shape -are- taken into account (see
117  *  GetAppliedHypothesis). Relevant hypothesis have a name (type) listed in
118  *  the algorithm. This method could be surcharged by specific algorithms, in 
119  *  case of several hypothesis simultaneously applicable.
120  */
121 //=============================================================================
122
123 const list <const SMESHDS_Hypothesis *> &
124 SMESH_Algo::GetUsedHypothesis(SMESH_Mesh &         aMesh,
125                               const TopoDS_Shape & aShape,
126                               const bool           ignoreAuxiliary)
127 {
128   _usedHypList.clear();
129   SMESH_HypoFilter filter;
130   if ( InitCompatibleHypoFilter( filter, ignoreAuxiliary ))
131   {
132     aMesh.GetHypotheses( aShape, filter, _usedHypList, true );
133     if ( ignoreAuxiliary && _usedHypList.size() > 1 )
134       _usedHypList.clear(); //only one compatible hypothesis allowed
135   }
136   return _usedHypList;
137 }
138
139 //=============================================================================
140 /*!
141  *  List the relevant hypothesis associated to the shape. Relevant hypothesis
142  *  have a name (type) listed in the algorithm. Hypothesis associated to
143  *  father shape -are not- taken into account (see GetUsedHypothesis)
144  */
145 //=============================================================================
146
147 const list<const SMESHDS_Hypothesis *> &
148 SMESH_Algo::GetAppliedHypothesis(SMESH_Mesh &         aMesh,
149                                  const TopoDS_Shape & aShape,
150                                  const bool           ignoreAuxiliary)
151 {
152   _appliedHypList.clear();
153   SMESH_HypoFilter filter;
154   if ( InitCompatibleHypoFilter( filter, ignoreAuxiliary ))
155     aMesh.GetHypotheses( aShape, filter, _appliedHypList, false );
156
157   return _appliedHypList;
158 }
159
160 //=============================================================================
161 /*!
162  *  Compute length of an edge
163  */
164 //=============================================================================
165
166 double SMESH_Algo::EdgeLength(const TopoDS_Edge & E)
167 {
168   double UMin = 0, UMax = 0;
169   if (BRep_Tool::Degenerated(E))
170     return 0;
171   TopLoc_Location L;
172   Handle(Geom_Curve) C = BRep_Tool::Curve(E, L, UMin, UMax);
173   GeomAdaptor_Curve AdaptCurve(C);
174   double length = GCPnts_AbscissaPoint::Length(AdaptCurve, UMin, UMax);
175   return length;
176 }
177
178 //================================================================================
179 /*!
180  * \brief Find out elements orientation on a geometrical face
181  * \param theFace - The face correctly oriented in the shape being meshed
182  * \param theMeshDS - The mesh data structure
183  * \retval bool - true if the face normal and the normal of first element
184  *                in the correspoding submesh point in different directions
185  */
186 //================================================================================
187
188 bool SMESH_Algo::IsReversedSubMesh (const TopoDS_Face&  theFace,
189                                     SMESHDS_Mesh*       theMeshDS)
190 {
191   if ( theFace.IsNull() || !theMeshDS )
192     return false;
193
194   // find out orientation of a meshed face
195   int faceID = theMeshDS->ShapeToIndex( theFace );
196   TopoDS_Shape aMeshedFace = theMeshDS->IndexToShape( faceID );
197   bool isReversed = ( theFace.Orientation() != aMeshedFace.Orientation() );
198
199   const SMESHDS_SubMesh * aSubMeshDSFace = theMeshDS->MeshElements( faceID );
200   if ( !aSubMeshDSFace )
201     return isReversed;
202
203   // find element with node located on face and get its normal
204   const SMDS_FacePosition* facePos = 0;
205   int vertexID = 0;
206   gp_Pnt nPnt[3];
207   gp_Vec Ne;
208   bool normalOK = false;
209   SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
210   while ( iteratorElem->more() ) // loop on elements on theFace
211   {
212     const SMDS_MeshElement* elem = iteratorElem->next();
213     if ( elem && elem->NbNodes() > 2 ) {
214       SMDS_ElemIteratorPtr nodesIt = elem->nodesIterator();
215       const SMDS_FacePosition* fPos = 0;
216       int i = 0, vID = 0;
217       while ( nodesIt->more() ) { // loop on nodes
218         const SMDS_MeshNode* node
219           = static_cast<const SMDS_MeshNode *>(nodesIt->next());
220         if ( i == 3 ) i = 2;
221         nPnt[ i++ ].SetCoord( node->X(), node->Y(), node->Z() );
222         // check position
223         const SMDS_PositionPtr& pos = node->GetPosition();
224         if ( !pos ) continue;
225         if ( pos->GetTypeOfPosition() == SMDS_TOP_FACE ) {
226           fPos = dynamic_cast< const SMDS_FacePosition* >( pos.get() );
227         }
228         else if ( pos->GetTypeOfPosition() == SMDS_TOP_VERTEX ) {
229           vID = pos->GetShapeId();
230         }
231       }
232       if ( fPos || ( !normalOK && vID )) {
233         // compute normal
234         gp_Vec v01( nPnt[0], nPnt[1] ), v02( nPnt[0], nPnt[2] );
235         if ( v01.SquareMagnitude() > RealSmall() &&
236              v02.SquareMagnitude() > RealSmall() )
237         {
238           Ne = v01 ^ v02;
239           normalOK = ( Ne.SquareMagnitude() > RealSmall() );
240         }
241         // we need position on theFace or at least on vertex
242         if ( normalOK ) {
243           vertexID = vID;
244           if ((facePos = fPos))
245             break;
246         }
247       }
248     }
249   }
250   if ( !normalOK )
251     return isReversed;
252
253   // node position on face
254   double u,v;
255   if ( facePos ) {
256     u = facePos->GetUParameter();
257     v = facePos->GetVParameter();
258   }
259   else if ( vertexID ) {
260     TopoDS_Shape V = theMeshDS->IndexToShape( vertexID );
261     if ( V.IsNull() || V.ShapeType() != TopAbs_VERTEX )
262       return isReversed;
263     gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( V ), theFace );
264     u = uv.X();
265     v = uv.Y();
266   }
267   else
268   {
269     return isReversed;
270   }
271
272   // face normal at node position
273   TopLoc_Location loc;
274   Handle(Geom_Surface) surf = BRep_Tool::Surface( theFace, loc );
275   if ( surf.IsNull() || surf->Continuity() < GeomAbs_C1 ) return isReversed;
276   gp_Vec d1u, d1v;
277   surf->D1( u, v, nPnt[0], d1u, d1v );
278   gp_Vec Nf = (d1u ^ d1v).Transformed( loc );
279
280   if ( theFace.Orientation() == TopAbs_REVERSED )
281     Nf.Reverse();
282
283   return Ne * Nf < 0.;
284 }
285
286 //================================================================================
287 /*!
288  * \brief Just return false as the algorithm does not hold parameters values
289  */
290 //================================================================================
291
292 bool SMESH_Algo::SetParametersByMesh(const SMESH_Mesh* /*theMesh*/,
293                                      const TopoDS_Shape& /*theShape*/)
294 {
295   return false;
296 }
297 bool SMESH_Algo::SetParametersByDefaults(const TDefaults& , const SMESH_Mesh*)
298 {
299   return false;
300 }
301 //================================================================================
302 /*!
303  * \brief Fill vector of node parameters on geometrical edge, including vertex nodes
304  * \param theMesh - The mesh containing nodes
305  * \param theEdge - The geometrical edge of interest
306  * \param theParams - The resulting vector of sorted node parameters
307  * \retval bool - false if not all parameters are OK
308  */
309 //================================================================================
310
311 bool SMESH_Algo::GetNodeParamOnEdge(const SMESHDS_Mesh* theMesh,
312                                     const TopoDS_Edge&  theEdge,
313                                     vector< double > &  theParams)
314 {
315   theParams.clear();
316
317   if ( !theMesh || theEdge.IsNull() )
318     return false;
319
320   SMESHDS_SubMesh * eSubMesh = theMesh->MeshElements( theEdge );
321   if ( !eSubMesh || !eSubMesh->GetElements()->more() )
322     return false; // edge is not meshed
323
324   int nbEdgeNodes = 0;
325   set < double > paramSet;
326   if ( eSubMesh )
327   {
328     // loop on nodes of an edge: sort them by param on edge
329     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
330     while ( nIt->more() )
331     {
332       const SMDS_MeshNode* node = nIt->next();
333       const SMDS_PositionPtr& pos = node->GetPosition();
334       if ( pos->GetTypeOfPosition() != SMDS_TOP_EDGE )
335         return false;
336       const SMDS_EdgePosition* epos =
337         static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
338       paramSet.insert( epos->GetUParameter() );
339       ++nbEdgeNodes;
340     }
341   }
342   // add vertex nodes params
343   Standard_Real f, l;
344   BRep_Tool::Range(theEdge, f, l);
345   paramSet.insert( f );
346   paramSet.insert( l );
347   if ( paramSet.size() != nbEdgeNodes + 2 )
348     return false; // there are equal parameters
349
350   // fill the vector
351   theParams.resize( paramSet.size() );
352   set < double >::iterator   par    = paramSet.begin();
353   vector< double >::iterator vecPar = theParams.begin();
354   for ( ; par != paramSet.end(); ++par, ++vecPar )
355     *vecPar = *par;
356
357   return theParams.size() > 1;
358 }
359
360 //================================================================================
361 /*!
362  * \brief Fill vector of node parameters on geometrical edge, including vertex nodes
363  * \param theMesh - The mesh containing nodes
364  * \param theEdge - The geometrical edge of interest
365  * \param theParams - The resulting vector of sorted node parameters
366  * \retval bool - false if not all parameters are OK
367  */
368 //================================================================================
369
370 bool SMESH_Algo::GetSortedNodesOnEdge(const SMESHDS_Mesh*                   theMesh,
371                                       const TopoDS_Edge&                    theEdge,
372                                       const bool                            ignoreMediumNodes,
373                                       map< double, const SMDS_MeshNode* > & theNodes)
374 {
375   theNodes.clear();
376
377   if ( !theMesh || theEdge.IsNull() )
378     return false;
379
380   SMESHDS_SubMesh * eSubMesh = theMesh->MeshElements( theEdge );
381   if ( !eSubMesh || !eSubMesh->GetElements()->more() )
382     return false; // edge is not meshed
383
384   int nbNodes = 0;
385   set < double > paramSet;
386   if ( eSubMesh )
387   {
388     // loop on nodes of an edge: sort them by param on edge
389     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
390     while ( nIt->more() )
391     {
392       const SMDS_MeshNode* node = nIt->next();
393       if ( ignoreMediumNodes ) {
394         SMDS_ElemIteratorPtr elemIt = node->GetInverseElementIterator();
395         if ( elemIt->more() && elemIt->next()->IsMediumNode( node ))
396           continue;
397       }
398       const SMDS_PositionPtr& pos = node->GetPosition();
399       if ( pos->GetTypeOfPosition() != SMDS_TOP_EDGE )
400         return false;
401       const SMDS_EdgePosition* epos =
402         static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
403       theNodes.insert( make_pair( epos->GetUParameter(), node ));
404       ++nbNodes;
405     }
406   }
407   // add vertex nodes
408   TopoDS_Vertex v1, v2;
409   TopExp::Vertices(theEdge, v1, v2);
410   const SMDS_MeshNode* n1 = VertexNode( v1, (SMESHDS_Mesh*) theMesh );
411   const SMDS_MeshNode* n2 = VertexNode( v2, (SMESHDS_Mesh*) theMesh );
412   Standard_Real f, l;
413   BRep_Tool::Range(theEdge, f, l);
414   if ( v1.Orientation() != TopAbs_FORWARD )
415     std::swap( f, l );
416   if ( n1 && ++nbNodes )
417     theNodes.insert( make_pair( f, n1 ));
418   if ( n2 && ++nbNodes )
419     theNodes.insert( make_pair( l, n2 ));
420
421   return theNodes.size() == nbNodes;
422 }
423
424 //================================================================================
425 /*!
426  * \brief Make filter recognize only compatible hypotheses
427  * \param theFilter - the filter to initialize
428  * \param ignoreAuxiliary - make filter ignore compatible auxiliary hypotheses
429  */
430 //================================================================================
431
432 bool SMESH_Algo::InitCompatibleHypoFilter( SMESH_HypoFilter & theFilter,
433                                            const bool         ignoreAuxiliary) const
434 {
435   if ( !_compatibleHypothesis.empty() )
436   {
437     theFilter.Init( theFilter.HasName( _compatibleHypothesis[0] ));
438     for ( int i = 1; i < _compatibleHypothesis.size(); ++i )
439       theFilter.Or( theFilter.HasName( _compatibleHypothesis[ i ] ));
440
441     if ( ignoreAuxiliary )
442       theFilter.AndNot( theFilter.IsAuxiliary() );
443
444     return true;
445   }
446   return false;
447 }
448
449 //================================================================================
450 /*!
451  * \brief Return continuity of two edges
452  * \param E1 - the 1st edge
453  * \param E2 - the 2nd edge
454  * \retval GeomAbs_Shape - regularity at the junction between E1 and E2
455  */
456 //================================================================================
457
458 GeomAbs_Shape SMESH_Algo::Continuity(const TopoDS_Edge & E1,
459                                      const TopoDS_Edge & E2)
460 {
461   TopoDS_Vertex V = TopExp::LastVertex (E1, true);
462   if ( !V.IsSame( TopExp::FirstVertex(E2, true )))
463     if ( !TopExp::CommonVertex( E1, E2, V ))
464       return GeomAbs_C0;
465   Standard_Real u1 = BRep_Tool::Parameter( V, E1 );
466   Standard_Real u2 = BRep_Tool::Parameter( V, E2 );
467   BRepAdaptor_Curve C1( E1 ), C2( E2 );
468   Standard_Real tol = BRep_Tool::Tolerance( V );
469   Standard_Real angTol = 2e-3;
470   try {
471 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
472     OCC_CATCH_SIGNALS;
473 #endif
474     return BRepLProp::Continuity(C1, C2, u1, u2, tol, angTol);
475   }
476   catch (Standard_Failure) {
477   }
478   return GeomAbs_C0;
479 }
480
481 //================================================================================
482 /*!
483  * \brief Return the node built on a vertex
484  * \param V - the vertex
485  * \param meshDS - mesh
486  * \retval const SMDS_MeshNode* - found node or NULL
487  */
488 //================================================================================
489
490 const SMDS_MeshNode* SMESH_Algo::VertexNode(const TopoDS_Vertex& V,
491                                             SMESHDS_Mesh*        meshDS)
492 {
493   if ( SMESHDS_SubMesh* sm = meshDS->MeshElements(V) ) {
494     SMDS_NodeIteratorPtr nIt= sm->GetNodes();
495     if (nIt->more())
496       return nIt->next();
497   }
498   return 0;
499 }
500
501 //================================================================================
502 /*!
503  * \brief Sets event listener to submeshes if necessary
504  * \param subMesh - submesh where algo is set
505  * 
506  * After being set, event listener is notified on each event of a submesh.
507  * By default non listener is set
508  */
509 //================================================================================
510
511 void SMESH_Algo::SetEventListener(SMESH_subMesh* /*subMesh*/)
512 {
513 }
514
515 //================================================================================
516 /*!
517  * \brief Allow algo to do something after persistent restoration
518  * \param subMesh - restored submesh
519  *
520  * This method is called only if a submesh has HYP_OK algo_state.
521  */
522 //================================================================================
523
524 void SMESH_Algo::SubmeshRestored(SMESH_subMesh* /*subMesh*/)
525 {
526 }
527
528 //================================================================================
529 /*!
530  * \brief Computes mesh without geometry
531  * \param aMesh - the mesh
532  * \param aHelper - helper that must be used for adding elements to \aaMesh
533  * \retval bool - is a success
534  */
535 //================================================================================
536
537 bool SMESH_Algo::Compute(SMESH_Mesh & /*aMesh*/, SMESH_MesherHelper* /*aHelper*/)
538 {
539   return error( COMPERR_BAD_INPUT_MESH, "Mesh built on shape expected");
540 }
541
542 //================================================================================
543 /*!
544  * \brief store error and comment and then return ( error == COMPERR_OK )
545  */
546 //================================================================================
547
548 bool SMESH_Algo::error(int error, const SMESH_Comment& comment)
549 {
550   _error   = error;
551   _comment = comment;
552   return ( error == COMPERR_OK );
553 }
554
555 //================================================================================
556 /*!
557  * \brief store error and return ( error == COMPERR_OK )
558  */
559 //================================================================================
560
561 bool SMESH_Algo::error(SMESH_ComputeErrorPtr error)
562 {
563   if ( error ) {
564     _error   = error->myName;
565     _comment = error->myComment;
566     _badInputElements = error->myBadElements;
567     return error->IsOK();
568   }
569   return true;
570 }
571
572 //================================================================================
573 /*!
574  * \brief return compute error
575  */
576 //================================================================================
577
578 SMESH_ComputeErrorPtr SMESH_Algo::GetComputeError() const
579 {
580   SMESH_ComputeErrorPtr err = SMESH_ComputeError::New( _error, _comment, this );
581   // hope this method is called by only SMESH_subMesh after this->Compute()
582   err->myBadElements.splice( err->myBadElements.end(),
583                              (list<const SMDS_MeshElement*>&) _badInputElements );
584   return err;
585 }
586
587 //================================================================================
588 /*!
589  * \brief initialize compute error
590  */
591 //================================================================================
592
593 void SMESH_Algo::InitComputeError()
594 {
595   _error = COMPERR_OK;
596   _comment.clear();
597   list<const SMDS_MeshElement*>::iterator elem = _badInputElements.begin();
598   for ( ; elem != _badInputElements.end(); ++elem )
599     if ( (*elem)->GetID() < 1 )
600       delete *elem;
601   _badInputElements.clear();
602 }
603
604 //================================================================================
605 /*!
606  * \brief store a bad input element preventing computation,
607  *        which may be a temporary one i.e. not residing the mesh,
608  *        then it will be deleted by InitComputeError()
609  */
610 //================================================================================
611
612 void SMESH_Algo::addBadInputElement(const SMDS_MeshElement* elem)
613 {
614   if ( elem )
615     _badInputElements.push_back( elem );
616 }