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