Salome HOME
Merge 'master' branch into 'V9_dev' branch.
[modules/smesh.git] / src / SMESH / SMESH_Gen.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  SMESH SMESH : implementation of SMESH idl descriptions
24 //  File   : SMESH_Gen.cxx
25 //  Author : Paul RASCLE, EDF
26 //  Module : SMESH
27 //
28
29 //#define CHRONODEF
30
31 #include "SMESH_Gen.hxx"
32
33 #include "SMDS_Mesh.hxx"
34 #include "SMDS_MeshElement.hxx"
35 #include "SMDS_MeshNode.hxx"
36 #include "SMESHDS_Document.hxx"
37 #include "SMESH_HypoFilter.hxx"
38 #include "SMESH_Mesh.hxx"
39 #include "SMESH_MesherHelper.hxx"
40 #include "SMESH_subMesh.hxx"
41
42 #include "utilities.h"
43 #include "OpUtil.hxx"
44 #include "Utils_ExceptHandlers.hxx"
45
46 #include <TopoDS_Iterator.hxx>
47 #include <TopoDS.hxx>
48
49 #include "memoire.h"
50
51 #ifdef WIN32
52   #include <windows.h>
53 #endif
54
55 using namespace std;
56
57 //#include <vtkDebugLeaks.h>
58
59
60 //=============================================================================
61 /*!
62  *  Constructor
63  */
64 //=============================================================================
65
66 SMESH_Gen::SMESH_Gen()
67 {
68   _studyContext = new StudyContextStruct;
69   _studyContext->myDocument = new SMESHDS_Document();
70   _localId = 0;
71   _hypId   = 0;
72   _segmentation = _nbSegments = 10;
73   SMDS_Mesh::_meshList.clear();
74   _compute_canceled = false;
75   //vtkDebugLeaks::SetExitError(0);
76 }
77
78 namespace
79 {
80   // a structure used to nullify SMESH_Gen field of SMESH_Hypothesis,
81   // which is needed for SMESH_Hypothesis not deleted before ~SMESH_Gen()
82   struct _Hyp : public SMESH_Hypothesis
83   {
84     void NullifyGen()
85     {
86       _gen = 0;
87     }
88   };
89 }
90
91 //=============================================================================
92 /*!
93  * Destructor
94  */
95 //=============================================================================
96
97 SMESH_Gen::~SMESH_Gen()
98 {
99     std::map < int, SMESH_Hypothesis * >::iterator i_hyp = _studyContext->mapHypothesis.begin();
100     for ( ; i_hyp != _studyContext->mapHypothesis.end(); ++i_hyp )
101     {
102       if ( _Hyp* h = static_cast< _Hyp*>( i_hyp->second ))
103         h->NullifyGen();
104     }
105   delete _studyContext->myDocument;
106   delete _studyContext;
107 }
108
109 //=============================================================================
110 /*!
111  * Creates a mesh in a study.
112  * if (theIsEmbeddedMode) { mesh modification commands are not logged }
113  */
114 //=============================================================================
115
116 SMESH_Mesh* SMESH_Gen::CreateMesh(bool theIsEmbeddedMode)
117   throw(SALOME_Exception)
118 {
119   Unexpect aCatch(SalomeException);
120
121   // create a new SMESH_mesh object
122   SMESH_Mesh *aMesh = new SMESH_Mesh(_localId++,
123                                      this,
124                                      theIsEmbeddedMode,
125                                      _studyContext->myDocument);
126   _studyContext->mapMesh[_localId-1] = aMesh;
127
128   return aMesh;
129 }
130
131 //=============================================================================
132 /*
133  * Compute a mesh
134  */
135 //=============================================================================
136
137 bool SMESH_Gen::Compute(SMESH_Mesh &          aMesh,
138                         const TopoDS_Shape &  aShape,
139                         const int             aFlags /*= COMPACT_MESH*/,
140                         const ::MeshDimension aDim /*=::MeshDim_3D*/,
141                         TSetOfInt*            aShapesId /*=0*/)
142 {
143   MEMOSTAT;
144
145   const bool   aShapeOnly = aFlags & SHAPE_ONLY;
146   const bool     anUpward = aFlags & UPWARD;
147   const bool aCompactMesh = aFlags & COMPACT_MESH;
148
149   bool ret = true;
150
151   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
152
153   const bool includeSelf = true;
154   const bool complexShapeFirst = true;
155   const int  globalAlgoDim = 100;
156
157   SMESH_subMeshIteratorPtr smIt;
158
159   // Fix of Issue 22150. Due to !BLSURF->OnlyUnaryInput(), BLSURF computes edges
160   // that must be computed by Projection 1D-2D while the Projection asks to compute
161   // one face only.
162   SMESH_subMesh::compute_event computeEvent =
163     aShapeOnly ? SMESH_subMesh::COMPUTE_SUBMESH : SMESH_subMesh::COMPUTE;
164   if ( !aMesh.HasShapeToMesh() )
165     computeEvent = SMESH_subMesh::COMPUTE_NOGEOM; // if several algos and no geometry
166
167   if ( anUpward ) // is called from the below code in this method
168   {
169     // ===============================================
170     // Mesh all the sub-shapes starting from vertices
171     // ===============================================
172
173     smIt = sm->getDependsOnIterator(includeSelf, !complexShapeFirst);
174     while ( smIt->more() )
175     {
176       SMESH_subMesh* smToCompute = smIt->next();
177
178       // do not mesh vertices of a pseudo shape
179       const TopoDS_Shape&        shape = smToCompute->GetSubShape();
180       const TopAbs_ShapeEnum shapeType = shape.ShapeType();
181       if ( !aMesh.HasShapeToMesh() && shapeType == TopAbs_VERTEX )
182         continue;
183
184       // check for preview dimension limitations
185       if ( aShapesId && GetShapeDim( shapeType ) > (int)aDim )
186       {
187         // clear compute state not to show previous compute errors
188         //  if preview invoked less dimension less than previous
189         smToCompute->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
190         continue;
191       }
192
193       if (smToCompute->GetComputeState() == SMESH_subMesh::READY_TO_COMPUTE)
194       {
195         if (_compute_canceled)
196           return false;
197         setCurrentSubMesh( smToCompute );
198         smToCompute->ComputeStateEngine( computeEvent );
199         setCurrentSubMesh( NULL );
200       }
201
202       // we check all the sub-meshes here and detect if any of them failed to compute
203       if (smToCompute->GetComputeState() == SMESH_subMesh::FAILED_TO_COMPUTE &&
204           ( shapeType != TopAbs_EDGE || !SMESH_Algo::isDegenerated( TopoDS::Edge( shape ))))
205         ret = false;
206       else if ( aShapesId )
207         aShapesId->insert( smToCompute->GetId() );
208     }
209     //aMesh.GetMeshDS()->Modified();
210     return ret;
211   }
212   else
213   {
214     // ================================================================
215     // Apply algos that do NOT require discreteized boundaries
216     // ("all-dimensional") and do NOT support sub-meshes, starting from
217     // the most complex shapes and collect sub-meshes with algos that 
218     // DO support sub-meshes
219     // ================================================================
220
221     list< SMESH_subMesh* > smWithAlgoSupportingSubmeshes[4]; // for each dim
222
223     // map to sort sm with same dim algos according to dim of
224     // the shape the algo assigned to (issue 0021217).
225     // Other issues influenced the algo applying order:
226     // 21406, 21556, 21893, 20206
227     multimap< int, SMESH_subMesh* > shDim2sm;
228     multimap< int, SMESH_subMesh* >::reverse_iterator shDim2smIt;
229     TopoDS_Shape algoShape;
230     int prevShapeDim = -1, aShapeDim;
231
232     smIt = sm->getDependsOnIterator(includeSelf, complexShapeFirst);
233     while ( smIt->more() )
234     {
235       SMESH_subMesh* smToCompute = smIt->next();
236       if ( smToCompute->GetComputeState() != SMESH_subMesh::READY_TO_COMPUTE )
237         continue;
238
239       const TopoDS_Shape& aSubShape = smToCompute->GetSubShape();
240       aShapeDim = GetShapeDim( aSubShape );
241       if ( aShapeDim < 1 ) break;
242       
243       // check for preview dimension limitations
244       if ( aShapesId && aShapeDim > (int)aDim )
245         continue;
246
247       SMESH_Algo* algo = GetAlgo( smToCompute, &algoShape );
248       if ( algo && !algo->NeedDiscreteBoundary() )
249       {
250         if ( algo->SupportSubmeshes() )
251         {
252           // reload sub-meshes from shDim2sm into smWithAlgoSupportingSubmeshes
253           // so that more local algos to go first
254           if ( prevShapeDim != aShapeDim )
255           {
256             prevShapeDim = aShapeDim;
257             for ( shDim2smIt = shDim2sm.rbegin(); shDim2smIt != shDim2sm.rend(); ++shDim2smIt )
258               if ( shDim2smIt->first == globalAlgoDim )
259                 smWithAlgoSupportingSubmeshes[ aShapeDim ].push_back( shDim2smIt->second );
260               else
261                 smWithAlgoSupportingSubmeshes[ aShapeDim ].push_front( shDim2smIt->second );
262             shDim2sm.clear();
263           }
264           // add smToCompute to shDim2sm map
265           if ( algoShape.IsSame( aMesh.GetShapeToMesh() ))
266           {
267             aShapeDim = globalAlgoDim; // to compute last
268           }
269           else
270           {
271             aShapeDim = GetShapeDim( algoShape );
272             if ( algoShape.ShapeType() == TopAbs_COMPOUND )
273             {
274               TopoDS_Iterator it( algoShape );
275               aShapeDim += GetShapeDim( it.Value() );
276             }
277           }
278           shDim2sm.insert( make_pair( aShapeDim, smToCompute ));
279         }
280         else // Compute w/o support of sub-meshes
281         {
282           if (_compute_canceled)
283             return false;
284           setCurrentSubMesh( smToCompute );
285           smToCompute->ComputeStateEngine( computeEvent );
286           setCurrentSubMesh( NULL );
287           if ( aShapesId )
288             aShapesId->insert( smToCompute->GetId() );
289         }
290       }
291     }
292     // reload sub-meshes from shDim2sm into smWithAlgoSupportingSubmeshes
293     for ( shDim2smIt = shDim2sm.rbegin(); shDim2smIt != shDim2sm.rend(); ++shDim2smIt )
294       if ( shDim2smIt->first == globalAlgoDim )
295         smWithAlgoSupportingSubmeshes[3].push_back( shDim2smIt->second );
296       else
297         smWithAlgoSupportingSubmeshes[0].push_front( shDim2smIt->second );
298
299     // ======================================================
300     // Apply all-dimensional algorithms supporing sub-meshes
301     // ======================================================
302
303     std::vector< SMESH_subMesh* > smVec;
304     for ( aShapeDim = 0; aShapeDim < 4; ++aShapeDim )
305     {
306       // ------------------------------------------------
307       // sort list of sub-meshes according to mesh order
308       // ------------------------------------------------
309       smVec.assign( smWithAlgoSupportingSubmeshes[ aShapeDim ].begin(),
310                     smWithAlgoSupportingSubmeshes[ aShapeDim ].end() );
311       aMesh.SortByMeshOrder( smVec );
312
313       // ------------------------------------------------------------
314       // compute sub-meshes with local uni-dimensional algos under
315       // sub-meshes with all-dimensional algos
316       // ------------------------------------------------------------
317       // start from lower shapes
318       for ( size_t i = 0; i < smVec.size(); ++i )
319       {
320         sm = smVec[i];
321
322         // get a shape the algo is assigned to
323         if ( !GetAlgo( sm, & algoShape ))
324           continue; // strange...
325
326         // look for more local algos
327         smIt = sm->getDependsOnIterator(!includeSelf, !complexShapeFirst);
328         while ( smIt->more() )
329         {
330           SMESH_subMesh* smToCompute = smIt->next();
331
332           const TopoDS_Shape& aSubShape = smToCompute->GetSubShape();
333           const int aShapeDim = GetShapeDim( aSubShape );
334           //if ( aSubShape.ShapeType() == TopAbs_VERTEX ) continue;
335           if ( aShapeDim < 1 ) continue;
336
337           // check for preview dimension limitations
338           if ( aShapesId && GetShapeDim( aSubShape.ShapeType() ) > (int)aDim )
339             continue;
340
341           SMESH_HypoFilter filter( SMESH_HypoFilter::IsAlgo() );
342           filter
343             .And( SMESH_HypoFilter::IsApplicableTo( aSubShape ))
344             .And( SMESH_HypoFilter::IsMoreLocalThan( algoShape, aMesh ));
345
346           if ( SMESH_Algo* subAlgo = (SMESH_Algo*) aMesh.GetHypothesis( smToCompute, filter, true))
347           {
348             if ( ! subAlgo->NeedDiscreteBoundary() ) continue;
349             SMESH_Hypothesis::Hypothesis_Status status;
350             if ( subAlgo->CheckHypothesis( aMesh, aSubShape, status ))
351               // mesh a lower smToCompute starting from vertices
352               Compute( aMesh, aSubShape, aFlags | SHAPE_ONLY_UPWARD, aDim, aShapesId );
353               // Compute( aMesh, aSubShape, aShapeOnly, /*anUpward=*/true, aDim, aShapesId );
354           }
355         }
356       }
357       // --------------------------------
358       // apply the all-dimensional algos
359       // --------------------------------
360       for ( size_t i = 0; i < smVec.size(); ++i )
361       {
362         sm = smVec[i];
363         if ( sm->GetComputeState() == SMESH_subMesh::READY_TO_COMPUTE)
364         {
365           const TopAbs_ShapeEnum shapeType = sm->GetSubShape().ShapeType();
366           // check for preview dimension limitations
367           if ( aShapesId && GetShapeDim( shapeType ) > (int)aDim )
368             continue;
369
370           if (_compute_canceled)
371             return false;
372           setCurrentSubMesh( sm );
373           sm->ComputeStateEngine( computeEvent );
374           setCurrentSubMesh( NULL );
375           if ( aShapesId )
376             aShapesId->insert( sm->GetId() );
377         }
378       }
379     } // loop on shape dimensions
380
381     // -----------------------------------------------
382     // mesh the rest sub-shapes starting from vertices
383     // -----------------------------------------------
384     ret = Compute( aMesh, aShape, aFlags | UPWARD, aDim, aShapesId );
385   }
386
387   MEMOSTAT;
388
389   // fix quadratic mesh by bending iternal links near concave boundary
390   if ( aCompactMesh && // a final compute
391        aShape.IsSame( aMesh.GetShapeToMesh() ) &&
392        !aShapesId && // not preview
393        ret ) // everything is OK
394   {
395     SMESH_MesherHelper aHelper( aMesh );
396     if ( aHelper.IsQuadraticMesh() != SMESH_MesherHelper::LINEAR )
397     {
398       aHelper.FixQuadraticElements( sm->GetComputeError() );
399     }
400   }
401
402   if ( aCompactMesh )
403     aMesh.GetMeshDS()->compactMesh();
404
405   return ret;
406 }
407
408 //=============================================================================
409 /*!
410  * Prepare Compute a mesh
411  */
412 //=============================================================================
413 void SMESH_Gen::PrepareCompute(SMESH_Mesh &          aMesh,
414                                const TopoDS_Shape &  aShape)
415 {
416   _compute_canceled = false;
417   resetCurrentSubMesh();
418 }
419
420 //=============================================================================
421 /*!
422  * Cancel Compute a mesh
423  */
424 //=============================================================================
425 void SMESH_Gen::CancelCompute(SMESH_Mesh &          aMesh,
426                               const TopoDS_Shape &  aShape)
427 {
428   _compute_canceled = true;
429   if ( const SMESH_subMesh* sm = GetCurrentSubMesh() )
430   {
431     const_cast< SMESH_subMesh* >( sm )->ComputeStateEngine( SMESH_subMesh::COMPUTE_CANCELED );
432   }
433   resetCurrentSubMesh();
434 }
435
436 //================================================================================
437 /*!
438  * \brief Returns a sub-mesh being currently computed
439  */
440 //================================================================================
441
442 const SMESH_subMesh* SMESH_Gen::GetCurrentSubMesh() const
443 {
444   return _sm_current.empty() ? 0 : _sm_current.back();
445 }
446
447 //================================================================================
448 /*!
449  * \brief Sets a sub-mesh being currently computed.
450  *
451  * An algorithm can call Compute() for a sub-shape, hence we keep a stack of sub-meshes
452  */
453 //================================================================================
454
455 void SMESH_Gen::setCurrentSubMesh(SMESH_subMesh* sm)
456 {
457   if ( sm )
458     _sm_current.push_back( sm );
459
460   else if ( !_sm_current.empty() )
461     _sm_current.pop_back();
462 }
463
464 void SMESH_Gen::resetCurrentSubMesh()
465 {
466   _sm_current.clear();
467 }
468
469 //=============================================================================
470 /*!
471  * Evaluate a mesh
472  */
473 //=============================================================================
474
475 bool SMESH_Gen::Evaluate(SMESH_Mesh &          aMesh,
476                          const TopoDS_Shape &  aShape,
477                          MapShapeNbElems&      aResMap,
478                          const bool            anUpward,
479                          TSetOfInt*            aShapesId)
480 {
481   bool ret = true;
482
483   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
484
485   const bool includeSelf = true;
486   const bool complexShapeFirst = true;
487   SMESH_subMeshIteratorPtr smIt;
488
489   if ( anUpward ) { // is called from below code here
490     // -----------------------------------------------
491     // mesh all the sub-shapes starting from vertices
492     // -----------------------------------------------
493     smIt = sm->getDependsOnIterator(includeSelf, !complexShapeFirst);
494     while ( smIt->more() ) {
495       SMESH_subMesh* smToCompute = smIt->next();
496
497       // do not mesh vertices of a pseudo shape
498       const TopAbs_ShapeEnum shapeType = smToCompute->GetSubShape().ShapeType();
499       //if ( !aMesh.HasShapeToMesh() && shapeType == TopAbs_VERTEX )
500       //  continue;
501       if ( !aMesh.HasShapeToMesh() ) {
502         if( shapeType == TopAbs_VERTEX || shapeType == TopAbs_WIRE ||
503             shapeType == TopAbs_SHELL )
504           continue;
505       }
506
507       smToCompute->Evaluate(aResMap);
508       if( aShapesId )
509         aShapesId->insert( smToCompute->GetId() );
510     }
511     return ret;
512   }
513   else {
514     // -----------------------------------------------------------------
515     // apply algos that DO NOT require Discreteized boundaries and DO NOT
516     // support sub-meshes, starting from the most complex shapes
517     // and collect sub-meshes with algos that DO support sub-meshes
518     // -----------------------------------------------------------------
519     list< SMESH_subMesh* > smWithAlgoSupportingSubmeshes;
520     smIt = sm->getDependsOnIterator(includeSelf, complexShapeFirst);
521     while ( smIt->more() ) {
522       SMESH_subMesh* smToCompute = smIt->next();
523       const TopoDS_Shape& aSubShape = smToCompute->GetSubShape();
524       const int aShapeDim = GetShapeDim( aSubShape );
525       if ( aShapeDim < 1 ) break;
526       
527       SMESH_Algo* algo = GetAlgo( smToCompute );
528       if ( algo && !algo->NeedDiscreteBoundary() ) {
529         if ( algo->SupportSubmeshes() ) {
530           smWithAlgoSupportingSubmeshes.push_front( smToCompute );
531         }
532         else {
533           smToCompute->Evaluate(aResMap);
534           if ( aShapesId )
535             aShapesId->insert( smToCompute->GetId() );
536         }
537       }
538     }
539
540     // ------------------------------------------------------------
541     // sort list of meshes according to mesh order
542     // ------------------------------------------------------------
543     std::vector< SMESH_subMesh* > smVec( smWithAlgoSupportingSubmeshes.begin(),
544                                          smWithAlgoSupportingSubmeshes.end() );
545     aMesh.SortByMeshOrder( smVec );
546
547     // ------------------------------------------------------------
548     // compute sub-meshes under shapes with algos that DO NOT require
549     // Discreteized boundaries and DO support sub-meshes
550     // ------------------------------------------------------------
551     // start from lower shapes
552     for ( size_t i = 0; i < smVec.size(); ++i )
553     {
554       sm = smVec[i];
555
556       // get a shape the algo is assigned to
557       TopoDS_Shape algoShape;
558       if ( !GetAlgo( sm, & algoShape ))
559         continue; // strange...
560
561       // look for more local algos
562       smIt = sm->getDependsOnIterator(!includeSelf, !complexShapeFirst);
563       while ( smIt->more() ) {
564         SMESH_subMesh* smToCompute = smIt->next();
565
566         const TopoDS_Shape& aSubShape = smToCompute->GetSubShape();
567         const int aShapeDim = GetShapeDim( aSubShape );
568         if ( aShapeDim < 1 ) continue;
569
570         SMESH_HypoFilter filter( SMESH_HypoFilter::IsAlgo() );
571         filter
572           .And( SMESH_HypoFilter::IsApplicableTo( aSubShape ))
573           .And( SMESH_HypoFilter::IsMoreLocalThan( algoShape, aMesh ));
574
575         if ( SMESH_Algo* subAlgo = (SMESH_Algo*) aMesh.GetHypothesis( smToCompute, filter, true ))
576         {
577           if ( ! subAlgo->NeedDiscreteBoundary() ) continue;
578           SMESH_Hypothesis::Hypothesis_Status status;
579           if ( subAlgo->CheckHypothesis( aMesh, aSubShape, status ))
580             // mesh a lower smToCompute starting from vertices
581             Evaluate( aMesh, aSubShape, aResMap, /*anUpward=*/true, aShapesId );
582         }
583       }
584     }
585     // ----------------------------------------------------------
586     // apply the algos that do not require Discreteized boundaries
587     // ----------------------------------------------------------
588     for ( size_t i = 0; i < smVec.size(); ++i )
589     {
590       sm = smVec[i];
591       sm->Evaluate(aResMap);
592       if ( aShapesId )
593         aShapesId->insert( sm->GetId() );
594     }
595
596     // -----------------------------------------------
597     // mesh the rest sub-shapes starting from vertices
598     // -----------------------------------------------
599     ret = Evaluate( aMesh, aShape, aResMap, /*anUpward=*/true, aShapesId );
600   }
601
602   return ret;
603 }
604
605
606 //=======================================================================
607 //function : checkConformIgnoredAlgos
608 //purpose  :
609 //=======================================================================
610
611 static bool checkConformIgnoredAlgos(SMESH_Mesh&               aMesh,
612                                      SMESH_subMesh*            aSubMesh,
613                                      const SMESH_Algo*         aGlobIgnoAlgo,
614                                      const SMESH_Algo*         aLocIgnoAlgo,
615                                      bool &                    checkConform,
616                                      set<SMESH_subMesh*>&      aCheckedMap,
617                                      list< SMESH_Gen::TAlgoStateError > & theErrors)
618 {
619   ASSERT( aSubMesh );
620   if ( aSubMesh->GetSubShape().ShapeType() == TopAbs_VERTEX)
621     return true;
622
623
624   bool ret = true;
625
626   const list<const SMESHDS_Hypothesis*>& listHyp =
627     aMesh.GetMeshDS()->GetHypothesis( aSubMesh->GetSubShape() );
628   list<const SMESHDS_Hypothesis*>::const_iterator it=listHyp.begin();
629   for ( ; it != listHyp.end(); it++)
630   {
631     const SMESHDS_Hypothesis * aHyp = *it;
632     if (aHyp->GetType() == SMESHDS_Hypothesis::PARAM_ALGO)
633       continue;
634
635     const SMESH_Algo* algo = dynamic_cast<const SMESH_Algo*> (aHyp);
636     ASSERT ( algo );
637
638     if ( aLocIgnoAlgo ) // algo is hidden by a local algo of upper dim
639     {
640       theErrors.push_back( SMESH_Gen::TAlgoStateError() );
641       theErrors.back().Set( SMESH_Hypothesis::HYP_HIDDEN_ALGO, algo, false );
642       INFOS( "Local <" << algo->GetName() << "> is hidden by local <"
643             << aLocIgnoAlgo->GetName() << ">");
644     }
645     else
646     {
647       bool       isGlobal = (aMesh.IsMainShape( aSubMesh->GetSubShape() ));
648       int             dim = algo->GetDim();
649       int aMaxGlobIgnoDim = ( aGlobIgnoAlgo ? aGlobIgnoAlgo->GetDim() : -1 );
650       bool    isNeededDim = ( aGlobIgnoAlgo ? aGlobIgnoAlgo->NeedLowerHyps( dim ) : false );
651
652       if (( dim < aMaxGlobIgnoDim && !isNeededDim ) &&
653           ( isGlobal || !aGlobIgnoAlgo->SupportSubmeshes() ))
654       {
655         // algo is hidden by a global algo
656         theErrors.push_back( SMESH_Gen::TAlgoStateError() );
657         theErrors.back().Set( SMESH_Hypothesis::HYP_HIDDEN_ALGO, algo, true );
658         INFOS( ( isGlobal ? "Global" : "Local" )
659               << " <" << algo->GetName() << "> is hidden by global <"
660               << aGlobIgnoAlgo->GetName() << ">");
661       }
662       else if ( !algo->NeedDiscreteBoundary() && !isGlobal)
663       {
664         // local algo is not hidden and hides algos on sub-shapes
665         if (checkConform && !aSubMesh->IsConform( algo ))
666         {
667           ret = false;
668           checkConform = false; // no more check conformity
669           INFOS( "ERROR: Local <" << algo->GetName() <<
670                 "> would produce not conform mesh: "
671                 "<Not Conform Mesh Allowed> hypotesis is missing");
672           theErrors.push_back( SMESH_Gen::TAlgoStateError() );
673           theErrors.back().Set( SMESH_Hypothesis::HYP_NOTCONFORM, algo, false );
674         }
675
676         // sub-algos will be hidden by a local <algo> if <algo> does not support sub-meshes
677         if ( algo->SupportSubmeshes() )
678           algo = 0;
679         SMESH_subMeshIteratorPtr revItSub =
680           aSubMesh->getDependsOnIterator( /*includeSelf=*/false, /*complexShapeFirst=*/true);
681         bool checkConform2 = false;
682         while ( revItSub->more() )
683         {
684           SMESH_subMesh* sm = revItSub->next();
685           checkConformIgnoredAlgos (aMesh, sm, aGlobIgnoAlgo,
686                                     algo, checkConform2, aCheckedMap, theErrors);
687           aCheckedMap.insert( sm );
688         }
689       }
690     }
691   }
692
693   return ret;
694 }
695
696 //=======================================================================
697 //function : checkMissing
698 //purpose  : notify on missing hypothesis
699 //           Return false if algo or hipothesis is missing
700 //=======================================================================
701
702 static bool checkMissing(SMESH_Gen*                aGen,
703                          SMESH_Mesh&               aMesh,
704                          SMESH_subMesh*            aSubMesh,
705                          const int                 aTopAlgoDim,
706                          bool*                     globalChecked,
707                          const bool                checkNoAlgo,
708                          set<SMESH_subMesh*>&      aCheckedMap,
709                          list< SMESH_Gen::TAlgoStateError > & theErrors)
710 {
711   switch ( aSubMesh->GetSubShape().ShapeType() )
712   {
713   case TopAbs_EDGE:
714   case TopAbs_FACE:
715   case TopAbs_SOLID: break; // check this sub-mesh, it can be meshed
716   default:
717     return true; // not meshable sub-mesh
718   }
719   if ( aCheckedMap.count( aSubMesh ))
720     return true;
721
722   int ret = true;
723   SMESH_Algo* algo = 0;
724
725   switch (aSubMesh->GetAlgoState())
726   {
727   case SMESH_subMesh::NO_ALGO: {
728     if (checkNoAlgo)
729     {
730       // should there be any algo?
731       int shapeDim = SMESH_Gen::GetShapeDim( aSubMesh->GetSubShape() );
732       if (aTopAlgoDim > shapeDim)
733       {
734         MESSAGE( "ERROR: " << shapeDim << "D algorithm is missing" );
735         ret = false;
736         theErrors.push_back( SMESH_Gen::TAlgoStateError() );
737         theErrors.back().Set( SMESH_Hypothesis::HYP_MISSING, shapeDim, true );
738       }
739     }
740     return ret;
741   }
742   case SMESH_subMesh::MISSING_HYP: {
743     // notify if an algo missing hyp is attached to aSubMesh
744     algo = aSubMesh->GetAlgo();
745     ASSERT( algo );
746     bool IsGlobalHypothesis = aGen->IsGlobalHypothesis( algo, aMesh );
747     if (!IsGlobalHypothesis || !globalChecked[ algo->GetDim() ])
748     {
749       TAlgoStateErrorName errName = SMESH_Hypothesis::HYP_MISSING;
750       SMESH_Hypothesis::Hypothesis_Status status;
751       algo->CheckHypothesis( aMesh, aSubMesh->GetSubShape(), status );
752       if ( status == SMESH_Hypothesis::HYP_BAD_PARAMETER ) {
753         MESSAGE( "ERROR: hypothesis of " << (IsGlobalHypothesis ? "Global " : "Local ")
754                  << "<" << algo->GetName() << "> has a bad parameter value");
755         errName = status;
756       } else if ( status == SMESH_Hypothesis::HYP_BAD_GEOMETRY ) {
757         MESSAGE( "ERROR: " << (IsGlobalHypothesis ? "Global " : "Local ")
758                  << "<" << algo->GetName() << "> assigned to mismatching geometry");
759         errName = status;
760       } else {
761         MESSAGE( "ERROR: " << (IsGlobalHypothesis ? "Global " : "Local ")
762                  << "<" << algo->GetName() << "> misses some hypothesis");
763       }
764       if (IsGlobalHypothesis)
765         globalChecked[ algo->GetDim() ] = true;
766       theErrors.push_back( SMESH_Gen::TAlgoStateError() );
767       theErrors.back().Set( errName, algo, IsGlobalHypothesis );
768     }
769     ret = false;
770     break;
771   }
772   case SMESH_subMesh::HYP_OK:
773     algo = aSubMesh->GetAlgo();
774     ret = true;
775     if (!algo->NeedDiscreteBoundary())
776     {
777       SMESH_subMeshIteratorPtr itsub = aSubMesh->getDependsOnIterator( /*includeSelf=*/false,
778                                                                        /*complexShapeFirst=*/false);
779       while ( itsub->more() )
780         aCheckedMap.insert( itsub->next() );
781     }
782     break;
783   default: ASSERT(0);
784   }
785
786   // do not check under algo that hides sub-algos or
787   // re-start checking NO_ALGO state
788   ASSERT (algo);
789   bool isTopLocalAlgo =
790     ( aTopAlgoDim <= algo->GetDim() && !aGen->IsGlobalHypothesis( algo, aMesh ));
791   if (!algo->NeedDiscreteBoundary() || isTopLocalAlgo)
792   {
793     bool checkNoAlgo2 = ( algo->NeedDiscreteBoundary() );
794     SMESH_subMeshIteratorPtr itsub = aSubMesh->getDependsOnIterator( /*includeSelf=*/false,
795                                                                      /*complexShapeFirst=*/true);
796     while ( itsub->more() )
797     {
798       // sub-meshes should not be checked further more
799       SMESH_subMesh* sm = itsub->next();
800
801       if (isTopLocalAlgo)
802       {
803         //check algo on sub-meshes
804         int aTopAlgoDim2 = algo->GetDim();
805         if (!checkMissing (aGen, aMesh, sm, aTopAlgoDim2,
806                            globalChecked, checkNoAlgo2, aCheckedMap, theErrors))
807         {
808           ret = false;
809           if (sm->GetAlgoState() == SMESH_subMesh::NO_ALGO )
810             checkNoAlgo2 = false;
811         }
812       }
813       aCheckedMap.insert( sm );
814     }
815   }
816   return ret;
817 }
818
819 //=======================================================================
820 //function : CheckAlgoState
821 //purpose  : notify on bad state of attached algos, return false
822 //           if Compute() would fail because of some algo bad state
823 //=======================================================================
824
825 bool SMESH_Gen::CheckAlgoState(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape)
826 {
827   list< TAlgoStateError > errors;
828   return GetAlgoState( aMesh, aShape, errors );
829 }
830
831 //=======================================================================
832 //function : GetAlgoState
833 //purpose  : notify on bad state of attached algos, return false
834 //           if Compute() would fail because of some algo bad state
835 //           theErrors list contains problems description
836 //=======================================================================
837
838 bool SMESH_Gen::GetAlgoState(SMESH_Mesh&               theMesh,
839                              const TopoDS_Shape&       theShape,
840                              list< TAlgoStateError > & theErrors)
841 {
842   bool ret = true;
843   bool hasAlgo = false;
844
845   SMESH_subMesh*          sm = theMesh.GetSubMesh(theShape);
846   const SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
847   TopoDS_Shape     mainShape = meshDS->ShapeToMesh();
848
849   // -----------------
850   // get global algos
851   // -----------------
852
853   const SMESH_Algo* aGlobAlgoArr[] = {0,0,0,0};
854
855   const list<const SMESHDS_Hypothesis*>& listHyp = meshDS->GetHypothesis( mainShape );
856   list<const SMESHDS_Hypothesis*>::const_iterator it=listHyp.begin();
857   for ( ; it != listHyp.end(); it++)
858   {
859     const SMESHDS_Hypothesis * aHyp = *it;
860     if (aHyp->GetType() == SMESHDS_Hypothesis::PARAM_ALGO)
861       continue;
862
863     const SMESH_Algo* algo = dynamic_cast<const SMESH_Algo*> (aHyp);
864     ASSERT ( algo );
865
866     int dim = algo->GetDim();
867     aGlobAlgoArr[ dim ] = algo;
868
869     hasAlgo = true;
870   }
871
872   // --------------------------------------------------------
873   // info on algos that will be ignored because of ones that
874   // don't NeedDiscreteBoundary() attached to super-shapes,
875   // check that a conform mesh will be produced
876   // --------------------------------------------------------
877
878
879   // find a global algo possibly hiding sub-algos
880   int dim;
881   const SMESH_Algo* aGlobIgnoAlgo = 0;
882   for (dim = 3; dim > 0; dim--)
883   {
884     if (aGlobAlgoArr[ dim ] &&
885         !aGlobAlgoArr[ dim ]->NeedDiscreteBoundary() /*&&
886         !aGlobAlgoArr[ dim ]->SupportSubmeshes()*/ )
887     {
888       aGlobIgnoAlgo = aGlobAlgoArr[ dim ];
889       break;
890     }
891   }
892
893   set<SMESH_subMesh*> aCheckedSubs;
894   bool checkConform = ( !theMesh.IsNotConformAllowed() );
895
896   // loop on theShape and its sub-shapes
897   SMESH_subMeshIteratorPtr revItSub = sm->getDependsOnIterator( /*includeSelf=*/true,
898                                                                 /*complexShapeFirst=*/true);
899   while ( revItSub->more() )
900   {
901     SMESH_subMesh* smToCheck = revItSub->next();
902     if ( smToCheck->GetSubShape().ShapeType() == TopAbs_VERTEX)
903       break;
904
905     if ( aCheckedSubs.insert( smToCheck ).second ) // not yet checked
906       if (!checkConformIgnoredAlgos (theMesh, smToCheck, aGlobIgnoAlgo,
907                                      0, checkConform, aCheckedSubs, theErrors))
908         ret = false;
909
910     if ( smToCheck->GetAlgoState() != SMESH_subMesh::NO_ALGO )
911       hasAlgo = true;
912   }
913
914   // ----------------------------------------------------------------
915   // info on missing hypothesis and find out if all needed algos are
916   // well defined
917   // ----------------------------------------------------------------
918
919   // find max dim of global algo
920   int aTopAlgoDim = 0;
921   for (dim = 3; dim > 0; dim--)
922   {
923     if (aGlobAlgoArr[ dim ])
924     {
925       aTopAlgoDim = dim;
926       break;
927     }
928   }
929   bool checkNoAlgo = theMesh.HasShapeToMesh() ? bool( aTopAlgoDim ) : false;
930   bool globalChecked[] = { false, false, false, false };
931
932   // loop on theShape and its sub-shapes
933   aCheckedSubs.clear();
934   revItSub = sm->getDependsOnIterator( /*includeSelf=*/true, /*complexShapeFirst=*/true);
935   while ( revItSub->more() )
936   {
937     SMESH_subMesh* smToCheck = revItSub->next();
938     if ( smToCheck->GetSubShape().ShapeType() == TopAbs_VERTEX)
939       break;
940
941     if (!checkMissing (this, theMesh, smToCheck, aTopAlgoDim,
942                        globalChecked, checkNoAlgo, aCheckedSubs, theErrors))
943     {
944       ret = false;
945       if (smToCheck->GetAlgoState() == SMESH_subMesh::NO_ALGO )
946         checkNoAlgo = false;
947     }
948   }
949
950   if ( !hasAlgo ) {
951     ret = false;
952     theErrors.push_back( TAlgoStateError() );
953     theErrors.back().Set( SMESH_Hypothesis::HYP_MISSING, theMesh.HasShapeToMesh() ? 1 : 3, true );
954   }
955
956   return ret;
957 }
958
959 //=======================================================================
960 //function : IsGlobalHypothesis
961 //purpose  : check if theAlgo is attached to the main shape
962 //=======================================================================
963
964 bool SMESH_Gen::IsGlobalHypothesis(const SMESH_Hypothesis* theHyp, SMESH_Mesh& aMesh)
965 {
966   SMESH_HypoFilter filter( SMESH_HypoFilter::Is( theHyp ));
967   return aMesh.GetHypothesis( aMesh.GetMeshDS()->ShapeToMesh(), filter, false );
968 }
969
970 //================================================================================
971 /*!
972  * \brief Return paths to xml files of plugins
973  */
974 //================================================================================
975
976 std::vector< std::string > SMESH_Gen::GetPluginXMLPaths()
977 {
978   // Get paths to xml files of plugins
979   vector< string > xmlPaths;
980   string sep;
981   if ( const char* meshersList = getenv("SMESH_MeshersList") )
982   {
983     string meshers = meshersList, plugin;
984     string::size_type from = 0, pos;
985     while ( from < meshers.size() )
986     {
987       // cut off plugin name
988       pos = meshers.find( ':', from );
989       if ( pos != string::npos )
990         plugin = meshers.substr( from, pos-from );
991       else
992         plugin = meshers.substr( from ), pos = meshers.size();
993       from = pos + 1;
994
995       // get PLUGIN_ROOT_DIR path
996       string rootDirVar, pluginSubDir = plugin;
997       if ( plugin == "StdMeshers" )
998         rootDirVar = "SMESH", pluginSubDir = "smesh";
999       else
1000         for ( pos = 0; pos < plugin.size(); ++pos )
1001           rootDirVar += toupper( plugin[pos] );
1002       rootDirVar += "_ROOT_DIR";
1003
1004       const char* rootDir = getenv( rootDirVar.c_str() );
1005       if ( !rootDir || strlen(rootDir) == 0 )
1006       {
1007         rootDirVar = plugin + "_ROOT_DIR"; // HexoticPLUGIN_ROOT_DIR
1008         rootDir = getenv( rootDirVar.c_str() );
1009         if ( !rootDir || strlen(rootDir) == 0 ) continue;
1010       }
1011
1012       // get a separator from rootDir
1013       for ( pos = strlen( rootDir )-1; pos >= 0 && sep.empty(); --pos )
1014         if ( rootDir[pos] == '/' || rootDir[pos] == '\\' )
1015         {
1016           sep = rootDir[pos];
1017           break;
1018         }
1019 #ifdef WIN32
1020       if (sep.empty() ) sep = "\\";
1021 #else
1022       if (sep.empty() ) sep = "/";
1023 #endif
1024
1025       // get a path to resource file
1026       string xmlPath = rootDir;
1027       if ( xmlPath[ xmlPath.size()-1 ] != sep[0] )
1028         xmlPath += sep;
1029       xmlPath += "share" + sep + "salome" + sep + "resources" + sep;
1030       for ( pos = 0; pos < pluginSubDir.size(); ++pos )
1031         xmlPath += tolower( pluginSubDir[pos] );
1032       xmlPath += sep + plugin + ".xml";
1033       bool fileOK;
1034 #ifdef WIN32
1035       fileOK = (GetFileAttributes(xmlPath.c_str()) != INVALID_FILE_ATTRIBUTES);
1036 #else
1037       fileOK = (access(xmlPath.c_str(), F_OK) == 0);
1038 #endif
1039       if ( fileOK )
1040         xmlPaths.push_back( xmlPath );
1041     }
1042   }
1043
1044   return xmlPaths;
1045 }
1046
1047 //=============================================================================
1048 /*!
1049  * Finds algo to mesh a shape. Optionally returns a shape the found algo is bound to
1050  */
1051 //=============================================================================
1052
1053 SMESH_Algo *SMESH_Gen::GetAlgo(SMESH_Mesh &         aMesh,
1054                                const TopoDS_Shape & aShape,
1055                                TopoDS_Shape*        assignedTo)
1056 {
1057   return GetAlgo( aMesh.GetSubMesh( aShape ), assignedTo );
1058 }
1059
1060 //=============================================================================
1061 /*!
1062  * Finds algo to mesh a sub-mesh. Optionally returns a shape the found algo is bound to
1063  */
1064 //=============================================================================
1065
1066 SMESH_Algo *SMESH_Gen::GetAlgo(SMESH_subMesh * aSubMesh,
1067                                TopoDS_Shape*   assignedTo)
1068 {
1069   if ( !aSubMesh ) return 0;
1070
1071   const TopoDS_Shape & aShape = aSubMesh->GetSubShape();
1072   SMESH_Mesh&          aMesh  = *aSubMesh->GetFather();
1073
1074   SMESH_HypoFilter filter( SMESH_HypoFilter::IsAlgo() );
1075   if ( aMesh.HasShapeToMesh() )
1076     filter.And( filter.IsApplicableTo( aShape ));
1077
1078   typedef SMESH_Algo::Features AlgoData;
1079
1080   TopoDS_Shape assignedToShape;
1081   SMESH_Algo* algo =
1082     (SMESH_Algo*) aMesh.GetHypothesis( aSubMesh, filter, true, &assignedToShape );
1083
1084   if ( algo &&
1085        aShape.ShapeType() == TopAbs_FACE &&
1086        !aShape.IsSame( assignedToShape ) &&
1087        SMESH_MesherHelper::NbAncestors( aShape, aMesh, TopAbs_SOLID ) > 1 )
1088   {
1089     // Issue 0021559. If there is another 2D algo with different types of output
1090     // elements that can be used to mesh aShape, and 3D algos on adjacent SOLIDs
1091     // have different types of input elements, we choose a most appropriate 2D algo.
1092
1093     // try to find a concurrent 2D algo
1094     filter.AndNot( filter.Is( algo ));
1095     TopoDS_Shape assignedToShape2;
1096     SMESH_Algo* algo2 =
1097       (SMESH_Algo*) aMesh.GetHypothesis( aSubMesh, filter, true, &assignedToShape2 );
1098     if ( algo2 &&                                                  // algo found
1099          !assignedToShape2.IsSame( aMesh.GetShapeToMesh() ) &&     // algo is local
1100          ( SMESH_MesherHelper::GetGroupType( assignedToShape2 ) == // algo of the same level
1101            SMESH_MesherHelper::GetGroupType( assignedToShape )) &&
1102          aMesh.IsOrderOK( aMesh.GetSubMesh( assignedToShape2 ),    // no forced order
1103                           aMesh.GetSubMesh( assignedToShape  )))
1104     {
1105       // get algos on the adjacent SOLIDs
1106       filter.Init( filter.IsAlgo() ).And( filter.HasDim( 3 ));
1107       vector< SMESH_Algo* > algos3D;
1108       PShapeIteratorPtr solidIt = SMESH_MesherHelper::GetAncestors( aShape, aMesh,
1109                                                                     TopAbs_SOLID );
1110       while ( const TopoDS_Shape* solid = solidIt->next() )
1111         if ( SMESH_Algo* algo3D = (SMESH_Algo*) aMesh.GetHypothesis( *solid, filter, true ))
1112         {
1113           algos3D.push_back( algo3D );
1114           filter.AndNot( filter.HasName( algo3D->GetName() ));
1115         }
1116       // check compatibility of algos
1117       if ( algos3D.size() > 1 )
1118       {
1119         const AlgoData& algoData    = algo->SMESH_Algo::GetFeatures();
1120         const AlgoData& algoData2   = algo2->SMESH_Algo::GetFeatures();
1121         const AlgoData& algoData3d0 = algos3D[0]->SMESH_Algo::GetFeatures();
1122         const AlgoData& algoData3d1 = algos3D[1]->SMESH_Algo::GetFeatures();
1123         if (( algoData2.IsCompatible( algoData3d0 ) &&
1124               algoData2.IsCompatible( algoData3d1 ))
1125             &&
1126             !(algoData.IsCompatible( algoData3d0 ) &&
1127               algoData.IsCompatible( algoData3d1 )))
1128           algo = algo2;
1129       }
1130     }
1131   }
1132
1133   if ( assignedTo && algo )
1134     * assignedTo = assignedToShape;
1135
1136   return algo;
1137 }
1138
1139 //=============================================================================
1140 /*!
1141  * Returns StudyContextStruct for a study
1142  */
1143 //=============================================================================
1144
1145 StudyContextStruct *SMESH_Gen::GetStudyContext()
1146 {
1147   return _studyContext;
1148 }
1149
1150 //================================================================================
1151 /*!
1152  * \brief Return shape dimension by TopAbs_ShapeEnum
1153  */
1154 //================================================================================
1155
1156 int SMESH_Gen::GetShapeDim(const TopAbs_ShapeEnum & aShapeType)
1157 {
1158   static vector<int> dim;
1159   if ( dim.empty() )
1160   {
1161     dim.resize( TopAbs_SHAPE, -1 );
1162     dim[ TopAbs_COMPOUND ]  = MeshDim_3D;
1163     dim[ TopAbs_COMPSOLID ] = MeshDim_3D;
1164     dim[ TopAbs_SOLID ]     = MeshDim_3D;
1165     dim[ TopAbs_SHELL ]     = MeshDim_2D;
1166     dim[ TopAbs_FACE  ]     = MeshDim_2D;
1167     dim[ TopAbs_WIRE ]      = MeshDim_1D;
1168     dim[ TopAbs_EDGE ]      = MeshDim_1D;
1169     dim[ TopAbs_VERTEX ]    = MeshDim_0D;
1170   }
1171   return dim[ aShapeType ];
1172 }
1173
1174 //=============================================================================
1175 /*!
1176  * Genarate a new id unique within this Gen
1177  */
1178 //=============================================================================
1179
1180 int SMESH_Gen::GetANewId()
1181 {
1182   return _hypId++;
1183 }