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