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