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