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