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