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