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