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