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