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