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