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