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