Salome HOME
0021803: EDF 2351 : Available versions of MED in TUI function ExportMED aren't consis...
[modules/smesh.git] / src / SMESH / SMESH_Mesh.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 //  File   : SMESH_Mesh.cxx
24 //  Author : Paul RASCLE, EDF
25 //  Module : SMESH
26 //
27 #include "SMESH_Mesh.hxx"
28 #include "SMESH_MesherHelper.hxx"
29 #include "SMDS_MeshVolume.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Document.hxx"
32 #include "SMESHDS_Group.hxx"
33 #include "SMESHDS_GroupOnGeom.hxx"
34 #include "SMESHDS_Script.hxx"
35 #include "SMESHDS_TSubMeshHolder.hxx"
36 #include "SMESH_Gen.hxx"
37 #include "SMESH_Group.hxx"
38 #include "SMESH_HypoFilter.hxx"
39 #include "SMESH_Hypothesis.hxx"
40 #include "SMESH_subMesh.hxx"
41
42 #include "utilities.h"
43
44 #include "DriverDAT_W_SMDS_Mesh.h"
45 #include "DriverGMF_Read.hxx"
46 #include "DriverGMF_Write.hxx"
47 #include "DriverMED_R_SMESHDS_Mesh.h"
48 #include "DriverMED_W_SMESHDS_Mesh.h"
49 #include "DriverSTL_R_SMDS_Mesh.h"
50 #include "DriverSTL_W_SMDS_Mesh.h"
51 #include "DriverUNV_R_SMDS_Mesh.h"
52 #include "DriverUNV_W_SMDS_Mesh.h"
53 #ifdef WITH_CGNS
54 #include "DriverCGNS_Read.hxx"
55 #include "DriverCGNS_Write.hxx"
56 #endif
57
58 #include <GEOMUtils.hxx>
59
60 #undef _Precision_HeaderFile
61 #include <BRepBndLib.hxx>
62 #include <BRepPrimAPI_MakeBox.hxx>
63 #include <Bnd_Box.hxx>
64 #include <TColStd_MapOfInteger.hxx>
65 #include <TopExp.hxx>
66 #include <TopExp_Explorer.hxx>
67 #include <TopTools_ListIteratorOfListOfShape.hxx>
68 #include <TopTools_ListOfShape.hxx>
69 #include <TopTools_MapOfShape.hxx>
70 #include <TopoDS_Iterator.hxx>
71
72 #include "SMESH_TryCatch.hxx" // include after OCCT headers!
73
74 #include "Utils_ExceptHandlers.hxx"
75
76 #ifndef WIN32
77 #include <boost/thread/thread.hpp>
78 #include <boost/bind.hpp>
79 #else 
80 #include <pthread.h>
81 #endif
82
83 using namespace std;
84
85 // maximum stored group name length in MED file
86 #define MAX_MED_GROUP_NAME_LENGTH 80
87
88 #ifdef _DEBUG_
89 static int MYDEBUG = 0;
90 #else
91 static int MYDEBUG = 0;
92 #endif
93
94 #define cSMESH_Hyp(h) static_cast<const SMESH_Hypothesis*>(h)
95
96 typedef SMESH_HypoFilter THypType;
97
98 class SMESH_Mesh::SubMeshHolder : public SMESHDS_TSubMeshHolder< SMESH_subMesh >
99 {
100 };
101
102 //=============================================================================
103 /*!
104  * 
105  */
106 //=============================================================================
107
108 SMESH_Mesh::SMESH_Mesh(int               theLocalId, 
109                        SMESH_Gen*        theGen,
110                        bool              theIsEmbeddedMode,
111                        SMESHDS_Document* theDocument):
112   _groupId( 0 ), _nbSubShapes( 0 )
113 {
114   if(MYDEBUG) MESSAGE("SMESH_Mesh::SMESH_Mesh(int localId)");
115   _id            = theLocalId;
116   _gen           = theGen;
117   _myDocument    = theDocument;
118   _myMeshDS      = theDocument->NewMesh(theIsEmbeddedMode,theLocalId);
119   _isShapeToMesh = false;
120   _isAutoColor   = false;
121   _isModified    = false;
122   _shapeDiagonal = 0.0;
123   _callUp        = NULL;
124   _myMeshDS->ShapeToMesh( PseudoShape() );
125   _subMeshHolder = new SubMeshHolder;
126 }
127
128 //================================================================================
129 /*!
130  * \brief Constructor of SMESH_Mesh being a base of some descendant class
131  */
132 //================================================================================
133
134 SMESH_Mesh::SMESH_Mesh():
135   _id(-1),
136   _groupId( 0 ),
137   _nbSubShapes( 0 ),
138   _isShapeToMesh( false ),
139   _myDocument( 0 ),
140   _myMeshDS( 0 ),
141   _gen( 0 ),
142   _isAutoColor( false ),
143   _isModified( false ),
144   _shapeDiagonal( 0.0 ),
145   _callUp( 0 )
146 {
147   _subMeshHolder = new SubMeshHolder;
148 }
149
150 namespace
151 {
152 #ifndef WIN32
153   void deleteMeshDS(SMESHDS_Mesh* meshDS)
154   {
155     //cout << "deleteMeshDS( " << meshDS << endl;
156     delete meshDS;
157   }
158 #else
159   static void* deleteMeshDS(void* meshDS)
160   {
161     //cout << "deleteMeshDS( " << meshDS << endl;
162     SMESHDS_Mesh* m = (SMESHDS_Mesh*)meshDS;
163     if(m) {
164       delete m;
165     }
166     return 0;
167   }
168 #endif
169 }
170
171 //=============================================================================
172 /*!
173  *
174  */
175 //=============================================================================
176
177 SMESH_Mesh::~SMESH_Mesh()
178 {
179   if(MYDEBUG) MESSAGE("SMESH_Mesh::~SMESH_Mesh");
180
181   // avoid usual removal of elements while processing RemoveHypothesis( algo ) event
182   SMESHDS_SubMeshIteratorPtr smIt = _myMeshDS->SubMeshes();
183   while ( smIt->more() )
184     const_cast<SMESHDS_SubMesh*>( smIt->next() )->Clear();
185
186   // issue 0020340: EDF 1022 SMESH : Crash with FindNodeClosestTo in a second new study
187   //   Notify event listeners at least that something happens
188   if ( SMESH_subMesh * sm = GetSubMeshContaining(1))
189     sm->ComputeStateEngine( SMESH_subMesh::MESH_ENTITY_REMOVED );
190
191   // delete groups
192   map < int, SMESH_Group * >::iterator itg;
193   for (itg = _mapGroup.begin(); itg != _mapGroup.end(); itg++) {
194     SMESH_Group *aGroup = (*itg).second;
195     delete aGroup;
196   }
197   _mapGroup.clear();
198
199   // delete sub-meshes
200   delete _subMeshHolder;
201
202   if ( _callUp) delete _callUp;
203   _callUp = 0;
204
205   // remove self from studyContext
206   if ( _gen )
207   {
208     StudyContextStruct * studyContext = _gen->GetStudyContext();
209     studyContext->mapMesh.erase( _id );
210   }
211   if ( _myDocument )
212     _myDocument->RemoveMesh( _id );
213   _myDocument = 0;
214
215   if ( _myMeshDS ) {
216     // delete _myMeshDS, in a thread in order not to block closing a study with large meshes
217 #ifndef WIN32
218     boost::thread aThread(boost::bind( & deleteMeshDS, _myMeshDS ));
219 #else
220     pthread_t thread;
221     int result=pthread_create(&thread, NULL, deleteMeshDS, (void*)_myMeshDS);
222 #endif
223   }
224 }
225
226 //================================================================================
227 /*!
228  * \brief Return true if a mesh with given id exists
229  */
230 //================================================================================
231
232 bool SMESH_Mesh::MeshExists( int meshId ) const
233 {
234   return _myDocument ? bool( _myDocument->GetMesh( meshId )) : false;
235 }
236
237 //================================================================================
238 /*!
239  * \brief Return a mesh by id
240  */
241 //================================================================================
242
243 SMESH_Mesh* SMESH_Mesh::FindMesh( int meshId ) const
244 {
245   if ( _id == meshId )
246     return (SMESH_Mesh*) this;
247
248   if ( StudyContextStruct *aStudyContext = _gen->GetStudyContext())
249   {
250     std::map < int, SMESH_Mesh * >::iterator i_m = aStudyContext->mapMesh.find( meshId );
251     if ( i_m != aStudyContext->mapMesh.end() )
252       return i_m->second;
253   }
254   return NULL;
255 }
256
257 //=============================================================================
258 /*!
259  * \brief Set geometry to be meshed
260  */
261 //=============================================================================
262
263 void SMESH_Mesh::ShapeToMesh(const TopoDS_Shape & aShape)
264 {
265   if(MYDEBUG) MESSAGE("SMESH_Mesh::ShapeToMesh");
266
267   if ( !aShape.IsNull() && _isShapeToMesh ) {
268     if ( aShape.ShapeType() != TopAbs_COMPOUND && // group contents is allowed to change
269          _myMeshDS->ShapeToMesh().ShapeType() != TopAbs_COMPOUND )
270       throw SALOME_Exception(LOCALIZED ("a shape to mesh has already been defined"));
271   }
272   // clear current data
273   if ( !_myMeshDS->ShapeToMesh().IsNull() )
274   {
275     // removal of a shape to mesh, delete objects referring to sub-shapes:
276     // - sub-meshes
277     _subMeshHolder->DeleteAll();
278     //  - groups on geometry
279     map <int, SMESH_Group *>::iterator i_gr = _mapGroup.begin();
280     while ( i_gr != _mapGroup.end() ) {
281       if ( dynamic_cast<SMESHDS_GroupOnGeom*>( i_gr->second->GetGroupDS() )) {
282         _myMeshDS->RemoveGroup( i_gr->second->GetGroupDS() );
283         delete i_gr->second;
284         _mapGroup.erase( i_gr++ );
285       }
286       else
287         i_gr++;
288     }
289     _mapAncestors.Clear();
290
291     // clear SMESHDS
292     TopoDS_Shape aNullShape;
293     _myMeshDS->ShapeToMesh( aNullShape );
294
295     _shapeDiagonal = 0.0;
296   }
297
298   // set a new geometry
299   if ( !aShape.IsNull() )
300   {
301     _myMeshDS->ShapeToMesh(aShape);
302     _isShapeToMesh = true;
303     _nbSubShapes = _myMeshDS->MaxShapeIndex();
304
305     // fill map of ancestors
306     fillAncestorsMap(aShape);
307   }
308   else
309   {
310     _isShapeToMesh = false;
311     _shapeDiagonal = 0.0;
312     _myMeshDS->ShapeToMesh( PseudoShape() );
313   }
314   _isModified = false;
315 }
316
317 //=======================================================================
318 /*!
319  * \brief Return geometry to be meshed. (It may be a PseudoShape()!)
320  */
321 //=======================================================================
322
323 TopoDS_Shape SMESH_Mesh::GetShapeToMesh() const
324 {
325   return _myMeshDS->ShapeToMesh();
326 }
327
328 //=======================================================================
329 /*!
330  * \brief Return a solid which is returned by GetShapeToMesh() if
331  *        a real geometry to be meshed was not set
332  */
333 //=======================================================================
334
335 const TopoDS_Solid& SMESH_Mesh::PseudoShape()
336 {
337   static TopoDS_Solid aSolid;
338   if ( aSolid.IsNull() )
339   {
340     aSolid = BRepPrimAPI_MakeBox(1,1,1);
341   }
342   return aSolid;
343 }
344
345 //=======================================================================
346 /*!
347  * \brief Return diagonal size of bounding box of a shape
348  */
349 //=======================================================================
350
351 double SMESH_Mesh::GetShapeDiagonalSize(const TopoDS_Shape & aShape)
352 {
353   if ( !aShape.IsNull() ) {
354     Bnd_Box Box;
355     // avoid too long waiting on large shapes. PreciseBoundingBox() was added
356     // to assure same result which else depends on presence of triangulation (IPAL52557).
357     const int maxNbFaces = 4000;
358     int nbFaces = 0;
359     for ( TopExp_Explorer f( aShape, TopAbs_FACE ); f.More() && nbFaces < maxNbFaces; f.Next() )
360       ++nbFaces;
361     bool isPrecise = false;
362     if ( nbFaces < maxNbFaces )
363       try {
364         GEOMUtils::PreciseBoundingBox( aShape, Box );
365         isPrecise = true;
366       }
367       catch (...) {
368         isPrecise = false;
369       }
370     if ( !isPrecise )
371     {
372       BRepBndLib::Add( aShape, Box );
373     }
374     if ( !Box.IsVoid() )
375       return sqrt( Box.SquareExtent() );
376   }
377   return 0;
378 }
379
380 //=======================================================================
381 /*!
382  * \brief Return diagonal size of bounding box of shape to mesh
383  */
384 //=======================================================================
385
386 double SMESH_Mesh::GetShapeDiagonalSize() const
387 {
388   if ( _shapeDiagonal == 0. && _isShapeToMesh )
389     const_cast<SMESH_Mesh*>(this)->_shapeDiagonal = GetShapeDiagonalSize( GetShapeToMesh() );
390
391   return _shapeDiagonal;
392 }
393
394 //================================================================================
395 /*!
396  * \brief Load mesh from study file
397  */
398 //================================================================================
399
400 void SMESH_Mesh::Load()
401 {
402   if (_callUp)
403     _callUp->Load();
404 }
405
406 //=======================================================================
407 /*!
408  * \brief Remove all nodes and elements
409  */
410 //=======================================================================
411
412 void SMESH_Mesh::Clear()
413 {
414   if ( HasShapeToMesh() ) // remove all nodes and elements
415   {
416     // clear mesh data
417     _myMeshDS->ClearMesh();
418
419     // update compute state of submeshes
420     if ( SMESH_subMesh *sm = GetSubMeshContaining( GetShapeToMesh() ) )
421     {
422       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
423       sm->ComputeSubMeshStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
424       sm->ComputeStateEngine( SMESH_subMesh::CLEAN ); // for event listeners (issue 0020918)
425       sm->ComputeSubMeshStateEngine( SMESH_subMesh::CLEAN );
426     }
427   }
428   else // remove only nodes/elements computed by algorithms
429   {
430     if ( SMESH_subMesh *sm = GetSubMeshContaining( GetShapeToMesh() ) )
431     {
432       sm->ComputeStateEngine( SMESH_subMesh::CLEAN );
433       sm->ComputeSubMeshStateEngine( SMESH_subMesh::CLEAN );
434       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
435       sm->ComputeSubMeshStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
436     }
437   }
438   GetMeshDS()->Modified();
439   _isModified = false;
440 }
441
442 //=======================================================================
443 /*!
444  * \brief Remove all nodes and elements of indicated shape
445  */
446 //=======================================================================
447
448 void SMESH_Mesh::ClearSubMesh(const int theShapeId)
449 {
450   // clear sub-meshes; get ready to re-compute as a side-effect 
451   if ( SMESH_subMesh *sm = GetSubMeshContaining( theShapeId ) )
452   {
453     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true,
454                                                              /*complexShapeFirst=*/false);
455     while ( smIt->more() )
456     {
457       sm = smIt->next();
458       TopAbs_ShapeEnum shapeType = sm->GetSubShape().ShapeType();      
459       if ( shapeType == TopAbs_VERTEX || shapeType < TopAbs_SOLID )
460         // all other shapes depends on vertices so they are already cleaned
461         sm->ComputeStateEngine( SMESH_subMesh::CLEAN );
462       // to recompute even if failed
463       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
464     }
465   }
466 }
467
468 //=======================================================================
469 //function : UNVToMesh
470 //purpose  : 
471 //=======================================================================
472
473 int SMESH_Mesh::UNVToMesh(const char* theFileName)
474 {
475   if ( _isShapeToMesh )
476     throw SALOME_Exception(LOCALIZED("a shape to mesh has already been defined"));
477   _isShapeToMesh = false;
478
479   DriverUNV_R_SMDS_Mesh myReader;
480   myReader.SetMesh(_myMeshDS);
481   myReader.SetFile(theFileName);
482   myReader.SetMeshId(-1);
483   myReader.Perform();
484
485   if ( SMDS_MeshGroup* aGroup = (SMDS_MeshGroup*) myReader.GetGroup() )
486   {
487     TGroupNamesMap aGroupNames = myReader.GetGroupNamesMap();
488     aGroup->InitSubGroupsIterator();
489     while (aGroup->MoreSubGroups())
490     {
491       SMDS_MeshGroup* aSubGroup = (SMDS_MeshGroup*) aGroup->NextSubGroup();
492       string aName = aGroupNames[aSubGroup];
493       int aId;
494       if ( SMESH_Group* aSMESHGroup = AddGroup( aSubGroup->GetType(), aName.c_str(), aId ))
495       {
496         SMESHDS_Group* aGroupDS = dynamic_cast<SMESHDS_Group*>( aSMESHGroup->GetGroupDS() );
497         if ( aGroupDS ) {
498           aGroupDS->SetStoreName(aName.c_str());
499           aSubGroup->InitIterator();
500           const SMDS_MeshElement* aElement = 0;
501           while ( aSubGroup->More() )
502             if (( aElement = aSubGroup->Next() ))
503               aGroupDS->SMDSGroup().Add( aElement );
504
505           if (aElement)
506             aGroupDS->SetType( aElement->GetType() );
507         }
508       }
509     }
510   }
511   return 1;
512 }
513
514 //=======================================================================
515 //function : MEDToMesh
516 //purpose  :
517 //=======================================================================
518
519 int SMESH_Mesh::MEDToMesh(const char* theFileName, const char* theMeshName)
520 {
521   if ( _isShapeToMesh )
522     throw SALOME_Exception(LOCALIZED("a shape to mesh has already been defined"));
523   _isShapeToMesh = false;
524
525   DriverMED_R_SMESHDS_Mesh myReader;
526   myReader.SetMesh(_myMeshDS);
527   myReader.SetMeshId(-1);
528   myReader.SetFile(theFileName);
529   myReader.SetMeshName(theMeshName);
530   Driver_Mesh::Status status = myReader.Perform();
531 #ifdef _DEBUG_
532   SMESH_ComputeErrorPtr er = myReader.GetError();
533   if ( er && !er->IsOK() ) cout << er->myComment << endl;
534 #endif
535
536   // Reading groups (sub-meshes are out of scope of MED import functionality)
537   list<TNameAndType> aGroupNames = myReader.GetGroupNamesAndTypes();
538   int anId;
539   list<TNameAndType>::iterator name_type = aGroupNames.begin();
540   for ( ; name_type != aGroupNames.end(); name_type++ )
541   {
542     SMESH_Group* aGroup = AddGroup( name_type->second, name_type->first.c_str(), anId );
543     if ( aGroup ) {
544       SMESHDS_Group* aGroupDS = dynamic_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
545       if ( aGroupDS ) {
546         aGroupDS->SetStoreName( name_type->first.c_str() );
547         myReader.GetGroup( aGroupDS );
548       }
549     }
550   }
551   return (int) status;
552 }
553
554 //=======================================================================
555 //function : STLToMesh
556 //purpose  : 
557 //=======================================================================
558
559 std::string SMESH_Mesh::STLToMesh(const char* theFileName)
560 {
561   if(_isShapeToMesh)
562     throw SALOME_Exception(LOCALIZED("a shape to mesh has already been defined"));
563   _isShapeToMesh = false;
564
565   DriverSTL_R_SMDS_Mesh myReader;
566   myReader.SetMesh(_myMeshDS);
567   myReader.SetFile(theFileName);
568   myReader.SetMeshId(-1);
569   myReader.Perform();
570
571   return myReader.GetName();
572 }
573
574 //================================================================================
575 /*!
576  * \brief Reads the given mesh from the CGNS file
577  *  \param theFileName - name of the file
578  *  \retval int - Driver_Mesh::Status
579  */
580 //================================================================================
581
582 int SMESH_Mesh::CGNSToMesh(const char*  theFileName,
583                            const int    theMeshIndex,
584                            std::string& theMeshName)
585 {
586   int res = Driver_Mesh::DRS_FAIL;
587 #ifdef WITH_CGNS
588
589   DriverCGNS_Read myReader;
590   myReader.SetMesh(_myMeshDS);
591   myReader.SetFile(theFileName);
592   myReader.SetMeshId(theMeshIndex);
593   res = myReader.Perform();
594   theMeshName = myReader.GetMeshName();
595
596   // create groups
597   SynchronizeGroups();
598
599 #endif
600   return res;
601 }
602
603 //================================================================================
604 /*!
605  * \brief Fill its data by reading a GMF file
606  */
607 //================================================================================
608
609 SMESH_ComputeErrorPtr SMESH_Mesh::GMFToMesh(const char* theFileName,
610                                             bool        theMakeRequiredGroups)
611 {
612   DriverGMF_Read myReader;
613   myReader.SetMesh(_myMeshDS);
614   myReader.SetFile(theFileName);
615   myReader.SetMakeRequiredGroups( theMakeRequiredGroups );
616   myReader.Perform();
617   //theMeshName = myReader.GetMeshName();
618
619   // create groups
620   SynchronizeGroups();
621
622   return myReader.GetError();
623 }
624
625 //=============================================================================
626 /*!
627  * 
628  */
629 //=============================================================================
630
631 SMESH_Hypothesis::Hypothesis_Status
632 SMESH_Mesh::AddHypothesis(const TopoDS_Shape & aSubShape,
633                           int                  anHypId,
634                           std::string*         anError  ) throw(SALOME_Exception)
635 {
636   Unexpect aCatch(SalomeException);
637   if(MYDEBUG) MESSAGE("SMESH_Mesh::AddHypothesis");
638
639   if ( anError )
640     anError->clear();
641
642   SMESH_subMesh *subMesh = GetSubMesh(aSubShape);
643   if ( !subMesh || !subMesh->GetId())
644     return SMESH_Hypothesis::HYP_BAD_SUBSHAPE;
645
646   SMESH_Hypothesis *anHyp = GetHypothesis( anHypId );
647   if ( !anHyp )
648     throw SALOME_Exception(LOCALIZED("hypothesis does not exist"));
649
650   bool isGlobalHyp = IsMainShape( aSubShape );
651
652   // NotConformAllowed can be only global
653   if ( !isGlobalHyp )
654   {
655     // NOTE: this is not a correct way to check a name of hypothesis,
656     // there should be an attribute of hypothesis saying that it can/can't
657     // be global/local
658     string hypName = anHyp->GetName();
659     if ( hypName == "NotConformAllowed" )
660     {
661       if(MYDEBUG) MESSAGE( "Hypotesis <NotConformAllowed> can be only global" );
662       return SMESH_Hypothesis::HYP_INCOMPATIBLE;
663     }
664   }
665
666   // shape
667
668   bool                     isAlgo = ( anHyp->GetType() != SMESHDS_Hypothesis::PARAM_ALGO );
669   SMESH_subMesh::algo_event event = isAlgo ? SMESH_subMesh::ADD_ALGO : SMESH_subMesh::ADD_HYP;
670
671   SMESH_Hypothesis::Hypothesis_Status ret = subMesh->AlgoStateEngine(event, anHyp);
672
673   if ( anError && SMESH_Hypothesis::IsStatusFatal(ret) && subMesh->GetComputeError() )
674     *anError = subMesh->GetComputeError()->myComment;
675
676   // sub-shapes
677   if ( !SMESH_Hypothesis::IsStatusFatal(ret) &&
678        anHyp->GetDim() <= SMESH_Gen::GetShapeDim(aSubShape)) // is added on father
679   {
680     event = isAlgo ? SMESH_subMesh::ADD_FATHER_ALGO : SMESH_subMesh::ADD_FATHER_HYP;
681
682     SMESH_Hypothesis::Hypothesis_Status ret2 =
683       subMesh->SubMeshesAlgoStateEngine(event, anHyp, /*exitOnFatal=*/true);
684     if (ret2 > ret)
685     {
686       ret = ret2;
687       if ( SMESH_Hypothesis::IsStatusFatal( ret ))
688       {
689         if ( anError && subMesh->GetComputeError() )
690           *anError = subMesh->GetComputeError()->myComment;
691         // remove anHyp
692         event = isAlgo ? SMESH_subMesh::REMOVE_ALGO : SMESH_subMesh::REMOVE_HYP;
693         subMesh->AlgoStateEngine(event, anHyp);
694       }
695     }
696
697     // check concurent hypotheses on ancestors
698     if (ret < SMESH_Hypothesis::HYP_CONCURENT && !isGlobalHyp )
699     {
700       SMESH_subMeshIteratorPtr smIt = subMesh->getDependsOnIterator(false,false);
701       while ( smIt->more() ) {
702         SMESH_subMesh* sm = smIt->next();
703         if ( sm->IsApplicableHypotesis( anHyp )) {
704           ret2 = sm->CheckConcurentHypothesis( anHyp->GetType() );
705           if (ret2 > ret) {
706             ret = ret2;
707             break;
708           }
709         }
710       }
711     }
712   }
713   HasModificationsToDiscard(); // to reset _isModified flag if a mesh becomes empty
714   GetMeshDS()->Modified();
715
716   if(MYDEBUG) subMesh->DumpAlgoState(true);
717   if(MYDEBUG) SCRUTE(ret);
718   return ret;
719 }
720
721 //=============================================================================
722 /*!
723  * 
724  */
725 //=============================================================================
726
727 SMESH_Hypothesis::Hypothesis_Status
728 SMESH_Mesh::RemoveHypothesis(const TopoDS_Shape & aSubShape,
729                              int                    anHypId) throw( SALOME_Exception )
730 {
731   Unexpect aCatch(SalomeException);
732   if(MYDEBUG) MESSAGE("SMESH_Mesh::RemoveHypothesis");
733
734   StudyContextStruct *sc = _gen->GetStudyContext();
735   if (sc->mapHypothesis.find(anHypId) == sc->mapHypothesis.end())
736     throw SALOME_Exception(LOCALIZED("hypothesis does not exist"));
737
738   SMESH_Hypothesis *anHyp = sc->mapHypothesis[anHypId];
739   if(MYDEBUG) { SCRUTE(anHyp->GetType()); }
740
741   // shape 
742
743   bool                     isAlgo = ( !anHyp->GetType() == SMESHDS_Hypothesis::PARAM_ALGO );
744   SMESH_subMesh::algo_event event = isAlgo ? SMESH_subMesh::REMOVE_ALGO : SMESH_subMesh::REMOVE_HYP;
745
746   SMESH_subMesh *subMesh = GetSubMesh(aSubShape);
747
748   SMESH_Hypothesis::Hypothesis_Status ret = subMesh->AlgoStateEngine(event, anHyp);
749
750   // there may appear concurrent hyps that were covered by the removed hyp
751   if (ret < SMESH_Hypothesis::HYP_CONCURENT &&
752       subMesh->IsApplicableHypotesis( anHyp ) &&
753       subMesh->CheckConcurentHypothesis( anHyp->GetType() ) != SMESH_Hypothesis::HYP_OK)
754     ret = SMESH_Hypothesis::HYP_CONCURENT;
755
756   // sub-shapes
757   if (!SMESH_Hypothesis::IsStatusFatal(ret) &&
758       anHyp->GetDim() <= SMESH_Gen::GetShapeDim(aSubShape)) // is removed from father
759   {
760     event = isAlgo ? SMESH_subMesh::REMOVE_FATHER_ALGO : SMESH_subMesh::REMOVE_FATHER_HYP;
761
762     SMESH_Hypothesis::Hypothesis_Status ret2 =
763       subMesh->SubMeshesAlgoStateEngine(event, anHyp);
764     if (ret2 > ret) // more severe
765       ret = ret2;
766
767     // check concurent hypotheses on ancestors
768     if (ret < SMESH_Hypothesis::HYP_CONCURENT && !IsMainShape( aSubShape ) )
769     {
770       SMESH_subMeshIteratorPtr smIt = subMesh->getDependsOnIterator(false,false);
771       while ( smIt->more() ) {
772         SMESH_subMesh* sm = smIt->next();
773         if ( sm->IsApplicableHypotesis( anHyp )) {
774           ret2 = sm->CheckConcurentHypothesis( anHyp->GetType() );
775           if (ret2 > ret) {
776             ret = ret2;
777             break;
778           }
779         }
780       }
781     }
782   }
783
784   HasModificationsToDiscard(); // to reset _isModified flag if mesh become empty
785   GetMeshDS()->Modified();
786
787   if(MYDEBUG) subMesh->DumpAlgoState(true);
788   if(MYDEBUG) SCRUTE(ret);
789   return ret;
790 }
791
792 //=============================================================================
793 /*!
794  * 
795  */
796 //=============================================================================
797
798 const list<const SMESHDS_Hypothesis*>&
799 SMESH_Mesh::GetHypothesisList(const TopoDS_Shape & aSubShape) const
800   throw(SALOME_Exception)
801 {
802   return _myMeshDS->GetHypothesis(aSubShape);
803 }
804
805 //=======================================================================
806 /*!
807  * \brief Return the hypothesis assigned to the shape
808  *  \param aSubShape    - the shape to check
809  *  \param aFilter      - the hypothesis filter
810  *  \param andAncestors - flag to check hypos assigned to ancestors of the shape
811  *  \param assignedTo   - to return the shape the found hypo is assigned to
812  *  \retval SMESH_Hypothesis* - the first hypo passed through aFilter
813  */
814 //=======================================================================
815
816 const SMESH_Hypothesis * SMESH_Mesh::GetHypothesis(const TopoDS_Shape &    aSubShape,
817                                                    const SMESH_HypoFilter& aFilter,
818                                                    const bool              andAncestors,
819                                                    TopoDS_Shape*           assignedTo) const
820 {
821   return GetHypothesis( const_cast< SMESH_Mesh* >(this)->GetSubMesh( aSubShape ),
822                         aFilter, andAncestors, assignedTo );
823 }
824
825 //=======================================================================
826 /*!
827  * \brief Return the hypothesis assigned to the shape of a sub-mesh
828  *  \param aSubMesh     - the sub-mesh to check
829  *  \param aFilter      - the hypothesis filter
830  *  \param andAncestors - flag to check hypos assigned to ancestors of the shape
831  *  \param assignedTo   - to return the shape the found hypo is assigned to
832  *  \retval SMESH_Hypothesis* - the first hypo passed through aFilter
833  */
834 //=======================================================================
835
836 const SMESH_Hypothesis * SMESH_Mesh::GetHypothesis(const SMESH_subMesh *   aSubMesh,
837                                                    const SMESH_HypoFilter& aFilter,
838                                                    const bool              andAncestors,
839                                                    TopoDS_Shape*           assignedTo) const
840 {
841   if ( !aSubMesh ) return 0;
842
843   {
844     const TopoDS_Shape & aSubShape = aSubMesh->GetSubShape();
845     const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(aSubShape);
846     list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
847     for ( ; hyp != hypList.end(); hyp++ ) {
848       const SMESH_Hypothesis * h = cSMESH_Hyp( *hyp );
849       if ( aFilter.IsOk( h, aSubShape)) {
850         if ( assignedTo ) *assignedTo = aSubShape;
851         return h;
852       }
853     }
854   }
855   if ( andAncestors )
856   {
857     // user sorted submeshes of ancestors, according to stored submesh priority
858     std::vector< SMESH_subMesh * > & ancestors =
859       const_cast< std::vector< SMESH_subMesh * > & > ( aSubMesh->GetAncestors() );
860     SortByMeshOrder( ancestors );
861
862     vector<SMESH_subMesh*>::const_iterator smIt = ancestors.begin(); 
863     for ( ; smIt != ancestors.end(); smIt++ )
864     {
865       const TopoDS_Shape& curSh = (*smIt)->GetSubShape();
866       const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(curSh);
867       list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
868       for ( ; hyp != hypList.end(); hyp++ ) {
869         const SMESH_Hypothesis * h = cSMESH_Hyp( *hyp );
870         if (aFilter.IsOk( h, curSh )) {
871           if ( assignedTo ) *assignedTo = curSh;
872           return h;
873         }
874       }
875     }
876   }
877   return 0;
878 }
879
880 //================================================================================
881 /*!
882  * \brief Return hypotheses assigned to the shape
883   * \param aSubShape - the shape to check
884   * \param aFilter - the hypothesis filter
885   * \param aHypList - the list of the found hypotheses
886   * \param andAncestors - flag to check hypos assigned to ancestors of the shape
887   * \retval int - number of unique hypos in aHypList
888  */
889 //================================================================================
890
891 int SMESH_Mesh::GetHypotheses(const TopoDS_Shape &                aSubShape,
892                               const SMESH_HypoFilter&             aFilter,
893                               list <const SMESHDS_Hypothesis * >& aHypList,
894                               const bool                          andAncestors,
895                               list< TopoDS_Shape > *              assignedTo/*=0*/) const
896 {
897   return GetHypotheses( const_cast< SMESH_Mesh* >(this)->GetSubMesh( aSubShape ),
898                         aFilter, aHypList, andAncestors, assignedTo );
899 }
900
901 //================================================================================
902 /*!
903  * \brief Return hypotheses assigned to the shape of a sub-mesh
904   * \param aSubShape - the sub-mesh to check
905   * \param aFilter - the hypothesis filter
906   * \param aHypList - the list of the found hypotheses
907   * \param andAncestors - flag to check hypos assigned to ancestors of the shape
908   * \retval int - number of unique hypos in aHypList
909  */
910 //================================================================================
911
912 int SMESH_Mesh::GetHypotheses(const SMESH_subMesh *               aSubMesh,
913                               const SMESH_HypoFilter&             aFilter,
914                               list <const SMESHDS_Hypothesis * >& aHypList,
915                               const bool                          andAncestors,
916                               list< TopoDS_Shape > *              assignedTo/*=0*/) const
917 {
918   if ( !aSubMesh ) return 0;
919
920   set<string> hypTypes; // to exclude same type hypos from the result list
921   int nbHyps = 0;
922
923   // only one main hypothesis is allowed
924   bool mainHypFound = false;
925
926   // fill in hypTypes
927   list<const SMESHDS_Hypothesis*>::const_iterator hyp;
928   for ( hyp = aHypList.begin(); hyp != aHypList.end(); hyp++ ) {
929     if ( hypTypes.insert( (*hyp)->GetName() ).second )
930       nbHyps++;
931     if ( !cSMESH_Hyp(*hyp)->IsAuxiliary() )
932       mainHypFound = true;
933   }
934
935   // get hypos from aSubShape
936   {
937     const TopoDS_Shape & aSubShape = aSubMesh->GetSubShape();
938     const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(aSubShape);
939     for ( hyp = hypList.begin(); hyp != hypList.end(); hyp++ )
940     {
941       const SMESH_Hypothesis* h = cSMESH_Hyp( *hyp );
942       if (( aFilter.IsOk( h, aSubShape )) &&
943           ( h->IsAuxiliary() || !mainHypFound ) &&
944           ( h->IsAuxiliary() || hypTypes.insert( h->GetName() ).second ))
945       {
946         aHypList.push_back( *hyp );
947         nbHyps++;
948         if ( !h->IsAuxiliary() )
949           mainHypFound = true;
950         if ( assignedTo ) assignedTo->push_back( aSubShape );
951       }
952     }
953   }
954
955   // get hypos from ancestors of aSubShape
956   if ( andAncestors )
957   {
958     // user sorted submeshes of ancestors, according to stored submesh priority
959     std::vector< SMESH_subMesh * > & ancestors =
960       const_cast< std::vector< SMESH_subMesh * > & > ( aSubMesh->GetAncestors() );
961     SortByMeshOrder( ancestors );
962
963     vector<SMESH_subMesh*>::const_iterator smIt = ancestors.begin();
964     for ( ; smIt != ancestors.end(); smIt++ )
965     {
966       const TopoDS_Shape& curSh = (*smIt)->GetSubShape();
967       const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(curSh);
968       for ( hyp = hypList.begin(); hyp != hypList.end(); hyp++ )
969       {
970         const SMESH_Hypothesis* h = cSMESH_Hyp( *hyp );
971         if (( aFilter.IsOk( h, curSh )) &&
972             ( h->IsAuxiliary() || !mainHypFound ) &&
973             ( h->IsAuxiliary() || hypTypes.insert( h->GetName() ).second ))
974         {
975           aHypList.push_back( *hyp );
976           nbHyps++;
977           if ( !h->IsAuxiliary() )
978             mainHypFound = true;
979           if ( assignedTo ) assignedTo->push_back( curSh );
980         }
981       }
982     }
983   }
984   return nbHyps;
985 }
986
987 //================================================================================
988 /*!
989  * \brief Return a hypothesis by its ID
990  */
991 //================================================================================
992
993 SMESH_Hypothesis * SMESH_Mesh::GetHypothesis(const int anHypId) const
994 {
995   StudyContextStruct *sc = _gen->GetStudyContext();
996   if (sc->mapHypothesis.find(anHypId) == sc->mapHypothesis.end())
997     return NULL;
998
999   SMESH_Hypothesis *anHyp = sc->mapHypothesis[anHypId];
1000   return anHyp;
1001 }
1002
1003 //=============================================================================
1004 /*!
1005  * 
1006  */
1007 //=============================================================================
1008
1009 const list<SMESHDS_Command*> & SMESH_Mesh::GetLog() throw(SALOME_Exception)
1010 {
1011   Unexpect aCatch(SalomeException);
1012   return _myMeshDS->GetScript()->GetCommands();
1013 }
1014
1015 //=============================================================================
1016 /*!
1017  * 
1018  */
1019 //=============================================================================
1020 void SMESH_Mesh::ClearLog() throw(SALOME_Exception)
1021 {
1022   Unexpect aCatch(SalomeException);
1023   _myMeshDS->GetScript()->Clear();
1024 }
1025
1026 //=============================================================================
1027 /*!
1028  * Get or Create the SMESH_subMesh object implementation
1029  */
1030 //=============================================================================
1031
1032 SMESH_subMesh * SMESH_Mesh::GetSubMesh(const TopoDS_Shape & aSubShape)
1033   throw(SALOME_Exception)
1034 {
1035   int index = _myMeshDS->ShapeToIndex(aSubShape);
1036   if ( !index && aSubShape.IsNull() )
1037     return 0;
1038
1039   // for submeshes on GEOM Group
1040   if (( !index || index > _nbSubShapes ) && aSubShape.ShapeType() == TopAbs_COMPOUND )
1041   {
1042     TopoDS_Iterator it( aSubShape );
1043     if ( it.More() )
1044     {
1045       index = _myMeshDS->AddCompoundSubmesh( aSubShape, it.Value().ShapeType() );
1046       // fill map of Ancestors
1047       while ( _nbSubShapes < index )
1048         fillAncestorsMap( _myMeshDS->IndexToShape( ++_nbSubShapes ));
1049     }
1050   }
1051   // if ( !index )
1052   //   return NULL; // neither sub-shape nor a group
1053
1054   SMESH_subMesh* aSubMesh = _subMeshHolder->Get( index );
1055   if ( !aSubMesh )
1056   {
1057     aSubMesh = new SMESH_subMesh(index, this, _myMeshDS, aSubShape);
1058     _subMeshHolder->Add( index, aSubMesh );
1059
1060     // include non-computable sub-meshes in SMESH_subMesh::_ancestors of sub-submeshes
1061     switch ( aSubShape.ShapeType() ) {
1062     case TopAbs_COMPOUND:
1063     case TopAbs_WIRE:
1064     case TopAbs_SHELL:
1065       for ( TopoDS_Iterator subIt( aSubShape ); subIt.More(); subIt.Next() )
1066       {
1067         SMESH_subMesh* sm = GetSubMesh( subIt.Value() );
1068         SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*inclideSelf=*/true);
1069         while ( smIt->more() )
1070           smIt->next()->ClearAncestors();
1071       }
1072     default:;
1073     }
1074   }
1075   return aSubMesh;
1076 }
1077
1078 //=============================================================================
1079 /*!
1080  * Get the SMESH_subMesh object implementation. Don't create it, return null
1081  * if it does not exist.
1082  */
1083 //=============================================================================
1084
1085 SMESH_subMesh *SMESH_Mesh::GetSubMeshContaining(const TopoDS_Shape & aSubShape) const
1086   throw(SALOME_Exception)
1087 {
1088   int index = _myMeshDS->ShapeToIndex(aSubShape);
1089   return GetSubMeshContaining( index );
1090 }
1091
1092 //=============================================================================
1093 /*!
1094  * Get the SMESH_subMesh object implementation. Don't create it, return null
1095  * if it does not exist.
1096  */
1097 //=============================================================================
1098
1099 SMESH_subMesh *SMESH_Mesh::GetSubMeshContaining(const int aShapeID) const
1100 throw(SALOME_Exception)
1101 {
1102   SMESH_subMesh *aSubMesh = _subMeshHolder->Get( aShapeID );
1103
1104   return aSubMesh;
1105 }
1106
1107 //================================================================================
1108 /*!
1109  * \brief Return sub-meshes of groups containing the given sub-shape
1110  */
1111 //================================================================================
1112
1113 list<SMESH_subMesh*>
1114 SMESH_Mesh::GetGroupSubMeshesContaining(const TopoDS_Shape & aSubShape) const
1115   throw(SALOME_Exception)
1116 {
1117   list<SMESH_subMesh*> found;
1118
1119   SMESH_subMesh * subMesh = GetSubMeshContaining(aSubShape);
1120   if ( !subMesh )
1121     return found;
1122
1123   // sub-meshes of groups have max IDs, so search from the map end
1124   SMESH_subMeshIteratorPtr smIt( _subMeshHolder->GetIterator( /*reverse=*/true ) );
1125   while ( smIt->more() ) {
1126     SMESH_subMesh*    sm = smIt->next();
1127     SMESHDS_SubMesh * ds = sm->GetSubMeshDS();
1128     if ( ds && ds->IsComplexSubmesh() ) {
1129       if ( SMESH_MesherHelper::IsSubShape( aSubShape, sm->GetSubShape() ))
1130       {
1131         found.push_back( sm );
1132         //break;
1133       }
1134     } else {
1135       break; // the rest sub-meshes are not those of groups
1136     }
1137   }
1138
1139   if ( found.empty() ) // maybe the main shape is a COMPOUND (issue 0021530)
1140   {
1141     if ( SMESH_subMesh * mainSM = GetSubMeshContaining(1) )
1142       if ( mainSM->GetSubShape().ShapeType() == TopAbs_COMPOUND )
1143       {
1144         TopoDS_Iterator it( mainSM->GetSubShape() );
1145         if ( it.Value().ShapeType() == aSubShape.ShapeType() &&
1146              SMESH_MesherHelper::IsSubShape( aSubShape, mainSM->GetSubShape() ))
1147           found.push_back( mainSM );
1148       }
1149   }
1150   else // issue 0023068
1151   {
1152     if ( SMESH_subMesh * mainSM = GetSubMeshContaining(1) )
1153       if ( mainSM->GetSubShape().ShapeType() == TopAbs_COMPOUND )
1154         found.push_back( mainSM );
1155   }
1156   return found;
1157 }
1158 //=======================================================================
1159 //function : IsUsedHypothesis
1160 //purpose  : Return True if anHyp is used to mesh aSubShape
1161 //=======================================================================
1162
1163 bool SMESH_Mesh::IsUsedHypothesis(SMESHDS_Hypothesis * anHyp,
1164                                   const SMESH_subMesh* aSubMesh)
1165 {
1166   SMESH_Hypothesis* hyp = static_cast<SMESH_Hypothesis*>(anHyp);
1167
1168   // check if anHyp can be used to mesh aSubMesh
1169   if ( !aSubMesh || !aSubMesh->IsApplicableHypotesis( hyp ))
1170     return false;
1171
1172   SMESH_Algo *algo = aSubMesh->GetAlgo();
1173
1174   // algorithm
1175   if (anHyp->GetType() > SMESHDS_Hypothesis::PARAM_ALGO)
1176     return ( anHyp == algo );
1177
1178   // algorithm parameter
1179   if (algo)
1180   {
1181     // look trough hypotheses used by algo
1182     const SMESH_HypoFilter* hypoKind;
1183     if (( hypoKind = algo->GetCompatibleHypoFilter( !hyp->IsAuxiliary() ))) {
1184       list <const SMESHDS_Hypothesis * > usedHyps;
1185       if ( GetHypotheses( aSubMesh, *hypoKind, usedHyps, true ))
1186         return ( find( usedHyps.begin(), usedHyps.end(), anHyp ) != usedHyps.end() );
1187     }
1188   }
1189
1190   return false;
1191 }
1192
1193 //=======================================================================
1194 //function : NotifySubMeshesHypothesisModification
1195 //purpose  : Say all submeshes using theChangedHyp that it has been modified
1196 //=======================================================================
1197
1198 void SMESH_Mesh::NotifySubMeshesHypothesisModification(const SMESH_Hypothesis* hyp)
1199 {
1200   Unexpect aCatch(SalomeException);
1201
1202   if ( !GetMeshDS()->IsUsedHypothesis( hyp ))
1203     return;
1204
1205   if (_callUp)
1206     _callUp->HypothesisModified();
1207
1208   SMESH_Algo *algo;
1209   const SMESH_HypoFilter* compatibleHypoKind;
1210   list <const SMESHDS_Hypothesis * > usedHyps;
1211   vector< SMESH_subMesh* > smToNotify;
1212   bool allMeshedEdgesNotified = true;
1213
1214   SMESH_subMeshIteratorPtr smIt( _subMeshHolder->GetIterator() );
1215   while ( smIt->more() )
1216   {
1217     SMESH_subMesh* aSubMesh = smIt->next();
1218     bool toNotify = false;
1219
1220     // if aSubMesh meshing depends on hyp,
1221     // we call aSubMesh->AlgoStateEngine( MODIF_HYP, hyp ) that causes either
1222     // 1) clearing already computed aSubMesh or
1223     // 2) changing algo_state from MISSING_HYP to HYP_OK when parameters of hyp becomes valid,
1224     // other possible changes are not interesting. (IPAL0052457 - assigning hyp performance pb)
1225     if ( aSubMesh->GetComputeState() == SMESH_subMesh::COMPUTE_OK ||
1226          aSubMesh->GetComputeState() == SMESH_subMesh::FAILED_TO_COMPUTE ||
1227          aSubMesh->GetAlgoState()    == SMESH_subMesh::MISSING_HYP ||
1228          hyp->DataDependOnParams() )
1229     {
1230       const TopoDS_Shape & aSubShape = aSubMesh->GetSubShape();
1231
1232       if (( aSubMesh->IsApplicableHypotesis( hyp )) &&
1233           ( algo = aSubMesh->GetAlgo() )            &&
1234           ( compatibleHypoKind = algo->GetCompatibleHypoFilter( !hyp->IsAuxiliary() )) &&
1235           ( compatibleHypoKind->IsOk( hyp, aSubShape )))
1236       {
1237         // check if hyp is used by algo
1238         usedHyps.clear();
1239         toNotify = ( GetHypotheses( aSubMesh, *compatibleHypoKind, usedHyps, true ) &&
1240                      std::find( usedHyps.begin(), usedHyps.end(), hyp ) != usedHyps.end() );
1241       }
1242     }
1243     if ( toNotify )
1244     {
1245       smToNotify.push_back( aSubMesh );
1246       if ( aSubMesh->GetAlgoState() == SMESH_subMesh::MISSING_HYP )
1247         allMeshedEdgesNotified = false; //  update of algo state needed, not mesh clearing
1248     }
1249     else
1250     {
1251       if ( !aSubMesh->IsEmpty() &&
1252            aSubMesh->GetSubShape().ShapeType() == TopAbs_EDGE )
1253         allMeshedEdgesNotified = false;
1254     }
1255   }
1256   if ( smToNotify.empty() )
1257     return;
1258
1259   // if all meshed EDGEs will be notified then the notification is equivalent
1260   // to the whole mesh clearing, which is usually faster
1261   if ( allMeshedEdgesNotified && NbNodes() > 0 )
1262   {
1263     Clear();
1264   }
1265   else
1266   {
1267     // notify in reverse order to avoid filling the pool of IDs
1268     for ( int i = smToNotify.size()-1; i >= 0; --i )
1269       smToNotify[i]->AlgoStateEngine(SMESH_subMesh::MODIF_HYP,
1270                                      const_cast< SMESH_Hypothesis*>( hyp ));
1271   }
1272   HasModificationsToDiscard(); // to reset _isModified flag if mesh becomes empty
1273   GetMeshDS()->Modified();
1274 }
1275
1276 //=============================================================================
1277 /*!
1278  *  Auto color functionality
1279  */
1280 //=============================================================================
1281 void SMESH_Mesh::SetAutoColor(bool theAutoColor) throw(SALOME_Exception)
1282 {
1283   Unexpect aCatch(SalomeException);
1284   _isAutoColor = theAutoColor;
1285 }
1286
1287 bool SMESH_Mesh::GetAutoColor() throw(SALOME_Exception)
1288 {
1289   Unexpect aCatch(SalomeException);
1290   return _isAutoColor;
1291 }
1292
1293 //=======================================================================
1294 //function : SetIsModified
1295 //purpose  : Set the flag meaning that the mesh has been edited "manually"
1296 //=======================================================================
1297
1298 void SMESH_Mesh::SetIsModified(bool isModified)
1299 {
1300   _isModified = isModified;
1301
1302   if ( _isModified )
1303     // check if mesh becomes empty as result of modification
1304     HasModificationsToDiscard();
1305 }
1306
1307 //=======================================================================
1308 //function : HasModificationsToDiscard
1309 //purpose  : Return true if the mesh has been edited since a total re-compute
1310 //           and those modifications may prevent successful partial re-compute.
1311 //           As a side effect reset _isModified flag if mesh is empty
1312 //issue    : 0020693
1313 //=======================================================================
1314
1315 bool SMESH_Mesh::HasModificationsToDiscard() const
1316 {
1317   if ( ! _isModified )
1318     return false;
1319
1320   // return true if the next Compute() will be partial and
1321   // existing but changed elements may prevent successful re-compute
1322   bool hasComputed = false, hasNotComputed = false;
1323   SMESH_subMeshIteratorPtr smIt( _subMeshHolder->GetIterator() );
1324   while ( smIt->more() )
1325   {
1326     const SMESH_subMesh* aSubMesh = smIt->next();
1327     switch ( aSubMesh->GetSubShape().ShapeType() )
1328     {
1329     case TopAbs_EDGE:
1330     case TopAbs_FACE:
1331     case TopAbs_SOLID:
1332       if ( aSubMesh->IsMeshComputed() )
1333         hasComputed = true;
1334       else
1335         hasNotComputed = true;
1336       if ( hasComputed && hasNotComputed)
1337         return true;
1338
1339     default:;
1340     }
1341   }
1342   if ( NbNodes() < 1 )
1343     const_cast<SMESH_Mesh*>(this)->_isModified = false;
1344
1345   return false;
1346 }
1347
1348 //================================================================================
1349 /*!
1350  * \brief Check if any groups of the same type have equal names
1351  */
1352 //================================================================================
1353
1354 bool SMESH_Mesh::HasDuplicatedGroupNamesMED()
1355 {
1356   // Corrected for Mantis issue 0020028
1357   map< SMDSAbs_ElementType, set<string> > aGroupNames;
1358   for ( map<int, SMESH_Group*>::iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ )
1359   {
1360     SMESH_Group*       aGroup = it->second;
1361     SMDSAbs_ElementType aType = aGroup->GetGroupDS()->GetType();
1362     string         aGroupName = aGroup->GetName();
1363     aGroupName.resize( MAX_MED_GROUP_NAME_LENGTH );
1364     if ( !aGroupNames[aType].insert(aGroupName).second )
1365       return true;
1366   }
1367
1368   return false;
1369 }
1370
1371 //================================================================================
1372 /*!
1373  * \brief Export the mesh to a med file
1374  *  \param [in] file - name of the MED file
1375  *  \param [in] theMeshName - name of this mesh
1376  *  \param [in] theAutoGroups - boolean parameter for creating/not creating
1377  *              the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1378  *              the typical use is auto_groups=false.
1379  *  \param [in] meshPart - mesh data to export
1380  *  \param [in] theAutoDimension - if \c true, a space dimension of a MED mesh can be either
1381      *         - 1D if all mesh nodes lie on OX coordinate axis, or
1382      *         - 2D if all mesh nodes lie on XOY coordinate plane, or
1383      *         - 3D in the rest cases.
1384      *         If \a theAutoDimension is \c false, the space dimension is always 3.
1385  *  \param [in] theAddODOnVertices - to create 0D elements on all vertices
1386  *  \param [in] theAllElemsToGroup - to make every element to belong to any group (PAL23413)
1387  *  \return int - mesh index in the file
1388  */
1389 //================================================================================
1390
1391 void SMESH_Mesh::ExportMED(const char *        file, 
1392                            const char*         theMeshName, 
1393                            bool                theAutoGroups,
1394                            const SMESHDS_Mesh* meshPart,
1395                            bool                theAutoDimension,
1396                            bool                theAddODOnVertices,
1397                            bool                theAllElemsToGroup)
1398   throw(SALOME_Exception)
1399 {
1400   SMESH_TRY;
1401
1402   DriverMED_W_SMESHDS_Mesh myWriter;
1403   myWriter.SetFile         ( file );
1404   myWriter.SetMesh         ( meshPart ? (SMESHDS_Mesh*) meshPart : _myMeshDS   );
1405   myWriter.SetAutoDimension( theAutoDimension );
1406   myWriter.AddODOnVertices ( theAddODOnVertices );
1407   if ( !theMeshName ) 
1408     myWriter.SetMeshId     ( _id         );
1409   else {
1410     myWriter.SetMeshId     ( -1          );
1411     myWriter.SetMeshName   ( theMeshName );
1412   }
1413
1414   if ( theAutoGroups ) {
1415     myWriter.AddGroupOfNodes();
1416     myWriter.AddGroupOfEdges();
1417     myWriter.AddGroupOfFaces();
1418     myWriter.AddGroupOfVolumes();
1419     myWriter.AddGroupOf0DElems();
1420     myWriter.AddGroupOfBalls();
1421   }
1422   if ( theAllElemsToGroup )
1423     myWriter.AddAllToGroup();
1424
1425   // Pass groups to writer. Provide unique group names.
1426   //set<string> aGroupNames; // Corrected for Mantis issue 0020028
1427   if ( !meshPart )
1428   {
1429     map< SMDSAbs_ElementType, set<string> > aGroupNames;
1430     char aString [256];
1431     int maxNbIter = 10000; // to guarantee cycle finish
1432     for ( map<int, SMESH_Group*>::iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ ) {
1433       SMESH_Group*       aGroup   = it->second;
1434       SMESHDS_GroupBase* aGroupDS = aGroup->GetGroupDS();
1435       if ( aGroupDS ) {
1436         SMDSAbs_ElementType aType = aGroupDS->GetType();
1437         string aGroupName0 = aGroup->GetName();
1438         aGroupName0.resize(MAX_MED_GROUP_NAME_LENGTH);
1439         string aGroupName = aGroupName0;
1440         for (int i = 1; !aGroupNames[aType].insert(aGroupName).second && i < maxNbIter; i++) {
1441           sprintf(&aString[0], "GR_%d_%s", i, aGroupName0.c_str());
1442           aGroupName = aString;
1443           aGroupName.resize(MAX_MED_GROUP_NAME_LENGTH);
1444         }
1445         aGroupDS->SetStoreName( aGroupName.c_str() );
1446         myWriter.AddGroup( aGroupDS );
1447       }
1448     }
1449   }
1450   // Perform export
1451   myWriter.Perform();
1452
1453   SMESH_CATCH( SMESH::throwSalomeEx );
1454 }
1455
1456 //================================================================================
1457 /*!
1458  * \brief Export the mesh to a SAUV file
1459  */
1460 //================================================================================
1461
1462 void SMESH_Mesh::ExportSAUV(const char *file, 
1463                             const char* theMeshName, 
1464                             bool theAutoGroups)
1465   throw(SALOME_Exception)
1466 {
1467   std::string medfilename(file);
1468   medfilename += ".med";
1469   std::string cmd;
1470 #ifdef WIN32
1471   cmd = "%PYTHONBIN% ";
1472 #else
1473   cmd = "python3 ";
1474 #endif
1475   cmd += "-c \"";
1476   cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1477   cmd += "\"";
1478   system(cmd.c_str());
1479   ExportMED(medfilename.c_str(), theMeshName, theAutoGroups,
1480             /*meshPart=*/NULL, /*theAutoDimension=*/false, /*theAddODOnVertices=*/false,
1481             /*theAllElemsToGroup=*/true ); // theAllElemsToGroup is for PAL0023413
1482 #ifdef WIN32
1483   cmd = "%PYTHONBIN% ";
1484 #else
1485   cmd = "python3 ";
1486 #endif
1487   cmd += "-c \"";
1488   cmd += "from medutilities import convert ; convert(r'" + medfilename + "', 'MED', 'GIBI', 1, r'" + file + "')";
1489   cmd += "\"";
1490   system(cmd.c_str());
1491 #ifdef WIN32
1492   cmd = "%PYTHONBIN% ";
1493 #else
1494   cmd = "python3 ";
1495 #endif
1496   cmd += "-c \"";
1497   cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1498   cmd += "\"";
1499   system(cmd.c_str());
1500 }
1501
1502 //================================================================================
1503 /*!
1504  * \brief Export the mesh to a DAT file
1505  */
1506 //================================================================================
1507
1508 void SMESH_Mesh::ExportDAT(const char *        file,
1509                            const SMESHDS_Mesh* meshPart) throw(SALOME_Exception)
1510 {
1511   Unexpect aCatch(SalomeException);
1512   DriverDAT_W_SMDS_Mesh myWriter;
1513   myWriter.SetFile( file );
1514   myWriter.SetMesh( meshPart ? (SMESHDS_Mesh*) meshPart : _myMeshDS );
1515   myWriter.SetMeshId(_id);
1516   myWriter.Perform();
1517 }
1518
1519 //================================================================================
1520 /*!
1521  * \brief Export the mesh to an UNV file
1522  */
1523 //================================================================================
1524
1525 void SMESH_Mesh::ExportUNV(const char *        file,
1526                            const SMESHDS_Mesh* meshPart) throw(SALOME_Exception)
1527 {
1528   Unexpect aCatch(SalomeException);
1529   DriverUNV_W_SMDS_Mesh myWriter;
1530   myWriter.SetFile( file );
1531   myWriter.SetMesh( meshPart ? (SMESHDS_Mesh*) meshPart : _myMeshDS );
1532   myWriter.SetMeshId(_id);
1533   //  myWriter.SetGroups(_mapGroup);
1534
1535   if ( !meshPart )
1536   {
1537     for ( map<int, SMESH_Group*>::iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ ) {
1538       SMESH_Group*       aGroup   = it->second;
1539       SMESHDS_GroupBase* aGroupDS = aGroup->GetGroupDS();
1540       if ( aGroupDS ) {
1541         string aGroupName = aGroup->GetName();
1542         aGroupDS->SetStoreName( aGroupName.c_str() );
1543         myWriter.AddGroup( aGroupDS );
1544       }
1545     }
1546   }
1547   myWriter.Perform();
1548 }
1549
1550 //================================================================================
1551 /*!
1552  * \brief Export the mesh to an STL file
1553  */
1554 //================================================================================
1555
1556 void SMESH_Mesh::ExportSTL(const char *        file,
1557                            const bool          isascii,
1558                            const char *        name,
1559                            const SMESHDS_Mesh* meshPart) throw(SALOME_Exception)
1560 {
1561   Unexpect aCatch(SalomeException);
1562   DriverSTL_W_SMDS_Mesh myWriter;
1563   myWriter.SetFile( file );
1564   myWriter.SetIsAscii( isascii );
1565   myWriter.SetMesh( meshPart ? (SMESHDS_Mesh*) meshPart : _myMeshDS);
1566   myWriter.SetMeshId(_id);
1567   if ( name ) myWriter.SetName( name );
1568   myWriter.Perform();
1569 }
1570
1571 //================================================================================
1572 /*!
1573  * \brief Export the mesh to the CGNS file
1574  */
1575 //================================================================================
1576
1577 void SMESH_Mesh::ExportCGNS(const char *        file,
1578                             const SMESHDS_Mesh* meshDS,
1579                             const char *        meshName)
1580 {
1581   int res = Driver_Mesh::DRS_FAIL;
1582 #ifdef WITH_CGNS
1583   DriverCGNS_Write myWriter;
1584   myWriter.SetFile( file );
1585   myWriter.SetMesh( const_cast<SMESHDS_Mesh*>( meshDS ));
1586   myWriter.SetMeshName( SMESH_Comment("Mesh_") << meshDS->GetPersistentId());
1587   if ( meshName && meshName[0] )
1588     myWriter.SetMeshName( meshName );
1589   res = myWriter.Perform();
1590 #endif
1591   if ( res != Driver_Mesh::DRS_OK )
1592     throw SALOME_Exception("Export failed");
1593 }
1594
1595 //================================================================================
1596 /*!
1597  * \brief Export the mesh to a GMF file
1598  */
1599 //================================================================================
1600
1601 void SMESH_Mesh::ExportGMF(const char *        file,
1602                            const SMESHDS_Mesh* meshDS,
1603                            bool                withRequiredGroups)
1604 {
1605   DriverGMF_Write myWriter;
1606   myWriter.SetFile( file );
1607   myWriter.SetMesh( const_cast<SMESHDS_Mesh*>( meshDS ));
1608   myWriter.SetExportRequiredGroups( withRequiredGroups );
1609
1610   myWriter.Perform();
1611 }
1612
1613 //================================================================================
1614 /*!
1615  * \brief Return a ratio of "compute cost" of computed sub-meshes to the whole
1616  *        "compute cost".
1617  */
1618 //================================================================================
1619
1620 double SMESH_Mesh::GetComputeProgress() const
1621 {
1622   double totalCost = 1e-100, computedCost = 0;
1623   const SMESH_subMesh* curSM = _gen->GetCurrentSubMesh();
1624
1625   // get progress of a current algo
1626   TColStd_MapOfInteger currentSubIds; 
1627   if ( curSM )
1628     if ( SMESH_Algo* algo = curSM->GetAlgo() )
1629     {
1630       int algoNotDoneCost = 0, algoDoneCost = 0;
1631       const std::vector<SMESH_subMesh*>& smToCompute = algo->SubMeshesToCompute();
1632       for ( size_t i = 0; i < smToCompute.size(); ++i )
1633       {
1634         if ( smToCompute[i]->IsEmpty() || smToCompute.size() == 1 )
1635           algoNotDoneCost += smToCompute[i]->GetComputeCost();
1636         else
1637           algoDoneCost += smToCompute[i]->GetComputeCost();
1638         currentSubIds.Add( smToCompute[i]->GetId() );
1639       }
1640       double rate = 0;
1641       try
1642       {
1643         OCC_CATCH_SIGNALS;
1644         rate = algo->GetProgress();
1645       }
1646       catch (...) {
1647 #ifdef _DEBUG_
1648         cerr << "Exception in " << algo->GetName() << "::GetProgress()" << endl;
1649 #endif
1650       }
1651       if ( 0. < rate && rate < 1.001 )
1652       {
1653         computedCost += rate * ( algoDoneCost + algoNotDoneCost );
1654       }
1655       else
1656       {
1657         rate = algo->GetProgressByTic();
1658         computedCost += algoDoneCost + rate * algoNotDoneCost;
1659       }
1660       // cout << "rate: "<<rate << " algoNotDoneCost: " << algoNotDoneCost << endl;
1661     }
1662
1663   // get cost of already treated sub-meshes
1664   if ( SMESH_subMesh* mainSM = GetSubMeshContaining( 1 ))
1665   {
1666     SMESH_subMeshIteratorPtr smIt = mainSM->getDependsOnIterator(/*includeSelf=*/true);
1667     while ( smIt->more() )
1668     {
1669       const SMESH_subMesh* sm = smIt->next();
1670       const int smCost = sm->GetComputeCost();
1671       totalCost += smCost;
1672       if ( !currentSubIds.Contains( sm->GetId() ) )
1673       {
1674         if (( !sm->IsEmpty() ) ||
1675             ( sm->GetComputeState() == SMESH_subMesh::FAILED_TO_COMPUTE &&
1676               !sm->DependsOn( curSM ) ))
1677           computedCost += smCost;
1678       }
1679     }
1680   }
1681   // cout << "Total: " << totalCost
1682   //      << " computed: " << computedCost << " progress: " << computedCost / totalCost
1683   //      << " nbElems: " << GetMeshDS()->GetMeshInfo().NbElements() << endl;
1684   return computedCost / totalCost;
1685 }
1686
1687 //================================================================================
1688 /*!
1689  * \brief Return number of nodes in the mesh
1690  */
1691 //================================================================================
1692
1693 int SMESH_Mesh::NbNodes() const throw(SALOME_Exception)
1694 {
1695   Unexpect aCatch(SalomeException);
1696   return _myMeshDS->NbNodes();
1697 }
1698
1699 //================================================================================
1700 /*!
1701  * \brief  Return number of edges of given order in the mesh
1702  */
1703 //================================================================================
1704
1705 int SMESH_Mesh::Nb0DElements() const throw(SALOME_Exception)
1706 {
1707   Unexpect aCatch(SalomeException);
1708   return _myMeshDS->GetMeshInfo().Nb0DElements();
1709 }
1710
1711 //================================================================================
1712 /*!
1713  * \brief  Return number of edges of given order in the mesh
1714  */
1715 //================================================================================
1716
1717 int SMESH_Mesh::NbEdges(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1718 {
1719   Unexpect aCatch(SalomeException);
1720   return _myMeshDS->GetMeshInfo().NbEdges(order);
1721 }
1722
1723 //================================================================================
1724 /*!
1725  * \brief Return number of faces of given order in the mesh
1726  */
1727 //================================================================================
1728
1729 int SMESH_Mesh::NbFaces(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1730 {
1731   Unexpect aCatch(SalomeException);
1732   return _myMeshDS->GetMeshInfo().NbFaces(order);
1733 }
1734
1735 //================================================================================
1736 /*!
1737  * \brief Return the number of faces in the mesh
1738  */
1739 //================================================================================
1740
1741 int SMESH_Mesh::NbTriangles(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1742 {
1743   Unexpect aCatch(SalomeException);
1744   return _myMeshDS->GetMeshInfo().NbTriangles(order);
1745 }
1746
1747 //================================================================================
1748 /*!
1749  * \brief Return number of biquadratic triangles in the mesh
1750  */
1751 //================================================================================
1752
1753 int SMESH_Mesh::NbBiQuadTriangles() const throw(SALOME_Exception)
1754 {
1755   Unexpect aCatch(SalomeException);
1756   return _myMeshDS->GetMeshInfo().NbBiQuadTriangles();
1757 }
1758
1759 //================================================================================
1760 /*!
1761  * \brief Return the number nodes faces in the mesh
1762  */
1763 //================================================================================
1764
1765 int SMESH_Mesh::NbQuadrangles(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1766 {
1767   Unexpect aCatch(SalomeException);
1768   return _myMeshDS->GetMeshInfo().NbQuadrangles(order);
1769 }
1770
1771 //================================================================================
1772 /*!
1773  * \brief Return number of biquadratic quadrangles in the mesh
1774  */
1775 //================================================================================
1776
1777 int SMESH_Mesh::NbBiQuadQuadrangles() const throw(SALOME_Exception)
1778 {
1779   Unexpect aCatch(SalomeException);
1780   return _myMeshDS->GetMeshInfo().NbBiQuadQuadrangles();
1781 }
1782
1783 //================================================================================
1784 /*!
1785  * \brief Return the number of polygonal faces in the mesh
1786  */
1787 //================================================================================
1788
1789 int SMESH_Mesh::NbPolygons(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1790 {
1791   Unexpect aCatch(SalomeException);
1792   return _myMeshDS->GetMeshInfo().NbPolygons(order);
1793 }
1794
1795 //================================================================================
1796 /*!
1797  * \brief Return number of volumes of given order in the mesh
1798  */
1799 //================================================================================
1800
1801 int SMESH_Mesh::NbVolumes(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1802 {
1803   Unexpect aCatch(SalomeException);
1804   return _myMeshDS->GetMeshInfo().NbVolumes(order);
1805 }
1806
1807 //================================================================================
1808 /*!
1809  * \brief  Return number of tetrahedrons of given order in the mesh
1810  */
1811 //================================================================================
1812
1813 int SMESH_Mesh::NbTetras(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1814 {
1815   Unexpect aCatch(SalomeException);
1816   return _myMeshDS->GetMeshInfo().NbTetras(order);
1817 }
1818
1819 //================================================================================
1820 /*!
1821  * \brief  Return number of hexahedrons of given order in the mesh
1822  */
1823 //================================================================================
1824
1825 int SMESH_Mesh::NbHexas(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1826 {
1827   Unexpect aCatch(SalomeException);
1828   return _myMeshDS->GetMeshInfo().NbHexas(order);
1829 }
1830
1831 //================================================================================
1832 /*!
1833  * \brief  Return number of triquadratic hexahedrons in the mesh
1834  */
1835 //================================================================================
1836
1837 int SMESH_Mesh::NbTriQuadraticHexas() const throw(SALOME_Exception)
1838 {
1839   Unexpect aCatch(SalomeException);
1840   return _myMeshDS->GetMeshInfo().NbTriQuadHexas();
1841 }
1842
1843 //================================================================================
1844 /*!
1845  * \brief  Return number of pyramids of given order in the mesh
1846  */
1847 //================================================================================
1848
1849 int SMESH_Mesh::NbPyramids(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1850 {
1851   Unexpect aCatch(SalomeException);
1852   return _myMeshDS->GetMeshInfo().NbPyramids(order);
1853 }
1854
1855 //================================================================================
1856 /*!
1857  * \brief  Return number of prisms (penthahedrons) of given order in the mesh
1858  */
1859 //================================================================================
1860
1861 int SMESH_Mesh::NbPrisms(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1862 {
1863   Unexpect aCatch(SalomeException);
1864   return _myMeshDS->GetMeshInfo().NbPrisms(order);
1865 }
1866
1867 //================================================================================
1868 /*!
1869  * \brief  Return number of hexagonal prisms in the mesh
1870  */
1871 //================================================================================
1872
1873 int SMESH_Mesh::NbHexagonalPrisms() const throw(SALOME_Exception)
1874 {
1875   Unexpect aCatch(SalomeException);
1876   return _myMeshDS->GetMeshInfo().NbHexPrisms();
1877 }
1878
1879 //================================================================================
1880 /*!
1881  * \brief  Return number of polyhedrons in the mesh
1882  */
1883 //================================================================================
1884
1885 int SMESH_Mesh::NbPolyhedrons() const throw(SALOME_Exception)
1886 {
1887   Unexpect aCatch(SalomeException);
1888   return _myMeshDS->GetMeshInfo().NbPolyhedrons();
1889 }
1890
1891 //================================================================================
1892 /*!
1893  * \brief  Return number of ball elements in the mesh
1894  */
1895 //================================================================================
1896
1897 int SMESH_Mesh::NbBalls() const throw(SALOME_Exception)
1898 {
1899   Unexpect aCatch(SalomeException);
1900   return _myMeshDS->GetMeshInfo().NbBalls();
1901 }
1902
1903 //================================================================================
1904 /*!
1905  * \brief  Return number of submeshes in the mesh
1906  */
1907 //================================================================================
1908
1909 int SMESH_Mesh::NbSubMesh() const throw(SALOME_Exception)
1910 {
1911   Unexpect aCatch(SalomeException);
1912   return _myMeshDS->NbSubMesh();
1913 }
1914
1915 //================================================================================
1916 /*!
1917  * \brief Returns number of meshes in the Study, that is supposed to be
1918  *        equal to SMESHDS_Document::NbMeshes()
1919  */
1920 //================================================================================
1921
1922 int SMESH_Mesh::NbMeshes() const // nb meshes in the Study
1923 {
1924   return _myDocument->NbMeshes();
1925 }
1926
1927 //=======================================================================
1928 //function : IsNotConformAllowed
1929 //purpose  : check if a hypothesis allowing notconform mesh is present
1930 //=======================================================================
1931
1932 bool SMESH_Mesh::IsNotConformAllowed() const
1933 {
1934   if(MYDEBUG) MESSAGE("SMESH_Mesh::IsNotConformAllowed");
1935
1936   static SMESH_HypoFilter filter( SMESH_HypoFilter::HasName( "NotConformAllowed" ));
1937   return GetHypothesis( _myMeshDS->ShapeToMesh(), filter, false );
1938 }
1939
1940 //=======================================================================
1941 //function : IsMainShape
1942 //purpose  : 
1943 //=======================================================================
1944
1945 bool SMESH_Mesh::IsMainShape(const TopoDS_Shape& theShape) const
1946 {
1947   return theShape.IsSame(_myMeshDS->ShapeToMesh() );
1948 }
1949
1950 //=============================================================================
1951 /*!
1952  *  
1953  */
1954 //=============================================================================
1955
1956 SMESH_Group* SMESH_Mesh::AddGroup (const SMDSAbs_ElementType theType,
1957                                    const char*               theName,
1958                                    int&                      theId,
1959                                    const TopoDS_Shape&       theShape,
1960                                    const SMESH_PredicatePtr& thePredicate)
1961 {
1962   if (_mapGroup.count(_groupId))
1963     return NULL;
1964   theId = _groupId;
1965   SMESH_Group* aGroup = new SMESH_Group (theId, this, theType, theName, theShape, thePredicate);
1966   GetMeshDS()->AddGroup( aGroup->GetGroupDS() );
1967   _mapGroup[_groupId++] = aGroup;
1968   return aGroup;
1969 }
1970
1971 //================================================================================
1972 /*!
1973  * \brief Creates a group based on an existing SMESHDS group. Group ID should be unique
1974  */
1975 //================================================================================
1976
1977 SMESH_Group* SMESH_Mesh::AddGroup (SMESHDS_GroupBase* groupDS) throw(SALOME_Exception)
1978 {
1979   if ( !groupDS ) 
1980     throw SALOME_Exception(LOCALIZED ("SMESH_Mesh::AddGroup(): NULL SMESHDS_GroupBase"));
1981
1982   map <int, SMESH_Group*>::iterator i_g = _mapGroup.find( groupDS->GetID() );
1983   if ( i_g != _mapGroup.end() && i_g->second )
1984   {
1985     if ( i_g->second->GetGroupDS() == groupDS )
1986       return i_g->second;
1987     else
1988       throw SALOME_Exception(LOCALIZED ("SMESH_Mesh::AddGroup() wrong ID of SMESHDS_GroupBase"));
1989   }
1990   SMESH_Group* aGroup = new SMESH_Group (groupDS);
1991   _mapGroup[ groupDS->GetID() ] = aGroup;
1992   GetMeshDS()->AddGroup( aGroup->GetGroupDS() );
1993
1994   _groupId = 1 + _mapGroup.rbegin()->first;
1995
1996   return aGroup;
1997 }
1998
1999
2000 //================================================================================
2001 /*!
2002  * \brief Creates SMESH_Groups for not wrapped SMESHDS_Groups
2003  *  \retval bool - true if new SMESH_Groups have been created
2004  * 
2005  */
2006 //================================================================================
2007
2008 bool SMESH_Mesh::SynchronizeGroups()
2009 {
2010   const size_t                       nbGroups = _mapGroup.size();
2011   const set<SMESHDS_GroupBase*>&       groups = _myMeshDS->GetGroups();
2012   set<SMESHDS_GroupBase*>::const_iterator gIt = groups.begin();
2013   for ( ; gIt != groups.end(); ++gIt )
2014   {
2015     SMESHDS_GroupBase* groupDS = (SMESHDS_GroupBase*) *gIt;
2016     _groupId = groupDS->GetID();
2017     if ( !_mapGroup.count( _groupId ))
2018       _mapGroup[_groupId] = new SMESH_Group( groupDS );
2019   }
2020   if ( !_mapGroup.empty() )
2021     _groupId = _mapGroup.rbegin()->first + 1;
2022
2023   return nbGroups < _mapGroup.size();
2024 }
2025
2026 //================================================================================
2027 /*!
2028  * \brief Return iterator on all existing groups
2029  */
2030 //================================================================================
2031
2032 SMESH_Mesh::GroupIteratorPtr SMESH_Mesh::GetGroups() const
2033 {
2034   typedef map <int, SMESH_Group *> TMap;
2035   return GroupIteratorPtr( new SMDS_mapIterator<TMap>( _mapGroup ));
2036 }
2037
2038 //=============================================================================
2039 /*!
2040  * \brief Return a group by ID
2041  */
2042 //=============================================================================
2043
2044 SMESH_Group* SMESH_Mesh::GetGroup (const int theGroupID)
2045 {
2046   if (_mapGroup.find(theGroupID) == _mapGroup.end())
2047     return NULL;
2048   return _mapGroup[theGroupID];
2049 }
2050
2051
2052 //=============================================================================
2053 /*!
2054  * \brief Return IDs of all groups
2055  */
2056 //=============================================================================
2057
2058 list<int> SMESH_Mesh::GetGroupIds() const
2059 {
2060   list<int> anIds;
2061   for ( map<int, SMESH_Group*>::const_iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ )
2062     anIds.push_back( it->first );
2063   
2064   return anIds;
2065 }
2066
2067 //================================================================================
2068 /*!
2069  * \brief Set a caller of methods at level of CORBA API implementation.
2070  * The set upCaller will be deleted by SMESH_Mesh
2071  */
2072 //================================================================================
2073
2074 void SMESH_Mesh::SetCallUp( TCallUp* upCaller )
2075 {
2076   if ( _callUp ) delete _callUp;
2077   _callUp = upCaller;
2078 }
2079
2080 //=============================================================================
2081 /*!
2082  *  
2083  */
2084 //=============================================================================
2085
2086 bool SMESH_Mesh::RemoveGroup( const int theGroupID )
2087 {
2088   if (_mapGroup.find(theGroupID) == _mapGroup.end())
2089     return false;
2090   GetMeshDS()->RemoveGroup( _mapGroup[theGroupID]->GetGroupDS() );
2091   delete _mapGroup[theGroupID];
2092   _mapGroup.erase (theGroupID);
2093   if (_callUp)
2094     _callUp->RemoveGroup( theGroupID );
2095   return true;
2096 }
2097
2098 //=======================================================================
2099 //function : GetAncestors
2100 //purpose  : return list of ancestors of theSubShape in the order
2101 //           that lower dimension shapes come first.
2102 //=======================================================================
2103
2104 const TopTools_ListOfShape& SMESH_Mesh::GetAncestors(const TopoDS_Shape& theS) const
2105 {
2106   if ( _mapAncestors.Contains( theS ) )
2107     return _mapAncestors.FindFromKey( theS );
2108
2109   static TopTools_ListOfShape emptyList;
2110   return emptyList;
2111 }
2112
2113 //=======================================================================
2114 //function : Dump
2115 //purpose  : dumps contents of mesh to stream [ debug purposes ]
2116 //=======================================================================
2117
2118 ostream& SMESH_Mesh::Dump(ostream& save)
2119 {
2120   int clause = 0;
2121   save << "========================== Dump contents of mesh ==========================" << endl << endl;
2122   save << ++clause << ") Total number of nodes:      \t" << NbNodes() << endl;
2123   save << ++clause << ") Total number of edges:      \t" << NbEdges() << endl;
2124   save << ++clause << ") Total number of faces:      \t" << NbFaces() << endl;
2125   save << ++clause << ") Total number of polygons:   \t" << NbPolygons() << endl;
2126   save << ++clause << ") Total number of volumes:    \t" << NbVolumes() << endl;
2127   save << ++clause << ") Total number of polyhedrons:\t" << NbPolyhedrons() << endl << endl;
2128   for ( int isQuadratic = 0; isQuadratic < 2; ++isQuadratic )
2129   {
2130     string orderStr = isQuadratic ? "quadratic" : "linear";
2131     SMDSAbs_ElementOrder order  = isQuadratic ? ORDER_QUADRATIC : ORDER_LINEAR;
2132
2133     save << ++clause << ") Total number of " << orderStr << " edges:\t" << NbEdges(order) << endl;
2134     save << ++clause << ") Total number of " << orderStr << " faces:\t" << NbFaces(order) << endl;
2135     if ( NbFaces(order) > 0 ) {
2136       int nb3 = NbTriangles(order);
2137       int nb4 = NbQuadrangles(order);
2138       save << clause << ".1) Number of " << orderStr << " triangles:  \t" << nb3 << endl;
2139       save << clause << ".2) Number of " << orderStr << " quadrangles:\t" << nb4 << endl;
2140       if ( nb3 + nb4 !=  NbFaces(order) ) {
2141         map<int,int> myFaceMap;
2142         SMDS_FaceIteratorPtr itFaces=_myMeshDS->facesIterator();
2143         while( itFaces->more( ) ) {
2144           int nbNodes = itFaces->next()->NbNodes();
2145           if ( myFaceMap.find( nbNodes ) == myFaceMap.end() )
2146             myFaceMap[ nbNodes ] = 0;
2147           myFaceMap[ nbNodes ] = myFaceMap[ nbNodes ] + 1;
2148         }
2149         save << clause << ".3) Faces in detail: " << endl;
2150         map <int,int>::iterator itF;
2151         for (itF = myFaceMap.begin(); itF != myFaceMap.end(); itF++)
2152           save << "--> nb nodes: " << itF->first << " - nb elemens:\t" << itF->second << endl;
2153       }
2154     }
2155     save << ++clause << ") Total number of " << orderStr << " volumes:\t" << NbVolumes(order) << endl;
2156     if ( NbVolumes(order) > 0 ) {
2157       int nb8 = NbHexas(order);
2158       int nb4 = NbTetras(order);
2159       int nb5 = NbPyramids(order);
2160       int nb6 = NbPrisms(order);
2161       save << clause << ".1) Number of " << orderStr << " hexahedrons: \t" << nb8 << endl;
2162       save << clause << ".2) Number of " << orderStr << " tetrahedrons:\t" << nb4 << endl;
2163       save << clause << ".3) Number of " << orderStr << " prisms:      \t" << nb6 << endl;
2164       save << clause << ".4) Number of " << orderStr << " pyramids:    \t" << nb5 << endl;
2165       if ( nb8 + nb4 + nb5 + nb6 != NbVolumes(order) ) {
2166         map<int,int> myVolumesMap;
2167         SMDS_VolumeIteratorPtr itVolumes=_myMeshDS->volumesIterator();
2168         while( itVolumes->more( ) ) {
2169           int nbNodes = itVolumes->next()->NbNodes();
2170           if ( myVolumesMap.find( nbNodes ) == myVolumesMap.end() )
2171             myVolumesMap[ nbNodes ] = 0;
2172           myVolumesMap[ nbNodes ] = myVolumesMap[ nbNodes ] + 1;
2173         }
2174         save << clause << ".5) Volumes in detail: " << endl;
2175         map <int,int>::iterator itV;
2176         for (itV = myVolumesMap.begin(); itV != myVolumesMap.end(); itV++)
2177           save << "--> nb nodes: " << itV->first << " - nb elemens:\t" << itV->second << endl;
2178       }
2179     }
2180     save << endl;
2181   }
2182   save << "===========================================================================" << endl;
2183   return save;
2184 }
2185
2186 //=======================================================================
2187 //function : GetElementType
2188 //purpose  : Returns type of mesh element with certain id
2189 //=======================================================================
2190
2191 SMDSAbs_ElementType SMESH_Mesh::GetElementType( const int id, const bool iselem )
2192 {
2193   return _myMeshDS->GetElementType( id, iselem );
2194 }
2195
2196 //=============================================================================
2197 /*!
2198  *  \brief Convert group on geometry into standalone group
2199  */
2200 //=============================================================================
2201
2202 SMESH_Group* SMESH_Mesh::ConvertToStandalone ( int theGroupID )
2203 {
2204   SMESH_Group* aGroup = 0;
2205   map < int, SMESH_Group * >::iterator itg = _mapGroup.find( theGroupID );
2206   if ( itg == _mapGroup.end() )
2207     return aGroup;
2208
2209   SMESH_Group* anOldGrp = (*itg).second;
2210   if ( !anOldGrp || !anOldGrp->GetGroupDS() )
2211     return aGroup;
2212   SMESHDS_GroupBase* anOldGrpDS = anOldGrp->GetGroupDS();
2213
2214   // create new standalone group
2215   aGroup = new SMESH_Group (theGroupID, this, anOldGrpDS->GetType(), anOldGrp->GetName() );
2216   _mapGroup[theGroupID] = aGroup;
2217
2218   SMESHDS_Group* aNewGrpDS = dynamic_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
2219   GetMeshDS()->RemoveGroup( anOldGrpDS );
2220   GetMeshDS()->AddGroup( aNewGrpDS );
2221
2222   // add elements (or nodes) into new created group
2223   SMDS_ElemIteratorPtr anItr = anOldGrpDS->GetElements();
2224   while ( anItr->more() )
2225     aNewGrpDS->Add( (anItr->next())->GetID() );
2226
2227   // set color
2228   aNewGrpDS->SetColor( anOldGrpDS->GetColor() );
2229
2230   // remove old group
2231   delete anOldGrp;
2232
2233   return aGroup;
2234 }
2235
2236 //=============================================================================
2237 /*!
2238  *  \brief remove submesh order  from Mesh
2239  */
2240 //=============================================================================
2241
2242 void SMESH_Mesh::ClearMeshOrder()
2243 {
2244   _mySubMeshOrder.clear();
2245 }
2246
2247 //=============================================================================
2248 /*!
2249  *  \brief remove submesh order  from Mesh
2250  */
2251 //=============================================================================
2252
2253 void SMESH_Mesh::SetMeshOrder(const TListOfListOfInt& theOrder )
2254 {
2255   _mySubMeshOrder = theOrder;
2256 }
2257
2258 //=============================================================================
2259 /*!
2260  *  \brief return submesh order if any
2261  */
2262 //=============================================================================
2263
2264 const TListOfListOfInt& SMESH_Mesh::GetMeshOrder() const
2265 {
2266   return _mySubMeshOrder;
2267 }
2268
2269 //=============================================================================
2270 /*!
2271  *  \brief fill _mapAncestors
2272  */
2273 //=============================================================================
2274
2275 void SMESH_Mesh::fillAncestorsMap(const TopoDS_Shape& theShape)
2276 {
2277   int desType, ancType;
2278   if ( !theShape.IsSame( GetShapeToMesh()) && theShape.ShapeType() == TopAbs_COMPOUND )
2279   {
2280     // a geom group is added. Insert it into lists of ancestors before
2281     // the first ancestor more complex than group members
2282     TopoDS_Iterator subIt( theShape );
2283     if ( !subIt.More() ) return;
2284     int memberType = subIt.Value().ShapeType();
2285     for ( desType = TopAbs_VERTEX; desType >= memberType; desType-- )
2286       for (TopExp_Explorer des( theShape, TopAbs_ShapeEnum( desType )); des.More(); des.Next())
2287       {
2288         if ( !_mapAncestors.Contains( des.Current() )) continue;// issue 0020982
2289         TopTools_ListOfShape& ancList = _mapAncestors.ChangeFromKey( des.Current() );
2290         TopTools_ListIteratorOfListOfShape ancIt (ancList);
2291         while ( ancIt.More() && ancIt.Value().ShapeType() >= memberType )
2292           ancIt.Next();
2293         if ( ancIt.More() ) ancList.InsertBefore( theShape, ancIt );
2294         else                ancList.Append( theShape );
2295       }
2296   }
2297   else // else added for 52457: Addition of hypotheses is 8 time longer than meshing
2298   {
2299     for ( desType = TopAbs_VERTEX; desType > TopAbs_COMPOUND; desType-- )
2300       for ( ancType = desType - 1; ancType >= TopAbs_COMPOUND; ancType-- )
2301         TopExp::MapShapesAndAncestors ( theShape,
2302                                         (TopAbs_ShapeEnum) desType,
2303                                         (TopAbs_ShapeEnum) ancType,
2304                                         _mapAncestors );
2305   }
2306   // visit COMPOUNDs inside a COMPOUND that are not reachable by TopExp_Explorer
2307   if ( theShape.ShapeType() == TopAbs_COMPOUND )
2308   {
2309     TopoDS_Iterator sIt(theShape);
2310     if ( sIt.More() && sIt.Value().ShapeType() == TopAbs_COMPOUND )
2311       for ( ; sIt.More(); sIt.Next() )
2312         if ( sIt.Value().ShapeType() == TopAbs_COMPOUND )
2313           fillAncestorsMap( sIt.Value() );
2314   }
2315 }
2316
2317 //=============================================================================
2318 /*!
2319  * \brief sort submeshes according to stored mesh order
2320  * \param theListToSort in out list to be sorted
2321  * \return FALSE if nothing sorted
2322  */
2323 //=============================================================================
2324
2325 bool SMESH_Mesh::SortByMeshOrder(std::vector<SMESH_subMesh*>& theListToSort) const
2326 {
2327   if ( !_mySubMeshOrder.size() || theListToSort.size() < 2)
2328     return true;
2329   
2330   bool res = false;
2331   vector<SMESH_subMesh*> onlyOrderedList, smVec;
2332
2333   // collect all ordered submeshes in one list as pointers
2334   // and get their positions within theListToSort
2335   typedef vector<SMESH_subMesh*>::iterator TPosInList;
2336   map< int, TPosInList > sortedPos;
2337   TPosInList smBeg = theListToSort.begin(), smEnd = theListToSort.end();
2338   TListOfListOfInt::const_iterator      listIdsIt = _mySubMeshOrder.begin();
2339   for( ; listIdsIt != _mySubMeshOrder.end(); listIdsIt++)
2340   {
2341     const TListOfInt& listOfId = *listIdsIt;
2342     // convert sm ids to sm's
2343     smVec.clear();
2344     TListOfInt::const_iterator idIt = listOfId.begin();
2345     for ( ; idIt != listOfId.end(); idIt++ )
2346     {
2347       if ( SMESH_subMesh * sm = GetSubMeshContaining( *idIt ))
2348       {
2349         smVec.push_back( sm );
2350         if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->IsComplexSubmesh() )
2351         {
2352           SMESHDS_SubMeshIteratorPtr smdsIt = sm->GetSubMeshDS()->GetSubMeshIterator();
2353           while ( smdsIt->more() )
2354           {
2355             const SMESHDS_SubMesh* smDS = smdsIt->next();
2356             if (( sm = GetSubMeshContaining( smDS->GetID() )))
2357               smVec.push_back( sm );
2358           }
2359         }
2360       }
2361     }
2362     // find smVec items in theListToSort
2363     for ( size_t i = 0; i < smVec.size(); ++i )
2364     {
2365       TPosInList smPos = find( smBeg, smEnd, smVec[i] );
2366       if ( smPos != smEnd ) {
2367         onlyOrderedList.push_back( smVec[i] );
2368         sortedPos[ distance( smBeg, smPos )] = smPos;
2369       }
2370     }
2371   }
2372   if (onlyOrderedList.size() < 2)
2373     return res;
2374   res = true;
2375
2376   vector<SMESH_subMesh*>::iterator onlyBIt = onlyOrderedList.begin();
2377   vector<SMESH_subMesh*>::iterator onlyEIt = onlyOrderedList.end();
2378
2379   // iterate on ordered sub-meshes and insert them in detected positions
2380   map< int, TPosInList >::iterator i_pos = sortedPos.begin();
2381   for ( ; onlyBIt != onlyEIt; ++onlyBIt, ++i_pos )
2382     *(i_pos->second) = *onlyBIt;
2383
2384   return res;
2385 }
2386
2387 //================================================================================
2388 /*!
2389  * \brief Return true if given order of sub-meshes is OK
2390  */
2391 //================================================================================
2392
2393 bool SMESH_Mesh::IsOrderOK( const SMESH_subMesh* smBefore,
2394                             const SMESH_subMesh* smAfter ) const
2395 {
2396   TListOfListOfInt::const_iterator listIdsIt = _mySubMeshOrder.begin();
2397   for( ; listIdsIt != _mySubMeshOrder.end(); listIdsIt++)
2398   {
2399     const TListOfInt& listOfId = *listIdsIt;
2400     int iB = -1, iA = -1, i = 0;
2401     for ( TListOfInt::const_iterator id = listOfId.begin(); id != listOfId.end(); ++id, ++i )
2402     {
2403       if ( *id == smBefore->GetId() )
2404       {
2405         iB = i;
2406         if ( iA > -1 )
2407           return iB < iA;
2408       }
2409       else if ( *id == smAfter->GetId() )
2410       {
2411         iA = i;
2412         if ( iB > -1 )
2413           return iB < iA;
2414       }
2415     }
2416   }
2417   return true; // no order imposed to given sub-meshes
2418
2419
2420 //=============================================================================
2421 /*!
2422  * \brief sort submeshes according to stored mesh order
2423  * \param theListToSort in out list to be sorted
2424  * \return FALSE if nothing sorted
2425  */
2426 //=============================================================================
2427
2428 void SMESH_Mesh::getAncestorsSubMeshes (const TopoDS_Shape&            theSubShape,
2429                                         std::vector< SMESH_subMesh* >& theSubMeshes) const
2430 {
2431   theSubMeshes.clear();
2432   TopTools_ListIteratorOfListOfShape it( GetAncestors( theSubShape ));
2433   for (; it.More(); it.Next() )
2434     if ( SMESH_subMesh* sm = GetSubMeshContaining( it.Value() ))
2435       theSubMeshes.push_back(sm);
2436
2437   // sort submeshes according to stored mesh order
2438   SortByMeshOrder( theSubMeshes );
2439 }