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