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