Salome HOME
020697: EDF 1248 SMESH: Sub-mesh on group of face not taken into account
[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 ancestors
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   if(MYDEBUG) 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   if(MYDEBUG) {
564     int hypType = anHyp->GetType();
565     SCRUTE(hypType);
566   }
567   
568   // shape 
569   
570   bool isAlgo = ( !anHyp->GetType() == SMESHDS_Hypothesis::PARAM_ALGO );
571   int event = isAlgo ? SMESH_subMesh::REMOVE_ALGO : SMESH_subMesh::REMOVE_HYP;
572
573   SMESH_subMesh *subMesh = GetSubMesh(aSubShape);
574
575   SMESH_Hypothesis::Hypothesis_Status ret = subMesh->AlgoStateEngine(event, anHyp);
576
577   // there may appear concurrent hyps that were covered by the removed hyp
578   if (ret < SMESH_Hypothesis::HYP_CONCURENT &&
579       subMesh->IsApplicableHypotesis( anHyp ) &&
580       subMesh->CheckConcurentHypothesis( anHyp->GetType() ) != SMESH_Hypothesis::HYP_OK)
581     ret = SMESH_Hypothesis::HYP_CONCURENT;
582
583   // subShapes
584   if (!SMESH_Hypothesis::IsStatusFatal(ret) &&
585       anHyp->GetDim() <= SMESH_Gen::GetShapeDim(aSubShape)) // is removed from father
586   {
587     event = isAlgo ? SMESH_subMesh::REMOVE_FATHER_ALGO : SMESH_subMesh::REMOVE_FATHER_HYP;
588
589     SMESH_Hypothesis::Hypothesis_Status ret2 =
590       subMesh->SubMeshesAlgoStateEngine(event, anHyp);
591     if (ret2 > ret) // more severe
592       ret = ret2;
593
594     // check concurent hypotheses on ancestors
595     if (ret < SMESH_Hypothesis::HYP_CONCURENT && !IsMainShape( aSubShape ) )
596     {
597       SMESH_subMeshIteratorPtr smIt = subMesh->getDependsOnIterator(false,false);
598       while ( smIt->more() ) {
599         SMESH_subMesh* sm = smIt->next();
600         if ( sm->IsApplicableHypotesis( anHyp )) {
601           ret2 = sm->CheckConcurentHypothesis( anHyp->GetType() );
602           if (ret2 > ret) {
603             ret = ret2;
604             break;
605           }
606         }
607       }
608     }
609   }
610   
611   if(MYDEBUG) subMesh->DumpAlgoState(true);
612   if(MYDEBUG) SCRUTE(ret);
613   return ret;
614 }
615
616 //=============================================================================
617 /*!
618  * 
619  */
620 //=============================================================================
621
622 const list<const SMESHDS_Hypothesis*>&
623 SMESH_Mesh::GetHypothesisList(const TopoDS_Shape & aSubShape) const
624   throw(SALOME_Exception)
625 {
626   Unexpect aCatch(SalomeException);
627   return _myMeshDS->GetHypothesis(aSubShape);
628 }
629
630 //=======================================================================
631 /*!
632  * \brief Return the hypothesis assigned to the shape
633  *  \param aSubShape    - the shape to check
634  *  \param aFilter      - the hypothesis filter
635  *  \param andAncestors - flag to check hypos assigned to ancestors of the shape
636  *  \param assignedTo   - to return the shape the found hypo is assigned to
637  *  \retval SMESH_Hypothesis* - the first hypo passed through aFilter
638  */
639 //=======================================================================
640
641 const SMESH_Hypothesis * SMESH_Mesh::GetHypothesis(const TopoDS_Shape &    aSubShape,
642                                                    const SMESH_HypoFilter& aFilter,
643                                                    const bool              andAncestors,
644                                                    TopoDS_Shape*           assignedTo) const
645 {
646   {
647     const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(aSubShape);
648     list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
649     for ( ; hyp != hypList.end(); hyp++ ) {
650       const SMESH_Hypothesis * h = cSMESH_Hyp( *hyp );
651       if ( aFilter.IsOk( h, aSubShape)) {
652         if ( assignedTo ) *assignedTo = aSubShape;
653         return h;
654       }
655     }
656   }
657   if ( andAncestors )
658   {
659     // user sorted submeshes of ancestors, according to stored submesh priority
660     const list<SMESH_subMesh*> smList = getAncestorsSubMeshes( aSubShape );
661     list<SMESH_subMesh*>::const_iterator smIt = smList.begin(); 
662     for ( ; smIt != smList.end(); smIt++ )
663     {
664       const TopoDS_Shape& curSh = (*smIt)->GetSubShape();
665       const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(curSh);
666       list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
667       for ( ; hyp != hypList.end(); hyp++ ) {
668         const SMESH_Hypothesis * h = cSMESH_Hyp( *hyp );
669         if (aFilter.IsOk( h, curSh )) {
670           if ( assignedTo ) *assignedTo = curSh;
671           return h;
672         }
673       }
674     }
675   }
676   return 0;
677 }
678
679 //================================================================================
680 /*!
681  * \brief Return hypothesis assigned to the shape
682   * \param aSubShape - the shape to check
683   * \param aFilter - the hypothesis filter
684   * \param aHypList - the list of the found hypotheses
685   * \param andAncestors - flag to check hypos assigned to ancestors of the shape
686   * \retval int - number of unique hypos in aHypList
687  */
688 //================================================================================
689
690 int SMESH_Mesh::GetHypotheses(const TopoDS_Shape &                aSubShape,
691                               const SMESH_HypoFilter&             aFilter,
692                               list <const SMESHDS_Hypothesis * >& aHypList,
693                               const bool                          andAncestors) const
694 {
695   set<string> hypTypes; // to exclude same type hypos from the result list
696   int nbHyps = 0;
697
698   // only one main hypothesis is allowed
699   bool mainHypFound = false;
700
701   // fill in hypTypes
702   list<const SMESHDS_Hypothesis*>::const_iterator hyp;
703   for ( hyp = aHypList.begin(); hyp != aHypList.end(); hyp++ ) {
704     if ( hypTypes.insert( (*hyp)->GetName() ).second )
705       nbHyps++;
706     if ( !cSMESH_Hyp(*hyp)->IsAuxiliary() )
707       mainHypFound = true;
708   }
709
710   // get hypos from aSubShape
711   {
712     const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(aSubShape);
713     for ( hyp = hypList.begin(); hyp != hypList.end(); hyp++ )
714       if ( aFilter.IsOk (cSMESH_Hyp( *hyp ), aSubShape) &&
715            ( cSMESH_Hyp(*hyp)->IsAuxiliary() || !mainHypFound ) &&
716            hypTypes.insert( (*hyp)->GetName() ).second )
717       {
718         aHypList.push_back( *hyp );
719         nbHyps++;
720         if ( !cSMESH_Hyp(*hyp)->IsAuxiliary() )
721           mainHypFound = true;
722       }
723   }
724
725   // get hypos from ancestors of aSubShape
726   if ( andAncestors )
727   {
728     TopTools_MapOfShape map;
729
730     // user sorted submeshes of ancestors, according to stored submesh priority
731     const list<SMESH_subMesh*> smList = getAncestorsSubMeshes( aSubShape );
732     list<SMESH_subMesh*>::const_iterator smIt = smList.begin(); 
733     for ( ; smIt != smList.end(); smIt++ )
734     {
735       const TopoDS_Shape& curSh = (*smIt)->GetSubShape();
736      if ( !map.Add( curSh ))
737         continue;
738       const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(curSh);
739       for ( hyp = hypList.begin(); hyp != hypList.end(); hyp++ )
740         if (aFilter.IsOk( cSMESH_Hyp( *hyp ), curSh ) &&
741             ( cSMESH_Hyp(*hyp)->IsAuxiliary() || !mainHypFound ) &&
742             hypTypes.insert( (*hyp)->GetName() ).second )
743         {
744           aHypList.push_back( *hyp );
745           nbHyps++;
746           if ( !cSMESH_Hyp(*hyp)->IsAuxiliary() )
747             mainHypFound = true;
748         }
749     }
750   }
751   return nbHyps;
752 }
753
754 //=============================================================================
755 /*!
756  * 
757  */
758 //=============================================================================
759
760 const list<SMESHDS_Command*> & SMESH_Mesh::GetLog() throw(SALOME_Exception)
761 {
762   Unexpect aCatch(SalomeException);
763   if(MYDEBUG) MESSAGE("SMESH_Mesh::GetLog");
764   return _myMeshDS->GetScript()->GetCommands();
765 }
766
767 //=============================================================================
768 /*!
769  * 
770  */
771 //=============================================================================
772 void SMESH_Mesh::ClearLog() throw(SALOME_Exception)
773 {
774   Unexpect aCatch(SalomeException);
775   if(MYDEBUG) MESSAGE("SMESH_Mesh::ClearLog");
776   _myMeshDS->GetScript()->Clear();
777 }
778
779 //=============================================================================
780 /*!
781  * Get or Create the SMESH_subMesh object implementation
782  */
783 //=============================================================================
784
785 SMESH_subMesh *SMESH_Mesh::GetSubMesh(const TopoDS_Shape & aSubShape)
786   throw(SALOME_Exception)
787 {
788   Unexpect aCatch(SalomeException);
789   SMESH_subMesh *aSubMesh;
790   int index = _myMeshDS->ShapeToIndex(aSubShape);
791
792   // for submeshes on GEOM Group
793   if (( !index || index > _nbSubShapes ) && aSubShape.ShapeType() == TopAbs_COMPOUND ) {
794     TopoDS_Iterator it( aSubShape );
795     if ( it.More() )
796     {
797       index = _myMeshDS->AddCompoundSubmesh( aSubShape, it.Value().ShapeType() );
798       if ( index > _nbSubShapes ) _nbSubShapes = index; // not to create sm for this group again
799
800       // fill map of Ancestors
801       fillAncestorsMap(aSubShape);
802     }
803   }
804 //   if ( !index )
805 //     return NULL; // neither sub-shape nor a group
806
807   map <int, SMESH_subMesh *>::iterator i_sm = _mapSubMesh.find(index);
808   if ( i_sm != _mapSubMesh.end())
809   {
810     aSubMesh = i_sm->second;
811   }
812   else
813   {
814     aSubMesh = new SMESH_subMesh(index, this, _myMeshDS, aSubShape);
815     _mapSubMesh[index] = aSubMesh;
816     ClearMeshOrder();
817   }
818   return aSubMesh;
819 }
820
821 //=============================================================================
822 /*!
823  * Get the SMESH_subMesh object implementation. Dont create it, return null
824  * if it does not exist.
825  */
826 //=============================================================================
827
828 SMESH_subMesh *SMESH_Mesh::GetSubMeshContaining(const TopoDS_Shape & aSubShape) const
829   throw(SALOME_Exception)
830 {
831   Unexpect aCatch(SalomeException);
832   SMESH_subMesh *aSubMesh = NULL;
833   
834   int index = _myMeshDS->ShapeToIndex(aSubShape);
835
836   map <int, SMESH_subMesh *>::const_iterator i_sm = _mapSubMesh.find(index);
837   if ( i_sm != _mapSubMesh.end())
838     aSubMesh = i_sm->second;
839
840   return aSubMesh;
841 }
842 //=============================================================================
843 /*!
844  * Get the SMESH_subMesh object implementation. Dont create it, return null
845  * if it does not exist.
846  */
847 //=============================================================================
848
849 SMESH_subMesh *SMESH_Mesh::GetSubMeshContaining(const int aShapeID) const
850 throw(SALOME_Exception)
851 {
852   Unexpect aCatch(SalomeException);
853   
854   map <int, SMESH_subMesh *>::const_iterator i_sm = _mapSubMesh.find(aShapeID);
855   if (i_sm == _mapSubMesh.end())
856     return NULL;
857   return i_sm->second;
858 }
859 //================================================================================
860 /*!
861  * \brief Return submeshes of groups containing the given subshape
862  */
863 //================================================================================
864
865 list<SMESH_subMesh*>
866 SMESH_Mesh::GetGroupSubMeshesContaining(const TopoDS_Shape & aSubShape) const
867   throw(SALOME_Exception)
868 {
869   Unexpect aCatch(SalomeException);
870   list<SMESH_subMesh*> found;
871
872   SMESH_subMesh * subMesh = GetSubMeshContaining(aSubShape);
873   if ( !subMesh )
874     return found;
875
876   // submeshes of groups have max IDs, so search from the map end
877   map<int, SMESH_subMesh *>::const_reverse_iterator i_sm;
878   for ( i_sm = _mapSubMesh.rbegin(); i_sm != _mapSubMesh.rend(); ++i_sm) {
879     SMESHDS_SubMesh * ds = i_sm->second->GetSubMeshDS();
880     if ( ds && ds->IsComplexSubmesh() ) {
881       TopExp_Explorer exp( i_sm->second->GetSubShape(), aSubShape.ShapeType() );
882       for ( ; exp.More(); exp.Next() ) {
883         if ( aSubShape.IsSame( exp.Current() )) {
884           found.push_back( i_sm->second );
885           break;
886         }
887       }
888     } else {
889       break;
890     }
891   }
892   return found;
893 }
894 //=======================================================================
895 //function : IsUsedHypothesis
896 //purpose  : Return True if anHyp is used to mesh aSubShape
897 //=======================================================================
898
899 bool SMESH_Mesh::IsUsedHypothesis(SMESHDS_Hypothesis * anHyp,
900                                   const SMESH_subMesh* aSubMesh)
901 {
902   SMESH_Hypothesis* hyp = static_cast<SMESH_Hypothesis*>(anHyp);
903
904   // check if anHyp can be used to mesh aSubMesh
905   if ( !aSubMesh || !aSubMesh->IsApplicableHypotesis( hyp ))
906     return false;
907
908   const TopoDS_Shape & aSubShape = const_cast<SMESH_subMesh*>( aSubMesh )->GetSubShape();
909
910   SMESH_Algo *algo = _gen->GetAlgo(*this, aSubShape );
911
912   // algorithm
913   if (anHyp->GetType() > SMESHDS_Hypothesis::PARAM_ALGO)
914     return ( anHyp == algo );
915
916   // algorithm parameter
917   if (algo)
918   {
919     // look trough hypotheses used by algo
920     SMESH_HypoFilter hypoKind;
921     if ( algo->InitCompatibleHypoFilter( hypoKind, !hyp->IsAuxiliary() )) {
922       list <const SMESHDS_Hypothesis * > usedHyps;
923       if ( GetHypotheses( aSubShape, hypoKind, usedHyps, true ))
924         return ( find( usedHyps.begin(), usedHyps.end(), anHyp ) != usedHyps.end() );
925     }
926   }
927
928   // look through all assigned hypotheses
929   //SMESH_HypoFilter filter( SMESH_HypoFilter::Is( hyp ));
930   return false; //GetHypothesis( aSubShape, filter, true );
931 }
932
933 //=============================================================================
934 /*!
935  *
936  */
937 //=============================================================================
938
939 const list < SMESH_subMesh * >&
940 SMESH_Mesh::GetSubMeshUsingHypothesis(SMESHDS_Hypothesis * anHyp)
941   throw(SALOME_Exception)
942 {
943   Unexpect aCatch(SalomeException);
944   if(MYDEBUG) MESSAGE("SMESH_Mesh::GetSubMeshUsingHypothesis");
945   map < int, SMESH_subMesh * >::iterator itsm;
946   _subMeshesUsingHypothesisList.clear();
947   for (itsm = _mapSubMesh.begin(); itsm != _mapSubMesh.end(); itsm++)
948   {
949     SMESH_subMesh *aSubMesh = (*itsm).second;
950     if ( IsUsedHypothesis ( anHyp, aSubMesh ))
951       _subMeshesUsingHypothesisList.push_back(aSubMesh);
952   }
953   return _subMeshesUsingHypothesisList;
954 }
955
956 //=======================================================================
957 //function : NotifySubMeshesHypothesisModification
958 //purpose  : Say all submeshes using theChangedHyp that it has been modified
959 //=======================================================================
960
961 void SMESH_Mesh::NotifySubMeshesHypothesisModification(const SMESH_Hypothesis* hyp)
962 {
963   Unexpect aCatch(SalomeException);
964
965   const SMESH_Algo *foundAlgo = 0;
966   SMESH_HypoFilter algoKind, compatibleHypoKind;
967   list <const SMESHDS_Hypothesis * > usedHyps;
968
969
970   map < int, SMESH_subMesh * >::iterator itsm;
971   for (itsm = _mapSubMesh.begin(); itsm != _mapSubMesh.end(); itsm++)
972   {
973     SMESH_subMesh *aSubMesh = (*itsm).second;
974     if ( aSubMesh->IsApplicableHypotesis( hyp ))
975     {
976       const TopoDS_Shape & aSubShape = aSubMesh->GetSubShape();
977
978       if ( !foundAlgo ) // init filter for algo search
979         algoKind.Init( THypType::IsAlgo() ).And( THypType::IsApplicableTo( aSubShape ));
980       
981       const SMESH_Algo *algo = static_cast<const SMESH_Algo*>
982         ( GetHypothesis( aSubShape, algoKind, true ));
983
984       if ( algo )
985       {
986         bool sameAlgo = ( algo == foundAlgo );
987         if ( !sameAlgo && foundAlgo )
988           sameAlgo = ( strcmp( algo->GetName(), foundAlgo->GetName() ) == 0);
989
990         if ( !sameAlgo ) { // init filter for used hypos search
991           if ( !algo->InitCompatibleHypoFilter( compatibleHypoKind, !hyp->IsAuxiliary() ))
992             continue; // algo does not use any hypothesis
993           foundAlgo = algo;
994         }
995
996         // check if hyp is used by algo
997         usedHyps.clear();
998         if ( GetHypotheses( aSubShape, compatibleHypoKind, usedHyps, true ) &&
999              find( usedHyps.begin(), usedHyps.end(), hyp ) != usedHyps.end() )
1000         {
1001           aSubMesh->AlgoStateEngine(SMESH_subMesh::MODIF_HYP,
1002                                     const_cast< SMESH_Hypothesis*>( hyp ));
1003         }
1004       }
1005     }
1006   }
1007 }
1008
1009 //=============================================================================
1010 /*!
1011  *  Auto color functionality
1012  */
1013 //=============================================================================
1014 void SMESH_Mesh::SetAutoColor(bool theAutoColor) throw(SALOME_Exception)
1015 {
1016   Unexpect aCatch(SalomeException);
1017   _isAutoColor = theAutoColor;
1018 }
1019
1020 bool SMESH_Mesh::GetAutoColor() throw(SALOME_Exception)
1021 {
1022   Unexpect aCatch(SalomeException);
1023   return _isAutoColor;
1024 }
1025
1026 //=============================================================================
1027 /*! Export* methods.
1028  *  To store mesh contents on disk in different formats.
1029  */
1030 //=============================================================================
1031
1032 bool SMESH_Mesh::HasDuplicatedGroupNamesMED()
1033 {
1034   //set<string> aGroupNames; // Corrected for Mantis issue 0020028
1035   map< SMDSAbs_ElementType, set<string> > aGroupNames;
1036   for ( map<int, SMESH_Group*>::iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ )
1037   {
1038     SMESH_Group* aGroup = it->second;
1039     SMDSAbs_ElementType aType = aGroup->GetGroupDS()->GetType();
1040     string aGroupName = aGroup->GetName();
1041     aGroupName.resize(MAX_MED_GROUP_NAME_LENGTH);
1042     if (!aGroupNames[aType].insert(aGroupName).second)
1043       return true;
1044   }
1045
1046   return false;
1047 }
1048
1049 void SMESH_Mesh::ExportMED(const char *file, 
1050                            const char* theMeshName, 
1051                            bool theAutoGroups,
1052                            int theVersion) 
1053   throw(SALOME_Exception)
1054 {
1055   Unexpect aCatch(SalomeException);
1056
1057   DriverMED_W_SMESHDS_Mesh myWriter;
1058   myWriter.SetFile    ( file, MED::EVersion(theVersion) );
1059   myWriter.SetMesh    ( _myMeshDS   );
1060   if ( !theMeshName ) 
1061     myWriter.SetMeshId  ( _idDoc      );
1062   else {
1063     myWriter.SetMeshId  ( -1          );
1064     myWriter.SetMeshName( theMeshName );
1065   }
1066
1067   if ( theAutoGroups ) {
1068     myWriter.AddGroupOfNodes();
1069     myWriter.AddGroupOfEdges();
1070     myWriter.AddGroupOfFaces();
1071     myWriter.AddGroupOfVolumes();
1072   }
1073
1074   // Pass groups to writer. Provide unique group names.
1075   //set<string> aGroupNames; // Corrected for Mantis issue 0020028
1076   map< SMDSAbs_ElementType, set<string> > aGroupNames;
1077   char aString [256];
1078   int maxNbIter = 10000; // to guarantee cycle finish
1079   for ( map<int, SMESH_Group*>::iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ ) {
1080     SMESH_Group*       aGroup   = it->second;
1081     SMESHDS_GroupBase* aGroupDS = aGroup->GetGroupDS();
1082     if ( aGroupDS ) {
1083       SMDSAbs_ElementType aType = aGroupDS->GetType();
1084       string aGroupName0 = aGroup->GetName();
1085       aGroupName0.resize(MAX_MED_GROUP_NAME_LENGTH);
1086       string aGroupName = aGroupName0;
1087       for (int i = 1; !aGroupNames[aType].insert(aGroupName).second && i < maxNbIter; i++) {
1088         sprintf(&aString[0], "GR_%d_%s", i, aGroupName0.c_str());
1089         aGroupName = aString;
1090         aGroupName.resize(MAX_MED_GROUP_NAME_LENGTH);
1091       }
1092       aGroupDS->SetStoreName( aGroupName.c_str() );
1093       myWriter.AddGroup( aGroupDS );
1094     }
1095   }
1096
1097   // Perform export
1098   myWriter.Perform();
1099 }
1100
1101 void SMESH_Mesh::ExportDAT(const char *file) throw(SALOME_Exception)
1102 {
1103   Unexpect aCatch(SalomeException);
1104   DriverDAT_W_SMDS_Mesh myWriter;
1105   myWriter.SetFile(string(file));
1106   myWriter.SetMesh(_myMeshDS);
1107   myWriter.SetMeshId(_idDoc);
1108   myWriter.Perform();
1109 }
1110
1111 void SMESH_Mesh::ExportUNV(const char *file) throw(SALOME_Exception)
1112 {
1113   Unexpect aCatch(SalomeException);
1114   DriverUNV_W_SMDS_Mesh myWriter;
1115   myWriter.SetFile(string(file));
1116   myWriter.SetMesh(_myMeshDS);
1117   myWriter.SetMeshId(_idDoc);
1118   //  myWriter.SetGroups(_mapGroup);
1119
1120   for ( map<int, SMESH_Group*>::iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ ) {
1121     SMESH_Group*       aGroup   = it->second;
1122     SMESHDS_GroupBase* aGroupDS = aGroup->GetGroupDS();
1123     if ( aGroupDS ) {
1124       string aGroupName = aGroup->GetName();
1125       aGroupDS->SetStoreName( aGroupName.c_str() );
1126       myWriter.AddGroup( aGroupDS );
1127     }
1128   }
1129   myWriter.Perform();
1130 }
1131
1132 void SMESH_Mesh::ExportSTL(const char *file, const bool isascii) throw(SALOME_Exception)
1133 {
1134   Unexpect aCatch(SalomeException);
1135   DriverSTL_W_SMDS_Mesh myWriter;
1136   myWriter.SetFile(string(file));
1137   myWriter.SetIsAscii( isascii );
1138   myWriter.SetMesh(_myMeshDS);
1139   myWriter.SetMeshId(_idDoc);
1140   myWriter.Perform();
1141 }
1142
1143 //================================================================================
1144 /*!
1145  * \brief Return number of nodes in the mesh
1146  */
1147 //================================================================================
1148
1149 int SMESH_Mesh::NbNodes() throw(SALOME_Exception)
1150 {
1151   Unexpect aCatch(SalomeException);
1152   return _myMeshDS->NbNodes();
1153 }
1154
1155 //================================================================================
1156 /*!
1157  * \brief  Return number of edges of given order in the mesh
1158  */
1159 //================================================================================
1160
1161 int SMESH_Mesh::Nb0DElements() throw(SALOME_Exception)
1162 {
1163   Unexpect aCatch(SalomeException);
1164   return _myMeshDS->GetMeshInfo().Nb0DElements();
1165 }
1166
1167 //================================================================================
1168 /*!
1169  * \brief  Return number of edges of given order in the mesh
1170  */
1171 //================================================================================
1172
1173 int SMESH_Mesh::NbEdges(SMDSAbs_ElementOrder order) throw(SALOME_Exception)
1174 {
1175   Unexpect aCatch(SalomeException);
1176   return _myMeshDS->GetMeshInfo().NbEdges(order);
1177 }
1178
1179 //================================================================================
1180 /*!
1181  * \brief Return number of faces of given order in the mesh
1182  */
1183 //================================================================================
1184
1185 int SMESH_Mesh::NbFaces(SMDSAbs_ElementOrder order) throw(SALOME_Exception)
1186 {
1187   Unexpect aCatch(SalomeException);
1188   return _myMeshDS->GetMeshInfo().NbFaces(order);
1189 }
1190
1191 //================================================================================
1192 /*!
1193  * \brief Return the number of faces in the mesh
1194  */
1195 //================================================================================
1196
1197 int SMESH_Mesh::NbTriangles(SMDSAbs_ElementOrder order) throw(SALOME_Exception)
1198 {
1199   Unexpect aCatch(SalomeException);
1200   return _myMeshDS->GetMeshInfo().NbTriangles(order);
1201 }
1202
1203 //================================================================================
1204 /*!
1205  * \brief Return the number nodes faces in the mesh
1206  */
1207 //================================================================================
1208
1209 int SMESH_Mesh::NbQuadrangles(SMDSAbs_ElementOrder order) throw(SALOME_Exception)
1210 {
1211   Unexpect aCatch(SalomeException);
1212   return _myMeshDS->GetMeshInfo().NbQuadrangles(order);
1213 }
1214
1215 //================================================================================
1216 /*!
1217  * \brief Return the number of polygonal faces in the mesh
1218  */
1219 //================================================================================
1220
1221 int SMESH_Mesh::NbPolygons() throw(SALOME_Exception)
1222 {
1223   Unexpect aCatch(SalomeException);
1224   return _myMeshDS->GetMeshInfo().NbPolygons();
1225 }
1226
1227 //================================================================================
1228 /*!
1229  * \brief Return number of volumes of given order in the mesh
1230  */
1231 //================================================================================
1232
1233 int SMESH_Mesh::NbVolumes(SMDSAbs_ElementOrder order) throw(SALOME_Exception)
1234 {
1235   Unexpect aCatch(SalomeException);
1236   return _myMeshDS->GetMeshInfo().NbVolumes(order);
1237 }
1238
1239 //================================================================================
1240 /*!
1241  * \brief  Return number of tetrahedrons of given order in the mesh
1242  */
1243 //================================================================================
1244
1245 int SMESH_Mesh::NbTetras(SMDSAbs_ElementOrder order) throw(SALOME_Exception)
1246 {
1247   Unexpect aCatch(SalomeException);
1248   return _myMeshDS->GetMeshInfo().NbTetras(order);
1249 }
1250
1251 //================================================================================
1252 /*!
1253  * \brief  Return number of hexahedrons of given order in the mesh
1254  */
1255 //================================================================================
1256
1257 int SMESH_Mesh::NbHexas(SMDSAbs_ElementOrder order) throw(SALOME_Exception)
1258 {
1259   Unexpect aCatch(SalomeException);
1260   return _myMeshDS->GetMeshInfo().NbHexas(order);
1261 }
1262
1263 //================================================================================
1264 /*!
1265  * \brief  Return number of pyramids of given order in the mesh
1266  */
1267 //================================================================================
1268
1269 int SMESH_Mesh::NbPyramids(SMDSAbs_ElementOrder order) throw(SALOME_Exception)
1270 {
1271   Unexpect aCatch(SalomeException);
1272   return _myMeshDS->GetMeshInfo().NbPyramids(order);
1273 }
1274
1275 //================================================================================
1276 /*!
1277  * \brief  Return number of prisms (penthahedrons) of given order in the mesh
1278  */
1279 //================================================================================
1280
1281 int SMESH_Mesh::NbPrisms(SMDSAbs_ElementOrder order) throw(SALOME_Exception)
1282 {
1283   Unexpect aCatch(SalomeException);
1284   return _myMeshDS->GetMeshInfo().NbPrisms(order);
1285 }
1286
1287 //================================================================================
1288 /*!
1289  * \brief  Return number of polyhedrons in the mesh
1290  */
1291 //================================================================================
1292
1293 int SMESH_Mesh::NbPolyhedrons() throw(SALOME_Exception)
1294 {
1295   Unexpect aCatch(SalomeException);
1296   return _myMeshDS->GetMeshInfo().NbPolyhedrons();
1297 }
1298
1299 //================================================================================
1300 /*!
1301  * \brief  Return number of submeshes in the mesh
1302  */
1303 //================================================================================
1304
1305 int SMESH_Mesh::NbSubMesh() throw(SALOME_Exception)
1306 {
1307   Unexpect aCatch(SalomeException);
1308   return _myMeshDS->NbSubMesh();
1309 }
1310
1311 //=======================================================================
1312 //function : IsNotConformAllowed
1313 //purpose  : check if a hypothesis alowing notconform mesh is present
1314 //=======================================================================
1315
1316 bool SMESH_Mesh::IsNotConformAllowed() const
1317 {
1318   if(MYDEBUG) MESSAGE("SMESH_Mesh::IsNotConformAllowed");
1319
1320   static SMESH_HypoFilter filter( SMESH_HypoFilter::HasName( "NotConformAllowed" ));
1321   return GetHypothesis( _myMeshDS->ShapeToMesh(), filter, false );
1322 }
1323
1324 //=======================================================================
1325 //function : IsMainShape
1326 //purpose  : 
1327 //=======================================================================
1328
1329 bool SMESH_Mesh::IsMainShape(const TopoDS_Shape& theShape) const
1330 {
1331   return theShape.IsSame(_myMeshDS->ShapeToMesh() );
1332 }
1333
1334 //=============================================================================
1335 /*!
1336  *  
1337  */
1338 //=============================================================================
1339
1340 SMESH_Group* SMESH_Mesh::AddGroup (const SMDSAbs_ElementType theType,
1341                                    const char*               theName,
1342                                    int&                      theId,
1343                                    const TopoDS_Shape&       theShape)
1344 {
1345   if (_mapGroup.find(_groupId) != _mapGroup.end())
1346     return NULL;
1347   theId = _groupId;
1348   SMESH_Group* aGroup = new SMESH_Group (theId, this, theType, theName, theShape);
1349   GetMeshDS()->AddGroup( aGroup->GetGroupDS() );
1350   _mapGroup[_groupId++] = aGroup;
1351   return aGroup;
1352 }
1353
1354 //================================================================================
1355 /*!
1356  * \brief Return iterator on all existing groups
1357  */
1358 //================================================================================
1359
1360 SMESH_Mesh::GroupIteratorPtr SMESH_Mesh::GetGroups() const
1361 {
1362   typedef map <int, SMESH_Group *> TMap;
1363   return GroupIteratorPtr( new SMDS_mapIterator<TMap>( _mapGroup ));
1364 }
1365
1366 //=============================================================================
1367 /*!
1368  * \brief Return a group by ID
1369  */
1370 //=============================================================================
1371
1372 SMESH_Group* SMESH_Mesh::GetGroup (const int theGroupID)
1373 {
1374   if (_mapGroup.find(theGroupID) == _mapGroup.end())
1375     return NULL;
1376   return _mapGroup[theGroupID];
1377 }
1378
1379
1380 //=============================================================================
1381 /*!
1382  * \brief Return IDs of all groups
1383  */
1384 //=============================================================================
1385
1386 list<int> SMESH_Mesh::GetGroupIds() const
1387 {
1388   list<int> anIds;
1389   for ( map<int, SMESH_Group*>::const_iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ )
1390     anIds.push_back( it->first );
1391   
1392   return anIds;
1393 }
1394
1395
1396 //=============================================================================
1397 /*!
1398  *  
1399  */
1400 //=============================================================================
1401
1402 void SMESH_Mesh::RemoveGroup (const int theGroupID)
1403 {
1404   if (_mapGroup.find(theGroupID) == _mapGroup.end())
1405     return;
1406   GetMeshDS()->RemoveGroup( _mapGroup[theGroupID]->GetGroupDS() );
1407   delete _mapGroup[theGroupID];
1408   _mapGroup.erase (theGroupID);
1409 }
1410
1411 //=======================================================================
1412 //function : GetAncestors
1413 //purpose  : return list of ancestors of theSubShape in the order
1414 //           that lower dimention shapes come first.
1415 //=======================================================================
1416
1417 const TopTools_ListOfShape& SMESH_Mesh::GetAncestors(const TopoDS_Shape& theS) const
1418 {
1419   if ( _mapAncestors.Contains( theS ) )
1420     return _mapAncestors.FindFromKey( theS );
1421
1422   static TopTools_ListOfShape emptyList;
1423   return emptyList;
1424 }
1425
1426 //=======================================================================
1427 //function : Dump
1428 //purpose  : dumps contents of mesh to stream [ debug purposes ]
1429 //=======================================================================
1430
1431 ostream& SMESH_Mesh::Dump(ostream& save)
1432 {
1433   int clause = 0;
1434   save << "========================== Dump contents of mesh ==========================" << endl << endl;
1435   save << ++clause << ") Total number of nodes:   \t"    << NbNodes() << endl;
1436   save << ++clause << ") Total number of edges:   \t"    << NbEdges() << endl;
1437   save << ++clause << ") Total number of faces:   \t"    << NbFaces() << endl;
1438   save << ++clause << ") Total number of polygons:\t"    << NbPolygons() << endl;
1439   save << ++clause << ") Total number of volumes:\t"     << NbVolumes() << endl;
1440   save << ++clause << ") Total number of polyhedrons:\t" << NbPolyhedrons() << endl << endl;
1441   for ( int isQuadratic = 0; isQuadratic < 2; ++isQuadratic )
1442   {
1443     string orderStr = isQuadratic ? "quadratic" : "linear";
1444     SMDSAbs_ElementOrder order  = isQuadratic ? ORDER_QUADRATIC : ORDER_LINEAR;
1445
1446     save << ++clause << ") Total number of " << orderStr << " edges:\t" << NbEdges(order) << endl;
1447     save << ++clause << ") Total number of " << orderStr << " faces:\t" << NbFaces(order) << endl;
1448     if ( NbFaces(order) > 0 ) {
1449       int nb3 = NbTriangles(order);
1450       int nb4 = NbQuadrangles(order);
1451       save << clause << ".1) Number of " << orderStr << " triangles:  \t" << nb3 << endl;
1452       save << clause << ".2) Number of " << orderStr << " quadrangles:\t" << nb4 << endl;
1453       if ( nb3 + nb4 !=  NbFaces(order) ) {
1454         map<int,int> myFaceMap;
1455         SMDS_FaceIteratorPtr itFaces=_myMeshDS->facesIterator();
1456         while( itFaces->more( ) ) {
1457           int nbNodes = itFaces->next()->NbNodes();
1458           if ( myFaceMap.find( nbNodes ) == myFaceMap.end() )
1459             myFaceMap[ nbNodes ] = 0;
1460           myFaceMap[ nbNodes ] = myFaceMap[ nbNodes ] + 1;
1461         }
1462         save << clause << ".3) Faces in detail: " << endl;
1463         map <int,int>::iterator itF;
1464         for (itF = myFaceMap.begin(); itF != myFaceMap.end(); itF++)
1465           save << "--> nb nodes: " << itF->first << " - nb elemens:\t" << itF->second << endl;
1466       }
1467     }
1468     save << ++clause << ") Total number of " << orderStr << " volumes:\t" << NbVolumes(order) << endl;
1469     if ( NbVolumes(order) > 0 ) {
1470       int nb8 = NbHexas(order);
1471       int nb4 = NbTetras(order);
1472       int nb5 = NbPyramids(order);
1473       int nb6 = NbPrisms(order);
1474       save << clause << ".1) Number of " << orderStr << " hexahedrons:\t" << nb8 << endl;
1475       save << clause << ".2) Number of " << orderStr << " tetrahedrons:\t" << nb4 << endl;
1476       save << clause << ".3) Number of " << orderStr << " prisms:      \t" << nb6 << endl;
1477       save << clause << ".4) Number of " << orderStr << " pyramids:\t" << nb5 << endl;
1478       if ( nb8 + nb4 + nb5 + nb6 != NbVolumes(order) ) {
1479         map<int,int> myVolumesMap;
1480         SMDS_VolumeIteratorPtr itVolumes=_myMeshDS->volumesIterator();
1481         while( itVolumes->more( ) ) {
1482           int nbNodes = itVolumes->next()->NbNodes();
1483           if ( myVolumesMap.find( nbNodes ) == myVolumesMap.end() )
1484             myVolumesMap[ nbNodes ] = 0;
1485           myVolumesMap[ nbNodes ] = myVolumesMap[ nbNodes ] + 1;
1486         }
1487         save << clause << ".5) Volumes in detail: " << endl;
1488         map <int,int>::iterator itV;
1489         for (itV = myVolumesMap.begin(); itV != myVolumesMap.end(); itV++)
1490           save << "--> nb nodes: " << itV->first << " - nb elemens:\t" << itV->second << endl;
1491       }
1492     }
1493     save << endl;
1494   }
1495   save << "===========================================================================" << endl;
1496   return save;
1497 }
1498
1499 //=======================================================================
1500 //function : GetElementType
1501 //purpose  : Returns type of mesh element with certain id
1502 //=======================================================================
1503
1504 SMDSAbs_ElementType SMESH_Mesh::GetElementType( const int id, const bool iselem )
1505 {
1506   return _myMeshDS->GetElementType( id, iselem );
1507 }
1508
1509 //=============================================================================
1510 /*!
1511  *  \brief Convert group on geometry into standalone group
1512  */
1513 //=============================================================================
1514
1515 SMESH_Group* SMESH_Mesh::ConvertToStandalone ( int theGroupID )
1516 {
1517   SMESH_Group* aGroup = 0;
1518   map < int, SMESH_Group * >::iterator itg = _mapGroup.find( theGroupID );
1519   if ( itg == _mapGroup.end() )
1520     return aGroup;
1521
1522   SMESH_Group* anOldGrp = (*itg).second;
1523   SMESHDS_GroupBase* anOldGrpDS = anOldGrp->GetGroupDS();
1524   if ( !anOldGrp || !anOldGrpDS )
1525     return aGroup;
1526
1527   // create new standalone group
1528   aGroup = new SMESH_Group (theGroupID, this, anOldGrpDS->GetType(), anOldGrp->GetName() );
1529   _mapGroup[theGroupID] = aGroup;
1530
1531   SMESHDS_Group* aNewGrpDS = dynamic_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
1532   GetMeshDS()->RemoveGroup( anOldGrpDS );
1533   GetMeshDS()->AddGroup( aNewGrpDS );
1534
1535   // add elements (or nodes) into new created group
1536   SMDS_ElemIteratorPtr anItr = anOldGrpDS->GetElements();
1537   while ( anItr->more() )
1538     aNewGrpDS->Add( (anItr->next())->GetID() );
1539
1540   // remove old group
1541   delete anOldGrp;
1542
1543   return aGroup;
1544 }
1545
1546 //=============================================================================
1547 /*!
1548  *  \brief remove submesh order  from Mesh
1549  */
1550 //=============================================================================
1551
1552 void SMESH_Mesh::ClearMeshOrder()
1553 {
1554   _mySubMeshOrder.clear();
1555 }
1556
1557 //=============================================================================
1558 /*!
1559  *  \brief remove submesh order  from Mesh
1560  */
1561 //=============================================================================
1562
1563 void SMESH_Mesh::SetMeshOrder(const TListOfListOfInt& theOrder )
1564 {
1565   _mySubMeshOrder = theOrder;
1566 }
1567
1568 //=============================================================================
1569 /*!
1570  *  \brief return submesh order if any
1571  */
1572 //=============================================================================
1573
1574 const TListOfListOfInt& SMESH_Mesh::GetMeshOrder() const
1575 {
1576   return _mySubMeshOrder;
1577 }
1578
1579 //=============================================================================
1580 /*!
1581  *  \brief fill _mapAncestors
1582  */
1583 //=============================================================================
1584
1585 void SMESH_Mesh::fillAncestorsMap(const TopoDS_Shape& theShape)
1586 {
1587
1588   int desType, ancType;
1589   if ( !theShape.IsSame( GetShapeToMesh()) && theShape.ShapeType() == TopAbs_COMPOUND )
1590   {
1591     // a geom group is added. Insert it into lists of ancestors before
1592     // the first ancestor more complex than group members
1593     int memberType = TopoDS_Iterator( theShape ).Value().ShapeType();
1594     for ( desType = TopAbs_VERTEX; desType >= memberType; desType-- )
1595       for (TopExp_Explorer des( theShape, TopAbs_ShapeEnum( desType )); des.More(); des.Next())
1596       {
1597         TopTools_ListOfShape& ancList = _mapAncestors.ChangeFromKey( des.Current() );
1598         TopTools_ListIteratorOfListOfShape ancIt (ancList);
1599         while ( ancIt.More() && ancIt.Value().ShapeType() >= memberType )
1600           ancIt.Next();
1601         if ( ancIt.More() )
1602           ancList.InsertBefore( theShape, ancIt );
1603       }
1604   }
1605   {
1606     for ( desType = TopAbs_VERTEX; desType > TopAbs_COMPOUND; desType-- )
1607       for ( ancType = desType - 1; ancType >= TopAbs_COMPOUND; ancType-- )
1608         TopExp::MapShapesAndAncestors ( theShape,
1609                                         (TopAbs_ShapeEnum) desType,
1610                                         (TopAbs_ShapeEnum) ancType,
1611                                         _mapAncestors );
1612   }
1613 }
1614
1615 //=============================================================================
1616 /*!
1617  * \brief sort submeshes according to stored mesh order
1618  * \param theListToSort in out list to be sorted
1619  * \return FALSE if nothing sorted
1620  */
1621 //=============================================================================
1622
1623 bool SMESH_Mesh::SortByMeshOrder(list<SMESH_subMesh*>& theListToSort) const
1624 {
1625   if ( !_mySubMeshOrder.size() || theListToSort.size() < 2)
1626     return true;
1627   
1628   bool res = false;
1629   list<SMESH_subMesh*> onlyOrderedList;
1630   // collect all ordered submeshes in one list as pointers
1631   // and get their positions within theListToSort
1632   typedef list<SMESH_subMesh*>::iterator TPosInList;
1633   map< int, TPosInList > sortedPos;
1634   TPosInList smBeg = theListToSort.begin(), smEnd = theListToSort.end();
1635   TListOfListOfInt::const_iterator listIddIt = _mySubMeshOrder.begin();
1636   for( ; listIddIt != _mySubMeshOrder.end(); listIddIt++) {
1637     const TListOfInt& listOfId = *listIddIt;
1638     TListOfInt::const_iterator idIt = listOfId.begin();
1639     for ( ; idIt != listOfId.end(); idIt++ ) {
1640       if ( SMESH_subMesh * sm = GetSubMeshContaining( *idIt )) {
1641         TPosInList smPos = find( smBeg, smEnd, sm );
1642         if ( smPos != smEnd ) {
1643           onlyOrderedList.push_back( sm );
1644           sortedPos[ distance( smBeg, smPos )] = smPos;
1645         }
1646       }
1647     }
1648   }
1649   if (onlyOrderedList.size() < 2)
1650     return res;
1651   res = true;
1652
1653   list<SMESH_subMesh*>::iterator onlyBIt = onlyOrderedList.begin();
1654   list<SMESH_subMesh*>::iterator onlyEIt = onlyOrderedList.end();
1655
1656   // iterates on ordered submeshes and insert them in detected positions
1657   map< int, TPosInList >::iterator i_pos = sortedPos.begin();
1658   for ( ; onlyBIt != onlyEIt; ++onlyBIt, ++i_pos )
1659     *(i_pos->second) = *onlyBIt;
1660
1661   return res;
1662 }
1663
1664 //=============================================================================
1665 /*!
1666  * \brief sort submeshes according to stored mesh order
1667  * \param theListToSort in out list to be sorted
1668  * \return FALSE if nothing sorted
1669  */
1670 //=============================================================================
1671
1672 list<SMESH_subMesh*> SMESH_Mesh::getAncestorsSubMeshes
1673   (const TopoDS_Shape& theSubShape) const
1674 {
1675   list<SMESH_subMesh*> listOfSubMesh;
1676   TopTools_ListIteratorOfListOfShape it( GetAncestors( theSubShape ));
1677   for (; it.More(); it.Next() )
1678     if ( SMESH_subMesh* sm = GetSubMeshContaining( it.Value() ))
1679       listOfSubMesh.push_back(sm);
1680
1681   // sort submeshes according to stored mesh order
1682   SortByMeshOrder( listOfSubMesh );
1683
1684   return listOfSubMesh;
1685 }