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