Salome HOME
23092: EDF 10836 SMESH: UseExisting2DElements fails when geometry contains more than...
[modules/smesh.git] / src / SMESH / SMESH_Mesh.cxx
1 // Copyright (C) 2007-2015  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, or (at your option) any later version.
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 //  File   : SMESH_Mesh.cxx
24 //  Author : Paul RASCLE, EDF
25 //  Module : SMESH
26 //
27 #include "SMESH_Mesh.hxx"
28 #include "SMESH_MesherHelper.hxx"
29 #include "SMDS_MeshVolume.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Document.hxx"
32 #include "SMESHDS_Group.hxx"
33 #include "SMESHDS_GroupOnGeom.hxx"
34 #include "SMESHDS_Script.hxx"
35 #include "SMESHDS_TSubMeshHolder.hxx"
36 #include "SMESH_Gen.hxx"
37 #include "SMESH_Group.hxx"
38 #include "SMESH_HypoFilter.hxx"
39 #include "SMESH_Hypothesis.hxx"
40 #include "SMESH_subMesh.hxx"
41
42 #include "utilities.h"
43
44 #include "DriverDAT_W_SMDS_Mesh.h"
45 #include "DriverGMF_Read.hxx"
46 #include "DriverGMF_Write.hxx"
47 #include "DriverMED_R_SMESHDS_Mesh.h"
48 #include "DriverMED_W_SMESHDS_Mesh.h"
49 #include "DriverSTL_R_SMDS_Mesh.h"
50 #include "DriverSTL_W_SMDS_Mesh.h"
51 #include "DriverUNV_R_SMDS_Mesh.h"
52 #include "DriverUNV_W_SMDS_Mesh.h"
53 #ifdef WITH_CGNS
54 #include "DriverCGNS_Read.hxx"
55 #include "DriverCGNS_Write.hxx"
56 #endif
57
58 #include <GEOMUtils.hxx>
59
60 #undef _Precision_HeaderFile
61 #include <BRepBndLib.hxx>
62 #include <BRepPrimAPI_MakeBox.hxx>
63 #include <Bnd_Box.hxx>
64 #include <TColStd_MapOfInteger.hxx>
65 #include <TopExp.hxx>
66 #include <TopExp_Explorer.hxx>
67 #include <TopTools_ListIteratorOfListOfShape.hxx>
68 #include <TopTools_ListOfShape.hxx>
69 #include <TopTools_MapOfShape.hxx>
70 #include <TopoDS_Iterator.hxx>
71
72 #include "SMESH_TryCatch.hxx" // include after OCCT headers!
73
74 #include "Utils_ExceptHandlers.hxx"
75
76 #ifndef WIN32
77 #include <boost/thread/thread.hpp>
78 #include <boost/bind.hpp>
79 #else 
80 #include <pthread.h>
81 #endif
82
83 using namespace std;
84
85 // maximum stored group name length in MED file
86 #define MAX_MED_GROUP_NAME_LENGTH 80
87
88 #ifdef _DEBUG_
89 static int MYDEBUG = 0;
90 #else
91 static int MYDEBUG = 0;
92 #endif
93
94 #define cSMESH_Hyp(h) static_cast<const SMESH_Hypothesis*>(h)
95
96 typedef SMESH_HypoFilter THypType;
97
98 class SMESH_Mesh::SubMeshHolder : public SMESHDS_TSubMeshHolder< SMESH_subMesh >
99 {
100 };
101
102 //=============================================================================
103 /*!
104  * 
105  */
106 //=============================================================================
107
108 SMESH_Mesh::SMESH_Mesh(int               theLocalId, 
109                        int               theStudyId, 
110                        SMESH_Gen*        theGen,
111                        bool              theIsEmbeddedMode,
112                        SMESHDS_Document* theDocument):
113   _groupId( 0 ), _nbSubShapes( 0 )
114 {
115   MESSAGE("SMESH_Mesh::SMESH_Mesh(int localId)");
116   _id            = theLocalId;
117   _studyId       = theStudyId;
118   _gen           = theGen;
119   _myDocument    = theDocument;
120   _myMeshDS      = theDocument->NewMesh(theIsEmbeddedMode,theLocalId);
121   _isShapeToMesh = false;
122   _isAutoColor   = false;
123   _isModified    = false;
124   _shapeDiagonal = 0.0;
125   _callUp        = NULL;
126   _myMeshDS->ShapeToMesh( PseudoShape() );
127   _subMeshHolder = new SubMeshHolder;
128 }
129
130 //================================================================================
131 /*!
132  * \brief Constructor of SMESH_Mesh being a base of some descendant class
133  */
134 //================================================================================
135
136 SMESH_Mesh::SMESH_Mesh():
137   _id(-1),
138   _studyId(-1),
139   _groupId( 0 ),
140   _nbSubShapes( 0 ),
141   _isShapeToMesh( false ),
142   _myDocument( 0 ),
143   _myMeshDS( 0 ),
144   _gen( 0 ),
145   _isAutoColor( false ),
146   _isModified( false ),
147   _shapeDiagonal( 0.0 ),
148   _callUp( 0 )
149 {
150   _subMeshHolder = new SubMeshHolder;
151 }
152
153 namespace
154 {
155 #ifndef WIN32
156   void deleteMeshDS(SMESHDS_Mesh* meshDS)
157   {
158     //cout << "deleteMeshDS( " << meshDS << endl;
159     delete meshDS;
160   }
161 #else
162   static void* deleteMeshDS(void* meshDS)
163   {
164     //cout << "deleteMeshDS( " << meshDS << endl;
165     SMESHDS_Mesh* m = (SMESHDS_Mesh*)meshDS;
166     if(m) {
167       delete m;
168     }
169     return 0;
170   }
171 #endif
172 }
173
174 //=============================================================================
175 /*!
176  *
177  */
178 //=============================================================================
179
180 SMESH_Mesh::~SMESH_Mesh()
181 {
182   MESSAGE("SMESH_Mesh::~SMESH_Mesh");
183
184   // avoid usual removal of elements while processing RemoveHypothesis( algo ) event
185   SMESHDS_SubMeshIteratorPtr smIt = _myMeshDS->SubMeshes();
186   while ( smIt->more() )
187     const_cast<SMESHDS_SubMesh*>( smIt->next() )->Clear();
188
189   // issue 0020340: EDF 1022 SMESH : Crash with FindNodeClosestTo in a second new study
190   //   Notify event listeners at least that something happens
191   if ( SMESH_subMesh * sm = GetSubMeshContaining(1))
192     sm->ComputeStateEngine( SMESH_subMesh::MESH_ENTITY_REMOVED );
193
194   // delete groups
195   map < int, SMESH_Group * >::iterator itg;
196   for (itg = _mapGroup.begin(); itg != _mapGroup.end(); itg++) {
197     SMESH_Group *aGroup = (*itg).second;
198     delete aGroup;
199   }
200   _mapGroup.clear();
201
202   // delete sub-meshes
203   delete _subMeshHolder;
204
205   if ( _callUp) delete _callUp;
206   _callUp = 0;
207
208   // remove self from studyContext
209   if ( _gen )
210   {
211     StudyContextStruct * studyContext = _gen->GetStudyContext( _studyId );
212     studyContext->mapMesh.erase( _id );
213   }
214   if ( _myDocument )
215     _myDocument->RemoveMesh( _id );
216   _myDocument = 0;
217
218   if ( _myMeshDS ) {
219     // delete _myMeshDS, in a thread in order not to block closing a study with large meshes
220 #ifndef WIN32
221     boost::thread aThread(boost::bind( & deleteMeshDS, _myMeshDS ));
222 #else
223     pthread_t thread;
224     int result=pthread_create(&thread, NULL, deleteMeshDS, (void*)_myMeshDS);
225 #endif
226   }
227 }
228
229 //================================================================================
230 /*!
231  * \brief Return true if a mesh with given id exists
232  */
233 //================================================================================
234
235 bool SMESH_Mesh::MeshExists( int meshId ) const
236 {
237   return _myDocument ? bool( _myDocument->GetMesh( meshId )) : false;
238 }
239
240 //================================================================================
241 /*!
242  * \brief Return a mesh by id
243  */
244 //================================================================================
245
246 SMESH_Mesh* SMESH_Mesh::FindMesh( int meshId ) const
247 {
248   if ( _id == meshId )
249     return (SMESH_Mesh*) this;
250
251   if ( StudyContextStruct *aStudyContext = _gen->GetStudyContext( _studyId ))
252   {
253     std::map < int, SMESH_Mesh * >::iterator i_m = aStudyContext->mapMesh.find( meshId );
254     if ( i_m != aStudyContext->mapMesh.end() )
255       return i_m->second;
256   }
257   return NULL;
258 }
259
260 //=============================================================================
261 /*!
262  * \brief Set geometry to be meshed
263  */
264 //=============================================================================
265
266 void SMESH_Mesh::ShapeToMesh(const TopoDS_Shape & aShape)
267 {
268   if(MYDEBUG) MESSAGE("SMESH_Mesh::ShapeToMesh");
269
270   if ( !aShape.IsNull() && _isShapeToMesh ) {
271     if ( aShape.ShapeType() != TopAbs_COMPOUND && // group contents is allowed to change
272          _myMeshDS->ShapeToMesh().ShapeType() != TopAbs_COMPOUND )
273       throw SALOME_Exception(LOCALIZED ("a shape to mesh has already been defined"));
274   }
275   // clear current data
276   if ( !_myMeshDS->ShapeToMesh().IsNull() )
277   {
278     // removal of a shape to mesh, delete objects referring to sub-shapes:
279     // - sub-meshes
280     _subMeshHolder->DeleteAll();
281     //  - groups on geometry
282     map <int, SMESH_Group *>::iterator i_gr = _mapGroup.begin();
283     while ( i_gr != _mapGroup.end() ) {
284       if ( dynamic_cast<SMESHDS_GroupOnGeom*>( i_gr->second->GetGroupDS() )) {
285         _myMeshDS->RemoveGroup( i_gr->second->GetGroupDS() );
286         delete i_gr->second;
287         _mapGroup.erase( i_gr++ );
288       }
289       else
290         i_gr++;
291     }
292     _mapAncestors.Clear();
293
294     // clear SMESHDS
295     TopoDS_Shape aNullShape;
296     _myMeshDS->ShapeToMesh( aNullShape );
297
298     _shapeDiagonal = 0.0;
299   }
300
301   // set a new geometry
302   if ( !aShape.IsNull() )
303   {
304     _myMeshDS->ShapeToMesh(aShape);
305     _isShapeToMesh = true;
306     _nbSubShapes = _myMeshDS->MaxShapeIndex();
307
308     // fill map of ancestors
309     fillAncestorsMap(aShape);
310   }
311   else
312   {
313     _isShapeToMesh = false;
314     _shapeDiagonal = 0.0;
315     _myMeshDS->ShapeToMesh( PseudoShape() );
316   }
317   _isModified = false;
318 }
319
320 //=======================================================================
321 /*!
322  * \brief Return geometry to be meshed. (It may be a PseudoShape()!)
323  */
324 //=======================================================================
325
326 TopoDS_Shape SMESH_Mesh::GetShapeToMesh() const
327 {
328   return _myMeshDS->ShapeToMesh();
329 }
330
331 //=======================================================================
332 /*!
333  * \brief Return a solid which is returned by GetShapeToMesh() if
334  *        a real geometry to be meshed was not set
335  */
336 //=======================================================================
337
338 const TopoDS_Solid& SMESH_Mesh::PseudoShape()
339 {
340   static TopoDS_Solid aSolid;
341   if ( aSolid.IsNull() )
342   {
343     aSolid = BRepPrimAPI_MakeBox(1,1,1);
344   }
345   return aSolid;
346 }
347
348 //=======================================================================
349 /*!
350  * \brief Return diagonal size of bounding box of a shape
351  */
352 //=======================================================================
353
354 double SMESH_Mesh::GetShapeDiagonalSize(const TopoDS_Shape & aShape)
355 {
356   if ( !aShape.IsNull() ) {
357     Bnd_Box Box;
358     // avoid too long waiting on large shapes. PreciseBoundingBox() was added
359     // to assure same result which else depends on presence of triangulation (IPAL52557).
360     const int maxNbFaces = 4000;
361     int nbFaces = 0;
362     for ( TopExp_Explorer f( aShape, TopAbs_FACE ); f.More() && nbFaces < maxNbFaces; f.Next() )
363       ++nbFaces;
364     if ( nbFaces < maxNbFaces )
365       GEOMUtils::PreciseBoundingBox(aShape, Box);
366     else
367       BRepBndLib::Add( aShape, Box);
368     if ( !Box.IsVoid() )
369       return sqrt( Box.SquareExtent() );
370   }
371   return 0;
372 }
373
374 //=======================================================================
375 /*!
376  * \brief Return diagonal size of bounding box of shape to mesh
377  */
378 //=======================================================================
379
380 double SMESH_Mesh::GetShapeDiagonalSize() const
381 {
382   if ( _shapeDiagonal == 0. && _isShapeToMesh )
383     const_cast<SMESH_Mesh*>(this)->_shapeDiagonal = GetShapeDiagonalSize( GetShapeToMesh() );
384
385   return _shapeDiagonal;
386 }
387
388 //================================================================================
389 /*!
390  * \brief Load mesh from study file
391  */
392 //================================================================================
393
394 void SMESH_Mesh::Load()
395 {
396   if (_callUp)
397     _callUp->Load();
398 }
399
400 //=======================================================================
401 /*!
402  * \brief Remove all nodes and elements
403  */
404 //=======================================================================
405
406 void SMESH_Mesh::Clear()
407 {
408   if ( HasShapeToMesh() ) // remove all nodes and elements
409   {
410     // clear mesh data
411     _myMeshDS->ClearMesh();
412
413     // update compute state of submeshes
414     if ( SMESH_subMesh *sm = GetSubMeshContaining( GetShapeToMesh() ) )
415     {
416       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
417       sm->ComputeSubMeshStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
418       sm->ComputeStateEngine( SMESH_subMesh::CLEAN ); // for event listeners (issue 0020918)
419       sm->ComputeSubMeshStateEngine( SMESH_subMesh::CLEAN );
420     }
421   }
422   else // remove only nodes/elements computed by algorithms
423   {
424     if ( SMESH_subMesh *sm = GetSubMeshContaining( GetShapeToMesh() ) )
425     {
426       sm->ComputeStateEngine( SMESH_subMesh::CLEAN );
427       sm->ComputeSubMeshStateEngine( SMESH_subMesh::CLEAN );
428       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
429       sm->ComputeSubMeshStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
430     }
431   }
432   _isModified = false;
433 }
434
435 //=======================================================================
436 /*!
437  * \brief Remove all nodes and elements of indicated shape
438  */
439 //=======================================================================
440
441 void SMESH_Mesh::ClearSubMesh(const int theShapeId)
442 {
443   // clear sub-meshes; get ready to re-compute as a side-effect 
444   if ( SMESH_subMesh *sm = GetSubMeshContaining( theShapeId ) )
445   {
446     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true,
447                                                              /*complexShapeFirst=*/false);
448     while ( smIt->more() )
449     {
450       sm = smIt->next();
451       TopAbs_ShapeEnum shapeType = sm->GetSubShape().ShapeType();      
452       if ( shapeType == TopAbs_VERTEX || shapeType < TopAbs_SOLID )
453         // all other shapes depends on vertices so they are already cleaned
454         sm->ComputeStateEngine( SMESH_subMesh::CLEAN );
455       // to recompute even if failed
456       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
457     }
458   }
459 }
460
461 //=======================================================================
462 //function : UNVToMesh
463 //purpose  : 
464 //=======================================================================
465
466 int SMESH_Mesh::UNVToMesh(const char* theFileName)
467 {
468   if(MYDEBUG) MESSAGE("UNVToMesh - theFileName = "<<theFileName);
469   if(_isShapeToMesh)
470     throw SALOME_Exception(LOCALIZED("a shape to mesh has already been defined"));
471   _isShapeToMesh = false;
472   DriverUNV_R_SMDS_Mesh myReader;
473   myReader.SetMesh(_myMeshDS);
474   myReader.SetFile(theFileName);
475   myReader.SetMeshId(-1);
476   myReader.Perform();
477   if(MYDEBUG){
478     MESSAGE("UNVToMesh - _myMeshDS->NbNodes() = "<<_myMeshDS->NbNodes());
479     MESSAGE("UNVToMesh - _myMeshDS->NbEdges() = "<<_myMeshDS->NbEdges());
480     MESSAGE("UNVToMesh - _myMeshDS->NbFaces() = "<<_myMeshDS->NbFaces());
481     MESSAGE("UNVToMesh - _myMeshDS->NbVolumes() = "<<_myMeshDS->NbVolumes());
482   }
483   SMDS_MeshGroup* aGroup = (SMDS_MeshGroup*) myReader.GetGroup();
484   if (aGroup != 0) {
485     TGroupNamesMap aGroupNames = myReader.GetGroupNamesMap();
486     //const TGroupIdMap& aGroupId = myReader.GetGroupIdMap();
487     aGroup->InitSubGroupsIterator();
488     while (aGroup->MoreSubGroups()) {
489       SMDS_MeshGroup* aSubGroup = (SMDS_MeshGroup*) aGroup->NextSubGroup();
490       string aName = aGroupNames[aSubGroup];
491       int aId;
492
493       SMESH_Group* aSMESHGroup = AddGroup( aSubGroup->GetType(), aName.c_str(), aId );
494       if ( aSMESHGroup ) {
495         if(MYDEBUG) MESSAGE("UNVToMesh - group added: "<<aName);      
496         SMESHDS_Group* aGroupDS = dynamic_cast<SMESHDS_Group*>( aSMESHGroup->GetGroupDS() );
497         if ( aGroupDS ) {
498           aGroupDS->SetStoreName(aName.c_str());
499           aSubGroup->InitIterator();
500           const SMDS_MeshElement* aElement = 0;
501           while (aSubGroup->More()) {
502             aElement = aSubGroup->Next();
503             if (aElement) {
504               aGroupDS->SMDSGroup().Add(aElement);
505             }
506           }
507           if (aElement)
508             aGroupDS->SetType(aElement->GetType());
509         }
510       }
511     }
512   }
513   return 1;
514 }
515
516 //=======================================================================
517 //function : MEDToMesh
518 //purpose  : 
519 //=======================================================================
520
521 int SMESH_Mesh::MEDToMesh(const char* theFileName, const char* theMeshName)
522 {
523   if(MYDEBUG) MESSAGE("MEDToMesh - theFileName = "<<theFileName<<", mesh name = "<<theMeshName);
524   if(_isShapeToMesh)
525     throw SALOME_Exception(LOCALIZED("a shape to mesh has already been defined"));
526   _isShapeToMesh = false;
527   DriverMED_R_SMESHDS_Mesh myReader;
528   myReader.SetMesh(_myMeshDS);
529   myReader.SetMeshId(-1);
530   myReader.SetFile(theFileName);
531   myReader.SetMeshName(theMeshName);
532   Driver_Mesh::Status status = myReader.Perform();
533   if(MYDEBUG){
534     MESSAGE("MEDToMesh - _myMeshDS->NbNodes() = "<<_myMeshDS->NbNodes());
535     MESSAGE("MEDToMesh - _myMeshDS->NbEdges() = "<<_myMeshDS->NbEdges());
536     MESSAGE("MEDToMesh - _myMeshDS->NbFaces() = "<<_myMeshDS->NbFaces());
537     MESSAGE("MEDToMesh - _myMeshDS->NbVolumes() = "<<_myMeshDS->NbVolumes());
538   }
539
540   // Reading groups (sub-meshes are out of scope of MED import functionality)
541   list<TNameAndType> aGroupNames = myReader.GetGroupNamesAndTypes();
542   if(MYDEBUG) MESSAGE("MEDToMesh - Nb groups = "<<aGroupNames.size()); 
543   int anId;
544   list<TNameAndType>::iterator name_type = aGroupNames.begin();
545   for ( ; name_type != aGroupNames.end(); name_type++ ) {
546     SMESH_Group* aGroup = AddGroup( name_type->second, name_type->first.c_str(), anId );
547     if ( aGroup ) {
548       if(MYDEBUG) MESSAGE("MEDToMesh - group added: "<<name_type->first.c_str());      
549       SMESHDS_Group* aGroupDS = dynamic_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
550       if ( aGroupDS ) {
551         aGroupDS->SetStoreName( name_type->first.c_str() );
552         myReader.GetGroup( aGroupDS );
553       }
554     }
555   }
556   return (int) status;
557 }
558
559 //=======================================================================
560 //function : STLToMesh
561 //purpose  : 
562 //=======================================================================
563
564 int SMESH_Mesh::STLToMesh(const char* theFileName)
565 {
566   if(MYDEBUG) MESSAGE("STLToMesh - theFileName = "<<theFileName);
567   if(_isShapeToMesh)
568     throw SALOME_Exception(LOCALIZED("a shape to mesh has already been defined"));
569   _isShapeToMesh = false;
570   DriverSTL_R_SMDS_Mesh myReader;
571   myReader.SetMesh(_myMeshDS);
572   myReader.SetFile(theFileName);
573   myReader.SetMeshId(-1);
574   myReader.Perform();
575   if(MYDEBUG){
576     MESSAGE("STLToMesh - _myMeshDS->NbNodes() = "<<_myMeshDS->NbNodes());
577     MESSAGE("STLToMesh - _myMeshDS->NbEdges() = "<<_myMeshDS->NbEdges());
578     MESSAGE("STLToMesh - _myMeshDS->NbFaces() = "<<_myMeshDS->NbFaces());
579     MESSAGE("STLToMesh - _myMeshDS->NbVolumes() = "<<_myMeshDS->NbVolumes());
580   }
581   return 1;
582 }
583
584 //================================================================================
585 /*!
586  * \brief Reads the given mesh from the CGNS file
587  *  \param theFileName - name of the file
588  *  \retval int - Driver_Mesh::Status
589  */
590 //================================================================================
591
592 int SMESH_Mesh::CGNSToMesh(const char*  theFileName,
593                            const int    theMeshIndex,
594                            std::string& theMeshName)
595 {
596   int res = Driver_Mesh::DRS_FAIL;
597 #ifdef WITH_CGNS
598
599   DriverCGNS_Read myReader;
600   myReader.SetMesh(_myMeshDS);
601   myReader.SetFile(theFileName);
602   myReader.SetMeshId(theMeshIndex);
603   res = myReader.Perform();
604   theMeshName = myReader.GetMeshName();
605
606   // create groups
607   SynchronizeGroups();
608
609 #endif
610   return res;
611 }
612
613 //================================================================================
614 /*!
615  * \brief Fill its data by reading a GMF file
616  */
617 //================================================================================
618
619 SMESH_ComputeErrorPtr SMESH_Mesh::GMFToMesh(const char* theFileName,
620                                             bool        theMakeRequiredGroups)
621 {
622   DriverGMF_Read myReader;
623   myReader.SetMesh(_myMeshDS);
624   myReader.SetFile(theFileName);
625   myReader.SetMakeRequiredGroups( theMakeRequiredGroups );
626   myReader.Perform();
627   //theMeshName = myReader.GetMeshName();
628
629   // create groups
630   SynchronizeGroups();
631
632   return myReader.GetError();
633 }
634
635 //=============================================================================
636 /*!
637  * 
638  */
639 //=============================================================================
640
641 SMESH_Hypothesis::Hypothesis_Status
642 SMESH_Mesh::AddHypothesis(const TopoDS_Shape & aSubShape,
643                           int                  anHypId,
644                           std::string*         anError  ) throw(SALOME_Exception)
645 {
646   Unexpect aCatch(SalomeException);
647   if(MYDEBUG) MESSAGE("SMESH_Mesh::AddHypothesis");
648
649   if ( anError )
650     anError->clear();
651
652   SMESH_subMesh *subMesh = GetSubMesh(aSubShape);
653   if ( !subMesh || !subMesh->GetId())
654     return SMESH_Hypothesis::HYP_BAD_SUBSHAPE;
655
656   SMESH_Hypothesis *anHyp = GetHypothesis( anHypId );
657   if ( !anHyp )
658     throw SALOME_Exception(LOCALIZED("hypothesis does not exist"));
659
660   bool isGlobalHyp = IsMainShape( aSubShape );
661
662   // NotConformAllowed can be only global
663   if ( !isGlobalHyp )
664   {
665     // NOTE: this is not a correct way to check a name of hypothesis,
666     // there should be an attribute of hypothesis saying that it can/can't
667     // be global/local
668     string hypName = anHyp->GetName();
669     if ( hypName == "NotConformAllowed" )
670     {
671       if(MYDEBUG) MESSAGE( "Hypotesis <NotConformAllowed> can be only global" );
672       return SMESH_Hypothesis::HYP_INCOMPATIBLE;
673     }
674   }
675
676   // shape
677
678   bool isAlgo = ( anHyp->GetType() != SMESHDS_Hypothesis::PARAM_ALGO );
679   int   event = isAlgo ? SMESH_subMesh::ADD_ALGO : SMESH_subMesh::ADD_HYP;
680
681   SMESH_Hypothesis::Hypothesis_Status ret = subMesh->AlgoStateEngine(event, anHyp);
682
683   if ( anError && SMESH_Hypothesis::IsStatusFatal(ret) && subMesh->GetComputeError() )
684     *anError = subMesh->GetComputeError()->myComment;
685
686   // sub-shapes
687   if ( !SMESH_Hypothesis::IsStatusFatal(ret) &&
688        anHyp->GetDim() <= SMESH_Gen::GetShapeDim(aSubShape)) // is added on father
689   {
690     event = isAlgo ? SMESH_subMesh::ADD_FATHER_ALGO : SMESH_subMesh::ADD_FATHER_HYP;
691
692     SMESH_Hypothesis::Hypothesis_Status ret2 =
693       subMesh->SubMeshesAlgoStateEngine(event, anHyp, /*exitOnFatal=*/true);
694     if (ret2 > ret)
695     {
696       ret = ret2;
697       if ( SMESH_Hypothesis::IsStatusFatal( ret ))
698       {
699         if ( anError && subMesh->GetComputeError() )
700           *anError = subMesh->GetComputeError()->myComment;
701         // remove anHyp
702         event = isAlgo ? SMESH_subMesh::REMOVE_ALGO : SMESH_subMesh::REMOVE_HYP;
703         subMesh->AlgoStateEngine(event, anHyp);
704       }
705     }
706
707     // check concurent hypotheses on ancestors
708     if (ret < SMESH_Hypothesis::HYP_CONCURENT && !isGlobalHyp )
709     {
710       SMESH_subMeshIteratorPtr smIt = subMesh->getDependsOnIterator(false,false);
711       while ( smIt->more() ) {
712         SMESH_subMesh* sm = smIt->next();
713         if ( sm->IsApplicableHypotesis( anHyp )) {
714           ret2 = sm->CheckConcurentHypothesis( anHyp->GetType() );
715           if (ret2 > ret) {
716             ret = ret2;
717             break;
718           }
719         }
720       }
721     }
722   }
723   HasModificationsToDiscard(); // to reset _isModified flag if a mesh becomes empty
724
725   if(MYDEBUG) subMesh->DumpAlgoState(true);
726   if(MYDEBUG) SCRUTE(ret);
727   return ret;
728 }
729
730 //=============================================================================
731 /*!
732  * 
733  */
734 //=============================================================================
735
736 SMESH_Hypothesis::Hypothesis_Status
737   SMESH_Mesh::RemoveHypothesis(const TopoDS_Shape & aSubShape,
738                                int anHypId)throw(SALOME_Exception)
739 {
740   Unexpect aCatch(SalomeException);
741   if(MYDEBUG) MESSAGE("SMESH_Mesh::RemoveHypothesis");
742   
743   StudyContextStruct *sc = _gen->GetStudyContext(_studyId);
744   if (sc->mapHypothesis.find(anHypId) == sc->mapHypothesis.end())
745     throw SALOME_Exception(LOCALIZED("hypothesis does not exist"));
746   
747   SMESH_Hypothesis *anHyp = sc->mapHypothesis[anHypId];
748   if(MYDEBUG) {
749     SCRUTE(anHyp->GetType());
750   }
751   
752   // shape 
753   
754   bool isAlgo = ( !anHyp->GetType() == SMESHDS_Hypothesis::PARAM_ALGO );
755   int event = isAlgo ? SMESH_subMesh::REMOVE_ALGO : SMESH_subMesh::REMOVE_HYP;
756
757   SMESH_subMesh *subMesh = GetSubMesh(aSubShape);
758
759   SMESH_Hypothesis::Hypothesis_Status ret = subMesh->AlgoStateEngine(event, anHyp);
760
761   // there may appear concurrent hyps that were covered by the removed hyp
762   if (ret < SMESH_Hypothesis::HYP_CONCURENT &&
763       subMesh->IsApplicableHypotesis( anHyp ) &&
764       subMesh->CheckConcurentHypothesis( anHyp->GetType() ) != SMESH_Hypothesis::HYP_OK)
765     ret = SMESH_Hypothesis::HYP_CONCURENT;
766
767   // sub-shapes
768   if (!SMESH_Hypothesis::IsStatusFatal(ret) &&
769       anHyp->GetDim() <= SMESH_Gen::GetShapeDim(aSubShape)) // is removed from father
770   {
771     event = isAlgo ? SMESH_subMesh::REMOVE_FATHER_ALGO : SMESH_subMesh::REMOVE_FATHER_HYP;
772
773     SMESH_Hypothesis::Hypothesis_Status ret2 =
774       subMesh->SubMeshesAlgoStateEngine(event, anHyp);
775     if (ret2 > ret) // more severe
776       ret = ret2;
777
778     // check concurent hypotheses on ancestors
779     if (ret < SMESH_Hypothesis::HYP_CONCURENT && !IsMainShape( aSubShape ) )
780     {
781       SMESH_subMeshIteratorPtr smIt = subMesh->getDependsOnIterator(false,false);
782       while ( smIt->more() ) {
783         SMESH_subMesh* sm = smIt->next();
784         if ( sm->IsApplicableHypotesis( anHyp )) {
785           ret2 = sm->CheckConcurentHypothesis( anHyp->GetType() );
786           if (ret2 > ret) {
787             ret = ret2;
788             break;
789           }
790         }
791       }
792     }
793   }
794
795   HasModificationsToDiscard(); // to reset _isModified flag if mesh become empty
796
797   if(MYDEBUG) subMesh->DumpAlgoState(true);
798   if(MYDEBUG) SCRUTE(ret);
799   return ret;
800 }
801
802 //=============================================================================
803 /*!
804  * 
805  */
806 //=============================================================================
807
808 const list<const SMESHDS_Hypothesis*>&
809 SMESH_Mesh::GetHypothesisList(const TopoDS_Shape & aSubShape) const
810   throw(SALOME_Exception)
811 {
812   return _myMeshDS->GetHypothesis(aSubShape);
813 }
814
815 //=======================================================================
816 /*!
817  * \brief Return the hypothesis assigned to the shape
818  *  \param aSubShape    - the shape to check
819  *  \param aFilter      - the hypothesis filter
820  *  \param andAncestors - flag to check hypos assigned to ancestors of the shape
821  *  \param assignedTo   - to return the shape the found hypo is assigned to
822  *  \retval SMESH_Hypothesis* - the first hypo passed through aFilter
823  */
824 //=======================================================================
825
826 const SMESH_Hypothesis * SMESH_Mesh::GetHypothesis(const TopoDS_Shape &    aSubShape,
827                                                    const SMESH_HypoFilter& aFilter,
828                                                    const bool              andAncestors,
829                                                    TopoDS_Shape*           assignedTo) const
830 {
831   return GetHypothesis( const_cast< SMESH_Mesh* >(this)->GetSubMesh( aSubShape ),
832                         aFilter, andAncestors, assignedTo );
833 }
834
835 //=======================================================================
836 /*!
837  * \brief Return the hypothesis assigned to the shape of a sub-mesh
838  *  \param aSubMesh     - the sub-mesh to check
839  *  \param aFilter      - the hypothesis filter
840  *  \param andAncestors - flag to check hypos assigned to ancestors of the shape
841  *  \param assignedTo   - to return the shape the found hypo is assigned to
842  *  \retval SMESH_Hypothesis* - the first hypo passed through aFilter
843  */
844 //=======================================================================
845
846 const SMESH_Hypothesis * SMESH_Mesh::GetHypothesis(const SMESH_subMesh *   aSubMesh,
847                                                    const SMESH_HypoFilter& aFilter,
848                                                    const bool              andAncestors,
849                                                    TopoDS_Shape*           assignedTo) const
850 {
851   if ( !aSubMesh ) return 0;
852
853   {
854     const TopoDS_Shape & aSubShape = aSubMesh->GetSubShape();
855     const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(aSubShape);
856     list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
857     for ( ; hyp != hypList.end(); hyp++ ) {
858       const SMESH_Hypothesis * h = cSMESH_Hyp( *hyp );
859       if ( aFilter.IsOk( h, aSubShape)) {
860         if ( assignedTo ) *assignedTo = aSubShape;
861         return h;
862       }
863     }
864   }
865   if ( andAncestors )
866   {
867     // user sorted submeshes of ancestors, according to stored submesh priority
868     std::vector< SMESH_subMesh * > & ancestors =
869       const_cast< std::vector< SMESH_subMesh * > & > ( aSubMesh->GetAncestors() );
870     SortByMeshOrder( ancestors );
871
872     vector<SMESH_subMesh*>::const_iterator smIt = ancestors.begin(); 
873     for ( ; smIt != ancestors.end(); smIt++ )
874     {
875       const TopoDS_Shape& curSh = (*smIt)->GetSubShape();
876       const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(curSh);
877       list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
878       for ( ; hyp != hypList.end(); hyp++ ) {
879         const SMESH_Hypothesis * h = cSMESH_Hyp( *hyp );
880         if (aFilter.IsOk( h, curSh )) {
881           if ( assignedTo ) *assignedTo = curSh;
882           return h;
883         }
884       }
885     }
886   }
887   return 0;
888 }
889
890 //================================================================================
891 /*!
892  * \brief Return hypotheses assigned to the shape
893   * \param aSubShape - the shape to check
894   * \param aFilter - the hypothesis filter
895   * \param aHypList - the list of the found hypotheses
896   * \param andAncestors - flag to check hypos assigned to ancestors of the shape
897   * \retval int - number of unique hypos in aHypList
898  */
899 //================================================================================
900
901 int SMESH_Mesh::GetHypotheses(const TopoDS_Shape &                aSubShape,
902                               const SMESH_HypoFilter&             aFilter,
903                               list <const SMESHDS_Hypothesis * >& aHypList,
904                               const bool                          andAncestors,
905                               list< TopoDS_Shape > *              assignedTo/*=0*/) const
906 {
907   return GetHypotheses( const_cast< SMESH_Mesh* >(this)->GetSubMesh( aSubShape ),
908                         aFilter, aHypList, andAncestors, assignedTo );
909 }
910
911 //================================================================================
912 /*!
913  * \brief Return hypotheses assigned to the shape of a sub-mesh
914   * \param aSubShape - the sub-mesh to check
915   * \param aFilter - the hypothesis filter
916   * \param aHypList - the list of the found hypotheses
917   * \param andAncestors - flag to check hypos assigned to ancestors of the shape
918   * \retval int - number of unique hypos in aHypList
919  */
920 //================================================================================
921
922 int SMESH_Mesh::GetHypotheses(const SMESH_subMesh *               aSubMesh,
923                               const SMESH_HypoFilter&             aFilter,
924                               list <const SMESHDS_Hypothesis * >& aHypList,
925                               const bool                          andAncestors,
926                               list< TopoDS_Shape > *              assignedTo/*=0*/) const
927 {
928   if ( !aSubMesh ) return 0;
929
930   set<string> hypTypes; // to exclude same type hypos from the result list
931   int nbHyps = 0;
932
933   // only one main hypothesis is allowed
934   bool mainHypFound = false;
935
936   // fill in hypTypes
937   list<const SMESHDS_Hypothesis*>::const_iterator hyp;
938   for ( hyp = aHypList.begin(); hyp != aHypList.end(); hyp++ ) {
939     if ( hypTypes.insert( (*hyp)->GetName() ).second )
940       nbHyps++;
941     if ( !cSMESH_Hyp(*hyp)->IsAuxiliary() )
942       mainHypFound = true;
943   }
944
945   // get hypos from aSubShape
946   {
947     const TopoDS_Shape & aSubShape = aSubMesh->GetSubShape();
948     const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(aSubShape);
949     for ( hyp = hypList.begin(); hyp != hypList.end(); hyp++ )
950     {
951       const SMESH_Hypothesis* h = cSMESH_Hyp( *hyp );
952       if (( aFilter.IsOk( h, aSubShape )) &&
953           ( h->IsAuxiliary() || !mainHypFound ) &&
954           ( h->IsAuxiliary() || hypTypes.insert( h->GetName() ).second ))
955       {
956         aHypList.push_back( *hyp );
957         nbHyps++;
958         if ( !h->IsAuxiliary() )
959           mainHypFound = true;
960         if ( assignedTo ) assignedTo->push_back( aSubShape );
961       }
962     }
963   }
964
965   // get hypos from ancestors of aSubShape
966   if ( andAncestors )
967   {
968     // user sorted submeshes of ancestors, according to stored submesh priority
969     std::vector< SMESH_subMesh * > & ancestors =
970       const_cast< std::vector< SMESH_subMesh * > & > ( aSubMesh->GetAncestors() );
971     SortByMeshOrder( ancestors );
972
973     vector<SMESH_subMesh*>::const_iterator smIt = ancestors.begin();
974     for ( ; smIt != ancestors.end(); smIt++ )
975     {
976       const TopoDS_Shape& curSh = (*smIt)->GetSubShape();
977       const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(curSh);
978       for ( hyp = hypList.begin(); hyp != hypList.end(); hyp++ )
979       {
980         const SMESH_Hypothesis* h = cSMESH_Hyp( *hyp );
981         if (( aFilter.IsOk( h, curSh )) &&
982             ( h->IsAuxiliary() || !mainHypFound ) &&
983             ( h->IsAuxiliary() || hypTypes.insert( h->GetName() ).second ))
984         {
985           aHypList.push_back( *hyp );
986           nbHyps++;
987           if ( !h->IsAuxiliary() )
988             mainHypFound = true;
989           if ( assignedTo ) assignedTo->push_back( curSh );
990         }
991       }
992     }
993   }
994   return nbHyps;
995 }
996
997 //================================================================================
998 /*!
999  * \brief Return a hypothesis by its ID
1000  */
1001 //================================================================================
1002
1003 SMESH_Hypothesis * SMESH_Mesh::GetHypothesis(const int anHypId) const
1004 {
1005   StudyContextStruct *sc = _gen->GetStudyContext(_studyId);
1006   if (sc->mapHypothesis.find(anHypId) == sc->mapHypothesis.end())
1007     return NULL;
1008
1009   SMESH_Hypothesis *anHyp = sc->mapHypothesis[anHypId];
1010   return anHyp;
1011 }
1012
1013 //=============================================================================
1014 /*!
1015  * 
1016  */
1017 //=============================================================================
1018
1019 const list<SMESHDS_Command*> & SMESH_Mesh::GetLog() throw(SALOME_Exception)
1020 {
1021   Unexpect aCatch(SalomeException);
1022   if(MYDEBUG) MESSAGE("SMESH_Mesh::GetLog");
1023   return _myMeshDS->GetScript()->GetCommands();
1024 }
1025
1026 //=============================================================================
1027 /*!
1028  * 
1029  */
1030 //=============================================================================
1031 void SMESH_Mesh::ClearLog() throw(SALOME_Exception)
1032 {
1033   Unexpect aCatch(SalomeException);
1034   if(MYDEBUG) MESSAGE("SMESH_Mesh::ClearLog");
1035   _myMeshDS->GetScript()->Clear();
1036 }
1037
1038 //=============================================================================
1039 /*!
1040  * Get or Create the SMESH_subMesh object implementation
1041  */
1042 //=============================================================================
1043
1044 SMESH_subMesh *SMESH_Mesh::GetSubMesh(const TopoDS_Shape & aSubShape)
1045   throw(SALOME_Exception)
1046 {
1047   int index = _myMeshDS->ShapeToIndex(aSubShape);
1048   if ( !index && aSubShape.IsNull() )
1049     return 0;
1050
1051   // for submeshes on GEOM Group
1052   if (( !index || index > _nbSubShapes ) && aSubShape.ShapeType() == TopAbs_COMPOUND ) {
1053     TopoDS_Iterator it( aSubShape );
1054     if ( it.More() )
1055     {
1056       index = _myMeshDS->AddCompoundSubmesh( aSubShape, it.Value().ShapeType() );
1057       // fill map of Ancestors
1058       while ( _nbSubShapes < index )
1059         fillAncestorsMap( _myMeshDS->IndexToShape( ++_nbSubShapes ));
1060     }
1061   }
1062   // if ( !index )
1063   //   return NULL; // neither sub-shape nor a group
1064
1065   SMESH_subMesh* aSubMesh = _subMeshHolder->Get( index );
1066   if ( !aSubMesh )
1067   {
1068     aSubMesh = new SMESH_subMesh(index, this, _myMeshDS, aSubShape);
1069     _subMeshHolder->Add( index, aSubMesh );
1070
1071     // include non-computable sub-meshes in SMESH_subMesh::_ancestors of sub-submeshes
1072     switch ( aSubShape.ShapeType() ) {
1073     case TopAbs_COMPOUND:
1074     case TopAbs_WIRE:
1075     case TopAbs_SHELL:
1076       for ( TopoDS_Iterator subIt( aSubShape ); subIt.More(); subIt.Next() )
1077       {
1078         SMESH_subMesh* sm = GetSubMesh( subIt.Value() );
1079         SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*inclideSelf=*/true);
1080         while ( smIt->more() )
1081           smIt->next()->ClearAncestors();
1082       }
1083     default:;
1084     }
1085   }
1086   return aSubMesh;
1087 }
1088
1089 //=============================================================================
1090 /*!
1091  * Get the SMESH_subMesh object implementation. Dont create it, return null
1092  * if it does not exist.
1093  */
1094 //=============================================================================
1095
1096 SMESH_subMesh *SMESH_Mesh::GetSubMeshContaining(const TopoDS_Shape & aSubShape) const
1097   throw(SALOME_Exception)
1098 {
1099   int index = _myMeshDS->ShapeToIndex(aSubShape);
1100   return GetSubMeshContaining( index );
1101 }
1102
1103 //=============================================================================
1104 /*!
1105  * Get the SMESH_subMesh object implementation. Dont create it, return null
1106  * if it does not exist.
1107  */
1108 //=============================================================================
1109
1110 SMESH_subMesh *SMESH_Mesh::GetSubMeshContaining(const int aShapeID) const
1111 throw(SALOME_Exception)
1112 {
1113   SMESH_subMesh *aSubMesh = _subMeshHolder->Get( aShapeID );
1114
1115   return aSubMesh;
1116 }
1117
1118 //================================================================================
1119 /*!
1120  * \brief Return submeshes of groups containing the given sub-shape
1121  */
1122 //================================================================================
1123
1124 list<SMESH_subMesh*>
1125 SMESH_Mesh::GetGroupSubMeshesContaining(const TopoDS_Shape & aSubShape) const
1126   throw(SALOME_Exception)
1127 {
1128   list<SMESH_subMesh*> found;
1129
1130   SMESH_subMesh * subMesh = GetSubMeshContaining(aSubShape);
1131   if ( !subMesh )
1132     return found;
1133
1134   // submeshes of groups have max IDs, so search from the map end
1135 SMESH_subMeshIteratorPtr smIt( _subMeshHolder->GetIterator( /*reverse=*/true ) );
1136   while ( smIt->more() ) {
1137     SMESH_subMesh*    sm = smIt->next();
1138     SMESHDS_SubMesh * ds = sm->GetSubMeshDS();
1139     if ( ds && ds->IsComplexSubmesh() ) {
1140       if ( SMESH_MesherHelper::IsSubShape( aSubShape, sm->GetSubShape() ))
1141       {
1142         found.push_back( sm );
1143         //break;
1144       }
1145     } else {
1146       break; // the rest sub-meshes are not those of groups
1147     }
1148   }
1149
1150   if ( found.empty() ) // maybe the main shape is a COMPOUND (issue 0021530)
1151   {
1152     if ( SMESH_subMesh * mainSM = GetSubMeshContaining(1) )
1153       if ( mainSM->GetSubShape().ShapeType() == TopAbs_COMPOUND )
1154       {
1155         TopoDS_Iterator it( mainSM->GetSubShape() );
1156         if ( it.Value().ShapeType() == aSubShape.ShapeType() &&
1157              SMESH_MesherHelper::IsSubShape( aSubShape, mainSM->GetSubShape() ))
1158           found.push_back( mainSM );
1159       }
1160   }
1161   return found;
1162 }
1163 //=======================================================================
1164 //function : IsUsedHypothesis
1165 //purpose  : Return True if anHyp is used to mesh aSubShape
1166 //=======================================================================
1167
1168 bool SMESH_Mesh::IsUsedHypothesis(SMESHDS_Hypothesis * anHyp,
1169                                   const SMESH_subMesh* aSubMesh)
1170 {
1171   SMESH_Hypothesis* hyp = static_cast<SMESH_Hypothesis*>(anHyp);
1172
1173   // check if anHyp can be used to mesh aSubMesh
1174   if ( !aSubMesh || !aSubMesh->IsApplicableHypotesis( hyp ))
1175     return false;
1176
1177   SMESH_Algo *algo = aSubMesh->GetAlgo();
1178
1179   // algorithm
1180   if (anHyp->GetType() > SMESHDS_Hypothesis::PARAM_ALGO)
1181     return ( anHyp == algo );
1182
1183   // algorithm parameter
1184   if (algo)
1185   {
1186     // look trough hypotheses used by algo
1187     const SMESH_HypoFilter* hypoKind;
1188     if (( hypoKind = algo->GetCompatibleHypoFilter( !hyp->IsAuxiliary() ))) {
1189       list <const SMESHDS_Hypothesis * > usedHyps;
1190       if ( GetHypotheses( aSubMesh, *hypoKind, usedHyps, true ))
1191         return ( find( usedHyps.begin(), usedHyps.end(), anHyp ) != usedHyps.end() );
1192     }
1193   }
1194
1195   return false;
1196 }
1197
1198 //=============================================================================
1199 /*!
1200  *
1201  */
1202 //=============================================================================
1203
1204 // const list < SMESH_subMesh * >&
1205 // SMESH_Mesh::GetSubMeshUsingHypothesis(SMESHDS_Hypothesis * anHyp)
1206 //   throw(SALOME_Exception)
1207 // {
1208 //   _subMeshesUsingHypothesisList.clear();
1209 //   SMESH_subMeshIteratorPtr smIt( _subMeshHolder->GetIterator() );
1210 //   while ( smIt->more() )
1211 //   {
1212 //     SMESH_subMesh* aSubMesh = smIt->next();
1213 //     if ( IsUsedHypothesis ( anHyp, aSubMesh ))
1214 //       _subMeshesUsingHypothesisList.push_back( aSubMesh );
1215 //   }
1216 //   return _subMeshesUsingHypothesisList;
1217 // }
1218
1219 //=======================================================================
1220 //function : NotifySubMeshesHypothesisModification
1221 //purpose  : Say all submeshes using theChangedHyp that it has been modified
1222 //=======================================================================
1223
1224 void SMESH_Mesh::NotifySubMeshesHypothesisModification(const SMESH_Hypothesis* hyp)
1225 {
1226   Unexpect aCatch(SalomeException);
1227
1228   if ( !GetMeshDS()->IsUsedHypothesis( hyp ))
1229     return;
1230
1231   if (_callUp)
1232     _callUp->HypothesisModified();
1233
1234   SMESH_Algo *algo;
1235   const SMESH_HypoFilter* compatibleHypoKind;
1236   list <const SMESHDS_Hypothesis * > usedHyps;
1237
1238   // keep sub-meshes not to miss ones whose state can change due to notifying others
1239   vector< SMESH_subMesh* > smToNotify;
1240
1241   SMESH_subMeshIteratorPtr smIt( _subMeshHolder->GetIterator() );
1242   while ( smIt->more() )
1243   {
1244     SMESH_subMesh* aSubMesh = smIt->next();
1245
1246     // if aSubMesh meshing depends on hyp,
1247     // we call aSubMesh->AlgoStateEngine( MODIF_HYP, hyp ) that causes either
1248     // 1) clearing of already computed aSubMesh or
1249     // 2) changing algo_state from MISSING_HYP to HYP_OK when parameters of hyp becomes valid,
1250     // other possible changes are not interesting. (IPAL0052457 - assigning hyp performance pb)
1251     if ( aSubMesh->GetComputeState() != SMESH_subMesh::COMPUTE_OK &&
1252          aSubMesh->GetComputeState() != SMESH_subMesh::FAILED_TO_COMPUTE &&
1253          aSubMesh->GetAlgoState()    != SMESH_subMesh::MISSING_HYP &&
1254          !hyp->DataDependOnParams() )
1255       continue;
1256
1257     const TopoDS_Shape & aSubShape = aSubMesh->GetSubShape();
1258
1259     if (( aSubMesh->IsApplicableHypotesis( hyp )) &&
1260         ( algo = aSubMesh->GetAlgo() )            &&
1261         ( compatibleHypoKind = algo->GetCompatibleHypoFilter( !hyp->IsAuxiliary() )) &&
1262         ( compatibleHypoKind->IsOk( hyp, aSubShape )))
1263     {
1264       // check if hyp is used by algo
1265       usedHyps.clear();
1266       if ( GetHypotheses( aSubMesh, *compatibleHypoKind, usedHyps, true ) &&
1267            find( usedHyps.begin(), usedHyps.end(), hyp ) != usedHyps.end() )
1268       {
1269         smToNotify.push_back( aSubMesh );
1270       }
1271     }
1272   }
1273
1274   for ( size_t i = 0; i < smToNotify.size(); ++i )
1275   {
1276     smToNotify[i]->AlgoStateEngine(SMESH_subMesh::MODIF_HYP,
1277                                    const_cast< SMESH_Hypothesis*>( hyp ));
1278   }
1279
1280   HasModificationsToDiscard(); // to reset _isModified flag if mesh becomes empty
1281   GetMeshDS()->Modified();
1282 }
1283
1284 //=============================================================================
1285 /*!
1286  *  Auto color functionality
1287  */
1288 //=============================================================================
1289 void SMESH_Mesh::SetAutoColor(bool theAutoColor) throw(SALOME_Exception)
1290 {
1291   Unexpect aCatch(SalomeException);
1292   _isAutoColor = theAutoColor;
1293 }
1294
1295 bool SMESH_Mesh::GetAutoColor() throw(SALOME_Exception)
1296 {
1297   Unexpect aCatch(SalomeException);
1298   return _isAutoColor;
1299 }
1300
1301 //=======================================================================
1302 //function : SetIsModified
1303 //purpose  : Set the flag meaning that the mesh has been edited "manually"
1304 //=======================================================================
1305
1306 void SMESH_Mesh::SetIsModified(bool isModified)
1307 {
1308   _isModified = isModified;
1309
1310   if ( _isModified )
1311     // check if mesh becomes empty as result of modification
1312     HasModificationsToDiscard();
1313 }
1314
1315 //=======================================================================
1316 //function : HasModificationsToDiscard
1317 //purpose  : Return true if the mesh has been edited since a total re-compute
1318 //           and those modifications may prevent successful partial re-compute.
1319 //           As a side effect reset _isModified flag if mesh is empty
1320 //issue    : 0020693
1321 //=======================================================================
1322
1323 bool SMESH_Mesh::HasModificationsToDiscard() const
1324 {
1325   if ( ! _isModified )
1326     return false;
1327
1328   // return true if the next Compute() will be partial and
1329   // existing but changed elements may prevent successful re-compute
1330   bool hasComputed = false, hasNotComputed = false;
1331 SMESH_subMeshIteratorPtr smIt( _subMeshHolder->GetIterator() );
1332   while ( smIt->more() )
1333   {
1334     const SMESH_subMesh* aSubMesh = smIt->next();
1335     switch ( aSubMesh->GetSubShape().ShapeType() )
1336     {
1337     case TopAbs_EDGE:
1338     case TopAbs_FACE:
1339     case TopAbs_SOLID:
1340       if ( aSubMesh->IsMeshComputed() )
1341         hasComputed = true;
1342       else
1343         hasNotComputed = true;
1344       if ( hasComputed && hasNotComputed)
1345         return true;
1346     }
1347   }
1348   if ( NbNodes() < 1 )
1349     const_cast<SMESH_Mesh*>(this)->_isModified = false;
1350
1351   return false;
1352 }
1353
1354 //================================================================================
1355 /*!
1356  * \brief Check if any groups of the same type have equal names
1357  */
1358 //================================================================================
1359
1360 bool SMESH_Mesh::HasDuplicatedGroupNamesMED()
1361 {
1362   //set<string> aGroupNames; // Corrected for Mantis issue 0020028
1363   map< SMDSAbs_ElementType, set<string> > aGroupNames;
1364   for ( map<int, SMESH_Group*>::iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ )
1365   {
1366     SMESH_Group* aGroup = it->second;
1367     SMDSAbs_ElementType aType = aGroup->GetGroupDS()->GetType();
1368     string aGroupName = aGroup->GetName();
1369     aGroupName.resize(MAX_MED_GROUP_NAME_LENGTH);
1370     if (!aGroupNames[aType].insert(aGroupName).second)
1371       return true;
1372   }
1373
1374   return false;
1375 }
1376
1377 //================================================================================
1378 /*!
1379  * \brief Export the mesh to a med file
1380  *  \param [in] file - name of the MED file
1381  *  \param [in] theMeshName - name of this mesh
1382  *  \param [in] theAutoGroups - boolean parameter for creating/not creating
1383  *              the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1384  *              the typical use is auto_groups=false.
1385  *  \param [in] theVersion - defines the version of format of MED file, that will be created
1386  *  \param [in] meshPart - mesh data to export
1387  *  \param [in] theAutoDimension - if \c true, a space dimension of a MED mesh can be either
1388      *         - 1D if all mesh nodes lie on OX coordinate axis, or
1389      *         - 2D if all mesh nodes lie on XOY coordinate plane, or
1390      *         - 3D in the rest cases.
1391      *         If \a theAutoDimension is \c false, the space dimension is always 3.
1392  *  \return int - mesh index in the file
1393  */
1394 //================================================================================
1395
1396 void SMESH_Mesh::ExportMED(const char *        file, 
1397                            const char*         theMeshName, 
1398                            bool                theAutoGroups,
1399                            int                 theVersion,
1400                            const SMESHDS_Mesh* meshPart,
1401                            bool                theAutoDimension,
1402                            bool                theAddODOnVertices)
1403   throw(SALOME_Exception)
1404 {
1405   SMESH_TRY;
1406
1407   DriverMED_W_SMESHDS_Mesh myWriter;
1408   myWriter.SetFile         ( file, MED::EVersion(theVersion) );
1409   myWriter.SetMesh         ( meshPart ? (SMESHDS_Mesh*) meshPart : _myMeshDS   );
1410   myWriter.SetAutoDimension( theAutoDimension );
1411   myWriter.AddODOnVertices ( theAddODOnVertices );
1412   if ( !theMeshName ) 
1413     myWriter.SetMeshId     ( _id         );
1414   else {
1415     myWriter.SetMeshId     ( -1          );
1416     myWriter.SetMeshName   ( theMeshName );
1417   }
1418
1419   if ( theAutoGroups ) {
1420     myWriter.AddGroupOfNodes();
1421     myWriter.AddGroupOfEdges();
1422     myWriter.AddGroupOfFaces();
1423     myWriter.AddGroupOfVolumes();
1424   }
1425
1426   // Pass groups to writer. Provide unique group names.
1427   //set<string> aGroupNames; // Corrected for Mantis issue 0020028
1428   if ( !meshPart )
1429   {
1430     map< SMDSAbs_ElementType, set<string> > aGroupNames;
1431     char aString [256];
1432     int maxNbIter = 10000; // to guarantee cycle finish
1433     for ( map<int, SMESH_Group*>::iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ ) {
1434       SMESH_Group*       aGroup   = it->second;
1435       SMESHDS_GroupBase* aGroupDS = aGroup->GetGroupDS();
1436       if ( aGroupDS ) {
1437         SMDSAbs_ElementType aType = aGroupDS->GetType();
1438         string aGroupName0 = aGroup->GetName();
1439         aGroupName0.resize(MAX_MED_GROUP_NAME_LENGTH);
1440         string aGroupName = aGroupName0;
1441         for (int i = 1; !aGroupNames[aType].insert(aGroupName).second && i < maxNbIter; i++) {
1442           sprintf(&aString[0], "GR_%d_%s", i, aGroupName0.c_str());
1443           aGroupName = aString;
1444           aGroupName.resize(MAX_MED_GROUP_NAME_LENGTH);
1445         }
1446         aGroupDS->SetStoreName( aGroupName.c_str() );
1447         myWriter.AddGroup( aGroupDS );
1448       }
1449     }
1450   }
1451   // Perform export
1452   myWriter.Perform();
1453
1454   SMESH_CATCH( SMESH::throwSalomeEx );
1455 }
1456
1457 //================================================================================
1458 /*!
1459  * \brief Export the mesh to a SAUV file
1460  */
1461 //================================================================================
1462
1463 void SMESH_Mesh::ExportSAUV(const char *file, 
1464                             const char* theMeshName, 
1465                             bool theAutoGroups)
1466   throw(SALOME_Exception)
1467 {
1468   std::string medfilename(file);
1469   medfilename += ".med";
1470   std::string cmd;
1471 #ifdef WIN32
1472   cmd = "%PYTHONBIN% ";
1473 #else
1474   cmd = "python ";
1475 #endif
1476   cmd += "-c \"";
1477   cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1478   cmd += "\"";
1479   system(cmd.c_str());
1480   ExportMED(medfilename.c_str(), theMeshName, theAutoGroups, 1);
1481 #ifdef WIN32
1482   cmd = "%PYTHONBIN% ";
1483 #else
1484   cmd = "python ";
1485 #endif
1486   cmd += "-c \"";
1487   cmd += "from medutilities import convert ; convert(r'" + medfilename + "', 'MED', 'GIBI', 1, r'" + file + "')";
1488   cmd += "\"";
1489   system(cmd.c_str());
1490 #ifdef WIN32
1491   cmd = "%PYTHONBIN% ";
1492 #else
1493   cmd = "python ";
1494 #endif
1495   cmd += "-c \"";
1496   cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1497   cmd += "\"";
1498   system(cmd.c_str());
1499 }
1500
1501 //================================================================================
1502 /*!
1503  * \brief Export the mesh to a DAT file
1504  */
1505 //================================================================================
1506
1507 void SMESH_Mesh::ExportDAT(const char *        file,
1508                            const SMESHDS_Mesh* meshPart) throw(SALOME_Exception)
1509 {
1510   Unexpect aCatch(SalomeException);
1511   DriverDAT_W_SMDS_Mesh myWriter;
1512   myWriter.SetFile( file );
1513   myWriter.SetMesh( meshPart ? (SMESHDS_Mesh*) meshPart : _myMeshDS );
1514   myWriter.SetMeshId(_id);
1515   myWriter.Perform();
1516 }
1517
1518 //================================================================================
1519 /*!
1520  * \brief Export the mesh to an UNV file
1521  */
1522 //================================================================================
1523
1524 void SMESH_Mesh::ExportUNV(const char *        file,
1525                            const SMESHDS_Mesh* meshPart) throw(SALOME_Exception)
1526 {
1527   Unexpect aCatch(SalomeException);
1528   DriverUNV_W_SMDS_Mesh myWriter;
1529   myWriter.SetFile( file );
1530   myWriter.SetMesh( meshPart ? (SMESHDS_Mesh*) meshPart : _myMeshDS );
1531   myWriter.SetMeshId(_id);
1532   //  myWriter.SetGroups(_mapGroup);
1533
1534   if ( !meshPart )
1535   {
1536     for ( map<int, SMESH_Group*>::iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ ) {
1537       SMESH_Group*       aGroup   = it->second;
1538       SMESHDS_GroupBase* aGroupDS = aGroup->GetGroupDS();
1539       if ( aGroupDS ) {
1540         string aGroupName = aGroup->GetName();
1541         aGroupDS->SetStoreName( aGroupName.c_str() );
1542         myWriter.AddGroup( aGroupDS );
1543       }
1544     }
1545   }
1546   myWriter.Perform();
1547 }
1548
1549 //================================================================================
1550 /*!
1551  * \brief Export the mesh to an STL file
1552  */
1553 //================================================================================
1554
1555 void SMESH_Mesh::ExportSTL(const char *        file,
1556                            const bool          isascii,
1557                            const SMESHDS_Mesh* meshPart) throw(SALOME_Exception)
1558 {
1559   Unexpect aCatch(SalomeException);
1560   DriverSTL_W_SMDS_Mesh myWriter;
1561   myWriter.SetFile( file );
1562   myWriter.SetIsAscii( isascii );
1563   myWriter.SetMesh( meshPart ? (SMESHDS_Mesh*) meshPart : _myMeshDS);
1564   myWriter.SetMeshId(_id);
1565   myWriter.Perform();
1566 }
1567
1568 //================================================================================
1569 /*!
1570  * \brief Export the mesh to the CGNS file
1571  */
1572 //================================================================================
1573
1574 void SMESH_Mesh::ExportCGNS(const char *        file,
1575                             const SMESHDS_Mesh* meshDS,
1576                             const char *        meshName)
1577 {
1578   int res = Driver_Mesh::DRS_FAIL;
1579 #ifdef WITH_CGNS
1580   DriverCGNS_Write myWriter;
1581   myWriter.SetFile( file );
1582   myWriter.SetMesh( const_cast<SMESHDS_Mesh*>( meshDS ));
1583   myWriter.SetMeshName( SMESH_Comment("Mesh_") << meshDS->GetPersistentId());
1584   if ( meshName && meshName[0] )
1585     myWriter.SetMeshName( meshName );
1586   res = myWriter.Perform();
1587 #endif
1588   if ( res != Driver_Mesh::DRS_OK )
1589     throw SALOME_Exception("Export failed");
1590 }
1591
1592 //================================================================================
1593 /*!
1594  * \brief Export the mesh to a GMF file
1595  */
1596 //================================================================================
1597
1598 void SMESH_Mesh::ExportGMF(const char *        file,
1599                            const SMESHDS_Mesh* meshDS,
1600                            bool                withRequiredGroups)
1601 {
1602   DriverGMF_Write myWriter;
1603   myWriter.SetFile( file );
1604   myWriter.SetMesh( const_cast<SMESHDS_Mesh*>( meshDS ));
1605   myWriter.SetExportRequiredGroups( withRequiredGroups );
1606
1607   myWriter.Perform();
1608 }
1609
1610 //================================================================================
1611 /*!
1612  * \brief Return a ratio of "compute cost" of computed sub-meshes to the whole
1613  *        "compute cost".
1614  */
1615 //================================================================================
1616
1617 double SMESH_Mesh::GetComputeProgress() const
1618 {
1619   double totalCost = 1e-100, computedCost = 0;
1620   const SMESH_subMesh* curSM = _gen->GetCurrentSubMesh();
1621
1622   // get progress of a current algo
1623   TColStd_MapOfInteger currentSubIds; 
1624   if ( curSM )
1625     if ( SMESH_Algo* algo = curSM->GetAlgo() )
1626     {
1627       int algoNotDoneCost = 0, algoDoneCost = 0;
1628       const std::vector<SMESH_subMesh*>& smToCompute = algo->SubMeshesToCompute();
1629       for ( size_t i = 0; i < smToCompute.size(); ++i )
1630       {
1631         if ( smToCompute[i]->IsEmpty() )
1632           algoNotDoneCost += smToCompute[i]->GetComputeCost();
1633         else
1634           algoDoneCost += smToCompute[i]->GetComputeCost();
1635         currentSubIds.Add( smToCompute[i]->GetId() );
1636       }
1637       double rate = 0;
1638       try
1639       {
1640         OCC_CATCH_SIGNALS;
1641         rate = algo->GetProgress();
1642       }
1643       catch (...) {
1644 #ifdef _DEBUG_
1645         cerr << "Exception in " << algo->GetName() << "::GetProgress()" << endl;
1646 #endif
1647       }
1648       if ( 0. < rate && rate < 1.001 )
1649       {
1650         computedCost += rate * ( algoDoneCost + algoNotDoneCost );
1651       }
1652       else
1653       {
1654         rate = algo->GetProgressByTic();
1655         computedCost += algoDoneCost + rate * algoNotDoneCost;
1656       }
1657       // cout << "rate: "<<rate << " algoNotDoneCost: " << algoNotDoneCost << endl;
1658     }
1659
1660   // get cost of already treated sub-meshes
1661   if ( SMESH_subMesh* mainSM = GetSubMeshContaining( 1 ))
1662   {
1663     SMESH_subMeshIteratorPtr smIt = mainSM->getDependsOnIterator(/*includeSelf=*/true);
1664     while ( smIt->more() )
1665     {
1666       const SMESH_subMesh* sm = smIt->next();
1667       const int smCost = sm->GetComputeCost();
1668       totalCost += smCost;
1669       if ( !currentSubIds.Contains( sm->GetId() ) )
1670       {
1671         if (( !sm->IsEmpty() ) ||
1672             ( sm->GetComputeState() == SMESH_subMesh::FAILED_TO_COMPUTE &&
1673               !sm->DependsOn( curSM ) ))
1674           computedCost += smCost;
1675       }
1676     }
1677   }
1678   // cout << "Total: " << totalCost
1679   //      << " computed: " << computedCost << " progress: " << computedCost / totalCost
1680   //      << " nbElems: " << GetMeshDS()->GetMeshInfo().NbElements() << endl;
1681   return computedCost / totalCost;
1682 }
1683
1684 //================================================================================
1685 /*!
1686  * \brief Return number of nodes in the mesh
1687  */
1688 //================================================================================
1689
1690 int SMESH_Mesh::NbNodes() const throw(SALOME_Exception)
1691 {
1692   Unexpect aCatch(SalomeException);
1693   return _myMeshDS->NbNodes();
1694 }
1695
1696 //================================================================================
1697 /*!
1698  * \brief  Return number of edges of given order in the mesh
1699  */
1700 //================================================================================
1701
1702 int SMESH_Mesh::Nb0DElements() const throw(SALOME_Exception)
1703 {
1704   Unexpect aCatch(SalomeException);
1705   return _myMeshDS->GetMeshInfo().Nb0DElements();
1706 }
1707
1708 //================================================================================
1709 /*!
1710  * \brief  Return number of edges of given order in the mesh
1711  */
1712 //================================================================================
1713
1714 int SMESH_Mesh::NbEdges(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1715 {
1716   Unexpect aCatch(SalomeException);
1717   return _myMeshDS->GetMeshInfo().NbEdges(order);
1718 }
1719
1720 //================================================================================
1721 /*!
1722  * \brief Return number of faces of given order in the mesh
1723  */
1724 //================================================================================
1725
1726 int SMESH_Mesh::NbFaces(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1727 {
1728   Unexpect aCatch(SalomeException);
1729   return _myMeshDS->GetMeshInfo().NbFaces(order);
1730 }
1731
1732 //================================================================================
1733 /*!
1734  * \brief Return the number of faces in the mesh
1735  */
1736 //================================================================================
1737
1738 int SMESH_Mesh::NbTriangles(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1739 {
1740   Unexpect aCatch(SalomeException);
1741   return _myMeshDS->GetMeshInfo().NbTriangles(order);
1742 }
1743
1744 //================================================================================
1745 /*!
1746  * \brief Return number of biquadratic triangles in the mesh
1747  */
1748 //================================================================================
1749
1750 int SMESH_Mesh::NbBiQuadTriangles() const throw(SALOME_Exception)
1751 {
1752   Unexpect aCatch(SalomeException);
1753   return _myMeshDS->GetMeshInfo().NbBiQuadTriangles();
1754 }
1755
1756 //================================================================================
1757 /*!
1758  * \brief Return the number nodes faces in the mesh
1759  */
1760 //================================================================================
1761
1762 int SMESH_Mesh::NbQuadrangles(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1763 {
1764   Unexpect aCatch(SalomeException);
1765   return _myMeshDS->GetMeshInfo().NbQuadrangles(order);
1766 }
1767
1768 //================================================================================
1769 /*!
1770  * \brief Return number of biquadratic quadrangles in the mesh
1771  */
1772 //================================================================================
1773
1774 int SMESH_Mesh::NbBiQuadQuadrangles() const throw(SALOME_Exception)
1775 {
1776   Unexpect aCatch(SalomeException);
1777   return _myMeshDS->GetMeshInfo().NbBiQuadQuadrangles();
1778 }
1779
1780 //================================================================================
1781 /*!
1782  * \brief Return the number of polygonal faces in the mesh
1783  */
1784 //================================================================================
1785
1786 int SMESH_Mesh::NbPolygons() const throw(SALOME_Exception)
1787 {
1788   Unexpect aCatch(SalomeException);
1789   return _myMeshDS->GetMeshInfo().NbPolygons();
1790 }
1791
1792 //================================================================================
1793 /*!
1794  * \brief Return number of volumes of given order in the mesh
1795  */
1796 //================================================================================
1797
1798 int SMESH_Mesh::NbVolumes(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1799 {
1800   Unexpect aCatch(SalomeException);
1801   return _myMeshDS->GetMeshInfo().NbVolumes(order);
1802 }
1803
1804 //================================================================================
1805 /*!
1806  * \brief  Return number of tetrahedrons of given order in the mesh
1807  */
1808 //================================================================================
1809
1810 int SMESH_Mesh::NbTetras(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1811 {
1812   Unexpect aCatch(SalomeException);
1813   return _myMeshDS->GetMeshInfo().NbTetras(order);
1814 }
1815
1816 //================================================================================
1817 /*!
1818  * \brief  Return number of hexahedrons of given order in the mesh
1819  */
1820 //================================================================================
1821
1822 int SMESH_Mesh::NbHexas(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1823 {
1824   Unexpect aCatch(SalomeException);
1825   return _myMeshDS->GetMeshInfo().NbHexas(order);
1826 }
1827
1828 //================================================================================
1829 /*!
1830  * \brief  Return number of triquadratic hexahedrons in the mesh
1831  */
1832 //================================================================================
1833
1834 int SMESH_Mesh::NbTriQuadraticHexas() const throw(SALOME_Exception)
1835 {
1836   Unexpect aCatch(SalomeException);
1837   return _myMeshDS->GetMeshInfo().NbTriQuadHexas();
1838 }
1839
1840 //================================================================================
1841 /*!
1842  * \brief  Return number of pyramids of given order in the mesh
1843  */
1844 //================================================================================
1845
1846 int SMESH_Mesh::NbPyramids(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1847 {
1848   Unexpect aCatch(SalomeException);
1849   return _myMeshDS->GetMeshInfo().NbPyramids(order);
1850 }
1851
1852 //================================================================================
1853 /*!
1854  * \brief  Return number of prisms (penthahedrons) of given order in the mesh
1855  */
1856 //================================================================================
1857
1858 int SMESH_Mesh::NbPrisms(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1859 {
1860   Unexpect aCatch(SalomeException);
1861   return _myMeshDS->GetMeshInfo().NbPrisms(order);
1862 }
1863
1864 //================================================================================
1865 /*!
1866  * \brief  Return number of hexagonal prisms in the mesh
1867  */
1868 //================================================================================
1869
1870 int SMESH_Mesh::NbHexagonalPrisms() const throw(SALOME_Exception)
1871 {
1872   Unexpect aCatch(SalomeException);
1873   return _myMeshDS->GetMeshInfo().NbHexPrisms();
1874 }
1875
1876 //================================================================================
1877 /*!
1878  * \brief  Return number of polyhedrons in the mesh
1879  */
1880 //================================================================================
1881
1882 int SMESH_Mesh::NbPolyhedrons() const throw(SALOME_Exception)
1883 {
1884   Unexpect aCatch(SalomeException);
1885   return _myMeshDS->GetMeshInfo().NbPolyhedrons();
1886 }
1887
1888 //================================================================================
1889 /*!
1890  * \brief  Return number of ball elements in the mesh
1891  */
1892 //================================================================================
1893
1894 int SMESH_Mesh::NbBalls() const throw(SALOME_Exception)
1895 {
1896   Unexpect aCatch(SalomeException);
1897   return _myMeshDS->GetMeshInfo().NbBalls();
1898 }
1899
1900 //================================================================================
1901 /*!
1902  * \brief  Return number of submeshes in the mesh
1903  */
1904 //================================================================================
1905
1906 int SMESH_Mesh::NbSubMesh() const throw(SALOME_Exception)
1907 {
1908   Unexpect aCatch(SalomeException);
1909   return _myMeshDS->NbSubMesh();
1910 }
1911
1912 //================================================================================
1913 /*!
1914  * \brief Returns number of meshes in the Study, that is supposed to be
1915  *        equal to SMESHDS_Document::NbMeshes()
1916  */
1917 //================================================================================
1918
1919 int SMESH_Mesh::NbMeshes() const // nb meshes in the Study
1920 {
1921   return _myDocument->NbMeshes();
1922 }
1923
1924 //=======================================================================
1925 //function : IsNotConformAllowed
1926 //purpose  : check if a hypothesis alowing notconform mesh is present
1927 //=======================================================================
1928
1929 bool SMESH_Mesh::IsNotConformAllowed() const
1930 {
1931   if(MYDEBUG) MESSAGE("SMESH_Mesh::IsNotConformAllowed");
1932
1933   static SMESH_HypoFilter filter( SMESH_HypoFilter::HasName( "NotConformAllowed" ));
1934   return GetHypothesis( _myMeshDS->ShapeToMesh(), filter, false );
1935 }
1936
1937 //=======================================================================
1938 //function : IsMainShape
1939 //purpose  : 
1940 //=======================================================================
1941
1942 bool SMESH_Mesh::IsMainShape(const TopoDS_Shape& theShape) const
1943 {
1944   return theShape.IsSame(_myMeshDS->ShapeToMesh() );
1945 }
1946
1947 //=============================================================================
1948 /*!
1949  *  
1950  */
1951 //=============================================================================
1952
1953 SMESH_Group* SMESH_Mesh::AddGroup (const SMDSAbs_ElementType theType,
1954                                    const char*               theName,
1955                                    int&                      theId,
1956                                    const TopoDS_Shape&       theShape,
1957                                    const SMESH_PredicatePtr& thePredicate)
1958 {
1959   if (_mapGroup.count(_groupId))
1960     return NULL;
1961   theId = _groupId;
1962   SMESH_Group* aGroup = new SMESH_Group (theId, this, theType, theName, theShape, thePredicate);
1963   GetMeshDS()->AddGroup( aGroup->GetGroupDS() );
1964   _mapGroup[_groupId++] = aGroup;
1965   return aGroup;
1966 }
1967
1968 //================================================================================
1969 /*!
1970  * \brief Creates a group based on an existing SMESHDS group. Group ID should be unique
1971  */
1972 //================================================================================
1973
1974 SMESH_Group* SMESH_Mesh::AddGroup (SMESHDS_GroupBase* groupDS) throw(SALOME_Exception)
1975 {
1976   if ( !groupDS ) 
1977     throw SALOME_Exception(LOCALIZED ("SMESH_Mesh::AddGroup(): NULL SMESHDS_GroupBase"));
1978
1979   map <int, SMESH_Group*>::iterator i_g = _mapGroup.find( groupDS->GetID() );
1980   if ( i_g != _mapGroup.end() && i_g->second )
1981   {
1982     if ( i_g->second->GetGroupDS() == groupDS )
1983       return i_g->second;
1984     else
1985       throw SALOME_Exception(LOCALIZED ("SMESH_Mesh::AddGroup() wrong ID of SMESHDS_GroupBase"));
1986   }
1987   SMESH_Group* aGroup = new SMESH_Group (groupDS);
1988   _mapGroup[ groupDS->GetID() ] = aGroup;
1989   GetMeshDS()->AddGroup( aGroup->GetGroupDS() );
1990
1991   _groupId = 1 + _mapGroup.rbegin()->first;
1992
1993   return aGroup;
1994 }
1995
1996
1997 //================================================================================
1998 /*!
1999  * \brief Creates SMESH_Groups for not wrapped SMESHDS_Groups
2000  *  \retval bool - true if new SMESH_Groups have been created
2001  * 
2002  */
2003 //================================================================================
2004
2005 bool SMESH_Mesh::SynchronizeGroups()
2006 {
2007   int nbGroups = _mapGroup.size();
2008   const set<SMESHDS_GroupBase*>& groups = _myMeshDS->GetGroups();
2009   set<SMESHDS_GroupBase*>::const_iterator gIt = groups.begin();
2010   for ( ; gIt != groups.end(); ++gIt )
2011   {
2012     SMESHDS_GroupBase* groupDS = (SMESHDS_GroupBase*) *gIt;
2013     _groupId = groupDS->GetID();
2014     if ( !_mapGroup.count( _groupId ))
2015       _mapGroup[_groupId] = new SMESH_Group( groupDS );
2016   }
2017   if ( !_mapGroup.empty() )
2018     _groupId = _mapGroup.rbegin()->first + 1;
2019
2020   return nbGroups < _mapGroup.size();
2021 }
2022
2023 //================================================================================
2024 /*!
2025  * \brief Return iterator on all existing groups
2026  */
2027 //================================================================================
2028
2029 SMESH_Mesh::GroupIteratorPtr SMESH_Mesh::GetGroups() const
2030 {
2031   typedef map <int, SMESH_Group *> TMap;
2032   return GroupIteratorPtr( new SMDS_mapIterator<TMap>( _mapGroup ));
2033 }
2034
2035 //=============================================================================
2036 /*!
2037  * \brief Return a group by ID
2038  */
2039 //=============================================================================
2040
2041 SMESH_Group* SMESH_Mesh::GetGroup (const int theGroupID)
2042 {
2043   if (_mapGroup.find(theGroupID) == _mapGroup.end())
2044     return NULL;
2045   return _mapGroup[theGroupID];
2046 }
2047
2048
2049 //=============================================================================
2050 /*!
2051  * \brief Return IDs of all groups
2052  */
2053 //=============================================================================
2054
2055 list<int> SMESH_Mesh::GetGroupIds() const
2056 {
2057   list<int> anIds;
2058   for ( map<int, SMESH_Group*>::const_iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ )
2059     anIds.push_back( it->first );
2060   
2061   return anIds;
2062 }
2063
2064 //================================================================================
2065 /*!
2066  * \brief Set a caller of methods at level of CORBA API implementation.
2067  * The set upCaller will be deleted by SMESH_Mesh
2068  */
2069 //================================================================================
2070
2071 void SMESH_Mesh::SetCallUp( TCallUp* upCaller )
2072 {
2073   if ( _callUp ) delete _callUp;
2074   _callUp = upCaller;
2075 }
2076
2077 //=============================================================================
2078 /*!
2079  *  
2080  */
2081 //=============================================================================
2082
2083 bool SMESH_Mesh::RemoveGroup (const int theGroupID)
2084 {
2085   if (_mapGroup.find(theGroupID) == _mapGroup.end())
2086     return false;
2087   GetMeshDS()->RemoveGroup( _mapGroup[theGroupID]->GetGroupDS() );
2088   delete _mapGroup[theGroupID];
2089   _mapGroup.erase (theGroupID);
2090   if (_callUp)
2091     _callUp->RemoveGroup( theGroupID );
2092   return true;
2093 }
2094
2095 //=======================================================================
2096 //function : GetAncestors
2097 //purpose  : return list of ancestors of theSubShape in the order
2098 //           that lower dimention shapes come first.
2099 //=======================================================================
2100
2101 const TopTools_ListOfShape& SMESH_Mesh::GetAncestors(const TopoDS_Shape& theS) const
2102 {
2103   if ( _mapAncestors.Contains( theS ) )
2104     return _mapAncestors.FindFromKey( theS );
2105
2106   static TopTools_ListOfShape emptyList;
2107   return emptyList;
2108 }
2109
2110 //=======================================================================
2111 //function : Dump
2112 //purpose  : dumps contents of mesh to stream [ debug purposes ]
2113 //=======================================================================
2114
2115 ostream& SMESH_Mesh::Dump(ostream& save)
2116 {
2117   int clause = 0;
2118   save << "========================== Dump contents of mesh ==========================" << endl << endl;
2119   save << ++clause << ") Total number of nodes:   \t"    << NbNodes() << endl;
2120   save << ++clause << ") Total number of edges:   \t"    << NbEdges() << endl;
2121   save << ++clause << ") Total number of faces:   \t"    << NbFaces() << endl;
2122   save << ++clause << ") Total number of polygons:\t"    << NbPolygons() << endl;
2123   save << ++clause << ") Total number of volumes:\t"     << NbVolumes() << endl;
2124   save << ++clause << ") Total number of polyhedrons:\t" << NbPolyhedrons() << endl << endl;
2125   for ( int isQuadratic = 0; isQuadratic < 2; ++isQuadratic )
2126   {
2127     string orderStr = isQuadratic ? "quadratic" : "linear";
2128     SMDSAbs_ElementOrder order  = isQuadratic ? ORDER_QUADRATIC : ORDER_LINEAR;
2129
2130     save << ++clause << ") Total number of " << orderStr << " edges:\t" << NbEdges(order) << endl;
2131     save << ++clause << ") Total number of " << orderStr << " faces:\t" << NbFaces(order) << endl;
2132     if ( NbFaces(order) > 0 ) {
2133       int nb3 = NbTriangles(order);
2134       int nb4 = NbQuadrangles(order);
2135       save << clause << ".1) Number of " << orderStr << " triangles:  \t" << nb3 << endl;
2136       save << clause << ".2) Number of " << orderStr << " quadrangles:\t" << nb4 << endl;
2137       if ( nb3 + nb4 !=  NbFaces(order) ) {
2138         map<int,int> myFaceMap;
2139         SMDS_FaceIteratorPtr itFaces=_myMeshDS->facesIterator();
2140         while( itFaces->more( ) ) {
2141           int nbNodes = itFaces->next()->NbNodes();
2142           if ( myFaceMap.find( nbNodes ) == myFaceMap.end() )
2143             myFaceMap[ nbNodes ] = 0;
2144           myFaceMap[ nbNodes ] = myFaceMap[ nbNodes ] + 1;
2145         }
2146         save << clause << ".3) Faces in detail: " << endl;
2147         map <int,int>::iterator itF;
2148         for (itF = myFaceMap.begin(); itF != myFaceMap.end(); itF++)
2149           save << "--> nb nodes: " << itF->first << " - nb elemens:\t" << itF->second << endl;
2150       }
2151     }
2152     save << ++clause << ") Total number of " << orderStr << " volumes:\t" << NbVolumes(order) << endl;
2153     if ( NbVolumes(order) > 0 ) {
2154       int nb8 = NbHexas(order);
2155       int nb4 = NbTetras(order);
2156       int nb5 = NbPyramids(order);
2157       int nb6 = NbPrisms(order);
2158       save << clause << ".1) Number of " << orderStr << " hexahedrons:\t" << nb8 << endl;
2159       save << clause << ".2) Number of " << orderStr << " tetrahedrons:\t" << nb4 << endl;
2160       save << clause << ".3) Number of " << orderStr << " prisms:      \t" << nb6 << endl;
2161       save << clause << ".4) Number of " << orderStr << " pyramids:\t" << nb5 << endl;
2162       if ( nb8 + nb4 + nb5 + nb6 != NbVolumes(order) ) {
2163         map<int,int> myVolumesMap;
2164         SMDS_VolumeIteratorPtr itVolumes=_myMeshDS->volumesIterator();
2165         while( itVolumes->more( ) ) {
2166           int nbNodes = itVolumes->next()->NbNodes();
2167           if ( myVolumesMap.find( nbNodes ) == myVolumesMap.end() )
2168             myVolumesMap[ nbNodes ] = 0;
2169           myVolumesMap[ nbNodes ] = myVolumesMap[ nbNodes ] + 1;
2170         }
2171         save << clause << ".5) Volumes in detail: " << endl;
2172         map <int,int>::iterator itV;
2173         for (itV = myVolumesMap.begin(); itV != myVolumesMap.end(); itV++)
2174           save << "--> nb nodes: " << itV->first << " - nb elemens:\t" << itV->second << endl;
2175       }
2176     }
2177     save << endl;
2178   }
2179   save << "===========================================================================" << endl;
2180   return save;
2181 }
2182
2183 //=======================================================================
2184 //function : GetElementType
2185 //purpose  : Returns type of mesh element with certain id
2186 //=======================================================================
2187
2188 SMDSAbs_ElementType SMESH_Mesh::GetElementType( const int id, const bool iselem )
2189 {
2190   return _myMeshDS->GetElementType( id, iselem );
2191 }
2192
2193 //=============================================================================
2194 /*!
2195  *  \brief Convert group on geometry into standalone group
2196  */
2197 //=============================================================================
2198
2199 SMESH_Group* SMESH_Mesh::ConvertToStandalone ( int theGroupID )
2200 {
2201   SMESH_Group* aGroup = 0;
2202   map < int, SMESH_Group * >::iterator itg = _mapGroup.find( theGroupID );
2203   if ( itg == _mapGroup.end() )
2204     return aGroup;
2205
2206   SMESH_Group* anOldGrp = (*itg).second;
2207   if ( !anOldGrp || !anOldGrp->GetGroupDS() )
2208     return aGroup;
2209   SMESHDS_GroupBase* anOldGrpDS = anOldGrp->GetGroupDS();
2210
2211   // create new standalone group
2212   aGroup = new SMESH_Group (theGroupID, this, anOldGrpDS->GetType(), anOldGrp->GetName() );
2213   _mapGroup[theGroupID] = aGroup;
2214
2215   SMESHDS_Group* aNewGrpDS = dynamic_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
2216   GetMeshDS()->RemoveGroup( anOldGrpDS );
2217   GetMeshDS()->AddGroup( aNewGrpDS );
2218
2219   // add elements (or nodes) into new created group
2220   SMDS_ElemIteratorPtr anItr = anOldGrpDS->GetElements();
2221   while ( anItr->more() )
2222     aNewGrpDS->Add( (anItr->next())->GetID() );
2223
2224   // set color
2225   aNewGrpDS->SetColor( anOldGrpDS->GetColor() );
2226
2227   // remove old group
2228   delete anOldGrp;
2229
2230   return aGroup;
2231 }
2232
2233 //=============================================================================
2234 /*!
2235  *  \brief remove submesh order  from Mesh
2236  */
2237 //=============================================================================
2238
2239 void SMESH_Mesh::ClearMeshOrder()
2240 {
2241   _mySubMeshOrder.clear();
2242 }
2243
2244 //=============================================================================
2245 /*!
2246  *  \brief remove submesh order  from Mesh
2247  */
2248 //=============================================================================
2249
2250 void SMESH_Mesh::SetMeshOrder(const TListOfListOfInt& theOrder )
2251 {
2252   _mySubMeshOrder = theOrder;
2253 }
2254
2255 //=============================================================================
2256 /*!
2257  *  \brief return submesh order if any
2258  */
2259 //=============================================================================
2260
2261 const TListOfListOfInt& SMESH_Mesh::GetMeshOrder() const
2262 {
2263   return _mySubMeshOrder;
2264 }
2265
2266 //=============================================================================
2267 /*!
2268  *  \brief fill _mapAncestors
2269  */
2270 //=============================================================================
2271
2272 void SMESH_Mesh::fillAncestorsMap(const TopoDS_Shape& theShape)
2273 {
2274   int desType, ancType;
2275   if ( !theShape.IsSame( GetShapeToMesh()) && theShape.ShapeType() == TopAbs_COMPOUND )
2276   {
2277     // a geom group is added. Insert it into lists of ancestors before
2278     // the first ancestor more complex than group members
2279     TopoDS_Iterator subIt( theShape );
2280     if ( !subIt.More() ) return;
2281     int memberType = subIt.Value().ShapeType();
2282     for ( desType = TopAbs_VERTEX; desType >= memberType; desType-- )
2283       for (TopExp_Explorer des( theShape, TopAbs_ShapeEnum( desType )); des.More(); des.Next())
2284       {
2285         if ( !_mapAncestors.Contains( des.Current() )) continue;// issue 0020982
2286         TopTools_ListOfShape& ancList = _mapAncestors.ChangeFromKey( des.Current() );
2287         TopTools_ListIteratorOfListOfShape ancIt (ancList);
2288         while ( ancIt.More() && ancIt.Value().ShapeType() >= memberType )
2289           ancIt.Next();
2290         if ( ancIt.More() ) ancList.InsertBefore( theShape, ancIt );
2291         else                ancList.Append( theShape );
2292       }
2293   }
2294   else // else added for 52457: Addition of hypotheses is 8 time longer than meshing
2295   {
2296     for ( desType = TopAbs_VERTEX; desType > TopAbs_COMPOUND; desType-- )
2297       for ( ancType = desType - 1; ancType >= TopAbs_COMPOUND; ancType-- )
2298         TopExp::MapShapesAndAncestors ( theShape,
2299                                         (TopAbs_ShapeEnum) desType,
2300                                         (TopAbs_ShapeEnum) ancType,
2301                                         _mapAncestors );
2302   }
2303   // visit COMPOUNDs inside a COMPOUND that are not reachable by TopExp_Explorer
2304   if ( theShape.ShapeType() == TopAbs_COMPOUND )
2305   {
2306     TopoDS_Iterator sIt(theShape);
2307     if ( sIt.More() && sIt.Value().ShapeType() == TopAbs_COMPOUND )
2308       for ( ; sIt.More(); sIt.Next() )
2309         if ( sIt.Value().ShapeType() == TopAbs_COMPOUND )
2310           fillAncestorsMap( sIt.Value() );
2311   }
2312 }
2313
2314 //=============================================================================
2315 /*!
2316  * \brief sort submeshes according to stored mesh order
2317  * \param theListToSort in out list to be sorted
2318  * \return FALSE if nothing sorted
2319  */
2320 //=============================================================================
2321
2322  bool SMESH_Mesh::SortByMeshOrder(std::vector<SMESH_subMesh*>& theListToSort) const
2323 {
2324   if ( !_mySubMeshOrder.size() || theListToSort.size() < 2)
2325     return true;
2326   
2327   bool res = false;
2328   vector<SMESH_subMesh*> onlyOrderedList;
2329   // collect all ordered submeshes in one list as pointers
2330   // and get their positions within theListToSort
2331   typedef vector<SMESH_subMesh*>::iterator TPosInList;
2332   map< int, TPosInList > sortedPos;
2333   TPosInList smBeg = theListToSort.begin(), smEnd = theListToSort.end();
2334   TListOfListOfInt::const_iterator listIdsIt = _mySubMeshOrder.begin();
2335   for( ; listIdsIt != _mySubMeshOrder.end(); listIdsIt++)
2336   {
2337     const TListOfInt& listOfId = *listIdsIt;
2338     // convert sm ids to sm's
2339     vector<SMESH_subMesh*> smVec;
2340     TListOfInt::const_iterator idIt = listOfId.begin();
2341     for ( ; idIt != listOfId.end(); idIt++ ) {
2342       if ( SMESH_subMesh * sm = GetSubMeshContaining( *idIt )) {
2343         if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->IsComplexSubmesh() )
2344         {
2345           SMESHDS_SubMeshIteratorPtr smdsIt = sm->GetSubMeshDS()->GetSubMeshIterator();
2346           while ( smdsIt->more() )
2347           {
2348             const SMESHDS_SubMesh* smDS = smdsIt->next();
2349             if (( sm = GetSubMeshContaining( smDS->GetID() )))
2350               smVec.push_back( sm );
2351           }
2352         }
2353         else
2354         {
2355           smVec.push_back( sm );
2356         }
2357       }
2358     }
2359     // find smVec items in theListToSort
2360     for ( size_t i = 0; i < smVec.size(); ++i )
2361     {
2362       TPosInList smPos = find( smBeg, smEnd, smVec[i] );
2363       if ( smPos != smEnd ) {
2364         onlyOrderedList.push_back( smVec[i] );
2365         sortedPos[ distance( smBeg, smPos )] = smPos;
2366       }
2367     }
2368   }
2369   if (onlyOrderedList.size() < 2)
2370     return res;
2371   res = true;
2372
2373   vector<SMESH_subMesh*>::iterator onlyBIt = onlyOrderedList.begin();
2374   vector<SMESH_subMesh*>::iterator onlyEIt = onlyOrderedList.end();
2375
2376   // iterate on ordered submeshes and insert them in detected positions
2377   map< int, TPosInList >::iterator i_pos = sortedPos.begin();
2378   for ( ; onlyBIt != onlyEIt; ++onlyBIt, ++i_pos )
2379     *(i_pos->second) = *onlyBIt;
2380
2381   return res;
2382 }
2383
2384 //================================================================================
2385 /*!
2386  * \brief Return true if given order of sub-meshes is OK
2387  */
2388 //================================================================================
2389
2390 bool SMESH_Mesh::IsOrderOK( const SMESH_subMesh* smBefore,
2391                             const SMESH_subMesh* smAfter ) const
2392 {
2393   TListOfListOfInt::const_iterator listIdsIt = _mySubMeshOrder.begin();
2394   TListOfInt::const_iterator idBef, idAft;
2395   for( ; listIdsIt != _mySubMeshOrder.end(); listIdsIt++)
2396   {
2397     const TListOfInt& listOfId = *listIdsIt;
2398     idBef = std::find( listOfId.begin(), listOfId.end(), smBefore->GetId() );
2399     if ( idBef != listOfId.end() )
2400       idAft = std::find( listOfId.begin(), listOfId.end(), smAfter->GetId() );
2401     if ( idAft != listOfId.end () )
2402       return ( std::distance( listOfId.begin(), idBef ) <
2403                std::distance( listOfId.begin(), idAft )   );
2404   }
2405   return true; // no order imposed to given submeshes
2406
2407
2408 //=============================================================================
2409 /*!
2410  * \brief sort submeshes according to stored mesh order
2411  * \param theListToSort in out list to be sorted
2412  * \return FALSE if nothing sorted
2413  */
2414 //=============================================================================
2415
2416 void SMESH_Mesh::getAncestorsSubMeshes (const TopoDS_Shape&            theSubShape,
2417                                         std::vector< SMESH_subMesh* >& theSubMeshes) const
2418 {
2419   theSubMeshes.clear();
2420   TopTools_ListIteratorOfListOfShape it( GetAncestors( theSubShape ));
2421   for (; it.More(); it.Next() )
2422     if ( SMESH_subMesh* sm = GetSubMeshContaining( it.Value() ))
2423       theSubMeshes.push_back(sm);
2424
2425   // sort submeshes according to stored mesh order
2426   SortByMeshOrder( theSubMeshes );
2427 }