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