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