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