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