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