Salome HOME
Optimize performance of mesh deletion upon hyp modification
[modules/smesh.git] / src / SMESH / SMESH_subMesh.cxx
1 // Copyright (C) 2007-2016  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 //  SMESH SMESH : implementaion of SMESH idl descriptions
24 //  File   : SMESH_subMesh.cxx
25 //  Author : Paul RASCLE, EDF
26 //  Module : SMESH
27
28 #include "SMESH_subMesh.hxx"
29
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Mesh.hxx"
32 #include "SMESH_Algo.hxx"
33 #include "SMESH_Comment.hxx"
34 #include "SMESH_Gen.hxx"
35 #include "SMESH_HypoFilter.hxx"
36 #include "SMESH_Hypothesis.hxx"
37 #include "SMESH_Mesh.hxx"
38 #include "SMESH_MesherHelper.hxx"
39 #include "SMESH_subMeshEventListener.hxx"
40
41 #include <Basics_OCCTVersion.hxx>
42
43 #include "utilities.h"
44 #include "OpUtil.hxx"
45 #include "Basics_Utils.hxx"
46
47 #include <BRep_Builder.hxx>
48 #include <BRep_Tool.hxx>
49 #include <TopExp.hxx>
50 #include <TopExp_Explorer.hxx>
51 #include <TopTools_IndexedMapOfShape.hxx>
52 #include <TopTools_ListIteratorOfListOfShape.hxx>
53 #include <TopTools_ListOfShape.hxx>
54 #include <TopoDS.hxx>
55 #include <TopoDS_Compound.hxx>
56 #include <TopoDS_Iterator.hxx>
57 #include <gp_Pnt.hxx>
58
59 #include <Standard_OutOfMemory.hxx>
60 #include <Standard_ErrorHandler.hxx>
61
62 #include <numeric>
63
64 using namespace std;
65
66 //=============================================================================
67 /*!
68  * \brief Allocate some memory at construction and release it at destruction.
69  * Is used to be able to continue working after mesh generation breaks due to
70  * lack of memory
71  */
72 //=============================================================================
73
74 struct MemoryReserve
75 {
76   char* myBuf;
77   MemoryReserve(): myBuf( new char[1024*1024*2] ){}
78   ~MemoryReserve() { delete [] myBuf; }
79 };
80
81 //=============================================================================
82 /*!
83  *  default constructor:
84  */
85 //=============================================================================
86
87 SMESH_subMesh::SMESH_subMesh(int                  Id,
88                              SMESH_Mesh *         father,
89                              SMESHDS_Mesh *       meshDS,
90                              const TopoDS_Shape & aSubShape)
91 {
92   _subShape           = aSubShape;
93   _subMeshDS          = meshDS->MeshElements(_subShape);   // may be null ...
94   _father             = father;
95   _Id                 = Id;
96   _dependenceAnalysed = _alwaysComputed = false;
97   _algo               = 0;
98   if (_subShape.ShapeType() == TopAbs_VERTEX)
99   {
100     _algoState = HYP_OK;
101     _computeState = READY_TO_COMPUTE;
102   }
103   else
104   {
105     _algoState = NO_ALGO;
106     _computeState = NOT_READY;
107   }
108   _computeCost = 0; // how costly is to compute this sub-mesh
109   _realComputeCost = 0;
110 }
111
112 //=============================================================================
113 /*!
114  *
115  */
116 //=============================================================================
117
118 SMESH_subMesh::~SMESH_subMesh()
119 {
120   deleteOwnListeners();
121 }
122
123 //=============================================================================
124 /*!
125  *
126  */
127 //=============================================================================
128
129 int SMESH_subMesh::GetId() const
130 {
131   //MESSAGE("SMESH_subMesh::GetId");
132   return _Id;
133 }
134
135 //=============================================================================
136 /*!
137  *
138  */
139 //=============================================================================
140
141 SMESHDS_SubMesh * SMESH_subMesh::GetSubMeshDS()
142 {
143   // submesh appears in DS only when a mesher set nodes and elements on a shape
144   return _subMeshDS ? _subMeshDS : _subMeshDS = _father->GetMeshDS()->MeshElements(_subShape); // may be null
145 }
146
147 //=============================================================================
148 /*!
149  *
150  */
151 //=============================================================================
152
153 const SMESHDS_SubMesh * SMESH_subMesh::GetSubMeshDS() const
154 {
155   return ((SMESH_subMesh*) this )->GetSubMeshDS();
156 }
157
158 //=============================================================================
159 /*!
160  *
161  */
162 //=============================================================================
163
164 SMESHDS_SubMesh* SMESH_subMesh::CreateSubMeshDS()
165 {
166   if ( !GetSubMeshDS() ) {
167     SMESHDS_Mesh* meshDS = _father->GetMeshDS();
168     meshDS->NewSubMesh( meshDS->ShapeToIndex( _subShape ) );
169   }
170   return GetSubMeshDS();
171 }
172
173 //=============================================================================
174 /*!
175  *
176  */
177 //=============================================================================
178
179 SMESH_subMesh *SMESH_subMesh::GetFirstToCompute()
180 {
181   SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(true,false);
182   while ( smIt->more() ) {
183     SMESH_subMesh *sm = smIt->next();
184     if ( sm->GetComputeState() == READY_TO_COMPUTE )
185       return sm;
186   }
187   return 0;                     // nothing to compute
188 }
189
190 //================================================================================
191 /*!
192  * \brief Returns a current algorithm
193  */
194 //================================================================================
195
196 SMESH_Algo* SMESH_subMesh::GetAlgo() const
197 {
198   if ( !_algo )
199   {
200     SMESH_subMesh* me = const_cast< SMESH_subMesh* >( this );
201     me->_algo = _father->GetGen()->GetAlgo( me );
202   }
203   return _algo;
204 }
205
206 //================================================================================
207 /*!
208  * \brief Allow algo->Compute() if a sub-shape of lower dim is meshed but
209  *        none mesh entity is bound to it (PAL13615, 2nd part)
210  */
211 //================================================================================
212
213 void SMESH_subMesh::SetIsAlwaysComputed(bool isAlCo)
214 {
215   _alwaysComputed = isAlCo;
216   if ( _alwaysComputed )
217     _computeState = COMPUTE_OK;
218   else
219     ComputeStateEngine( CHECK_COMPUTE_STATE );
220 }
221
222 //=======================================================================
223 /*!
224  * \brief Return true if no mesh entities is bound to the submesh
225  */
226 //=======================================================================
227
228 bool SMESH_subMesh::IsEmpty() const
229 {
230   if (SMESHDS_SubMesh * subMeshDS = ((SMESH_subMesh*)this)->GetSubMeshDS())
231     return (!subMeshDS->NbElements() && !subMeshDS->NbNodes());
232   return true;
233 }
234
235 //=======================================================================
236 //function : IsMeshComputed
237 //purpose  : check if _subMeshDS contains mesh elements
238 //=======================================================================
239
240 bool SMESH_subMesh::IsMeshComputed() const
241 {
242   if ( _alwaysComputed )
243     return true;
244   // algo may bind a sub-mesh not to _subShape, eg 3D algo
245   // sets nodes on SHELL while _subShape may be SOLID
246
247   SMESHDS_Mesh* meshDS = _father->GetMeshDS();
248   int dim = SMESH_Gen::GetShapeDim( _subShape );
249   int type = _subShape.ShapeType();
250   for ( ; type <= TopAbs_VERTEX; type++) {
251     if ( dim == SMESH_Gen::GetShapeDim( (TopAbs_ShapeEnum) type ))
252     {
253       TopExp_Explorer exp( _subShape, (TopAbs_ShapeEnum) type );
254       for ( ; exp.More(); exp.Next() )
255       {
256         if ( SMESHDS_SubMesh * smDS = meshDS->MeshElements( exp.Current() ))
257         {
258           bool computed = (dim > 0) ? smDS->NbElements() : smDS->NbNodes();
259           if ( computed )
260             return true;
261         }
262       }
263     }
264     else
265       break;
266   }
267
268   return false;
269 }
270
271 //=============================================================================
272 /*!
273  * Return true if all sub-meshes have been meshed
274  */
275 //=============================================================================
276
277 bool SMESH_subMesh::SubMeshesComputed(bool * isFailedToCompute/*=0*/) const
278 {
279   int myDim = SMESH_Gen::GetShapeDim( _subShape );
280   int dimToCheck = myDim - 1;
281   bool subMeshesComputed = true;
282   if ( isFailedToCompute ) *isFailedToCompute = false;
283   // check sub-meshes with upper dimension => reverse iteration
284   SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,true);
285   while ( smIt->more() )
286   {
287     SMESH_subMesh *sm = smIt->next();
288     if ( sm->_alwaysComputed )
289       continue;
290     const TopoDS_Shape & ss = sm->GetSubShape();
291
292     // MSV 07.04.2006: restrict checking to myDim-1 only. Ex., there is no sense
293     // in checking of existence of edges if the algo needs only faces. Moreover,
294     // degenerated edges may have no sub-mesh, as after computing NETGEN_2D.
295     if ( !_algo || _algo->NeedDiscreteBoundary() ) {
296       int dim = SMESH_Gen::GetShapeDim( ss );
297       if (dim < dimToCheck)
298         break; // the rest sub-meshes are all of less dimension
299     }
300     SMESHDS_SubMesh * ds = sm->GetSubMeshDS();
301     bool computeOk = ((sm->GetComputeState() == COMPUTE_OK ) ||
302                       (ds && ( dimToCheck ? ds->NbElements() : ds->NbNodes() )));
303     if (!computeOk)
304     {
305       subMeshesComputed = false;
306
307       if ( isFailedToCompute && !(*isFailedToCompute) )
308         *isFailedToCompute = ( sm->GetComputeState() == FAILED_TO_COMPUTE );
309
310       if ( !isFailedToCompute )
311         break;
312     }
313   }
314   return subMeshesComputed;
315 }
316
317 //================================================================================
318 /*!
319  * \brief Return cost of computing this sub-mesh. If hypotheses are not well defined,
320  *        zero is returned
321  *  \return int - the computation cost in abstract units.
322  */
323 //================================================================================
324
325 int SMESH_subMesh::GetComputeCost() const
326 {
327   return _realComputeCost;
328 }
329
330 //================================================================================
331 /*!
332  * \brief Return cost of computing this sub-mesh. The cost depends on the shape type
333  *        and number of sub-meshes this one DependsOn().
334  *  \return int - the computation cost in abstract units.
335  */
336 //================================================================================
337
338 int SMESH_subMesh::computeCost() const
339 {
340   if ( !_computeCost )
341   {
342     int computeCost;
343     switch ( _subShape.ShapeType() ) {
344     case TopAbs_SOLID:
345     case TopAbs_SHELL: computeCost = 5000; break;
346     case TopAbs_FACE:  computeCost = 500; break;
347     case TopAbs_EDGE:  computeCost = 2; break;
348     default:           computeCost = 1;
349     }
350     SMESH_subMeshIteratorPtr childIt = getDependsOnIterator(/*includeSelf=*/false);
351     while ( childIt->more() )
352       computeCost += childIt->next()->computeCost();
353
354     ((SMESH_subMesh*)this)->_computeCost = computeCost;
355   }
356   return _computeCost;
357 }
358
359 //=============================================================================
360 /*!
361  * Returns all sub-meshes this one depend on
362  */
363 //=============================================================================
364
365 const map < int, SMESH_subMesh * >& SMESH_subMesh::DependsOn()
366 {
367   if ( _dependenceAnalysed || !_father->HasShapeToMesh() )
368     return _mapDepend;
369
370   int type = _subShape.ShapeType();
371   switch (type)
372   {
373   case TopAbs_COMPOUND:
374   {
375     list< TopoDS_Shape > compounds( 1, _subShape );
376     list< TopoDS_Shape >::iterator comp = compounds.begin();
377     for ( ; comp != compounds.end(); ++comp )
378     {
379       for ( TopoDS_Iterator sub( *comp ); sub.More(); sub.Next() )
380         switch ( sub.Value().ShapeType() )
381         {
382         case TopAbs_COMPOUND:  compounds.push_back( sub.Value() ); break;
383         case TopAbs_COMPSOLID: insertDependence( sub.Value(), TopAbs_SOLID ); break;
384         case TopAbs_SOLID:     insertDependence( sub.Value(), TopAbs_SOLID ); break;
385         case TopAbs_SHELL:     insertDependence( sub.Value(), TopAbs_FACE ); break;
386         case TopAbs_FACE:      insertDependence( sub.Value(), TopAbs_FACE ); break;
387         case TopAbs_WIRE:      insertDependence( sub.Value(), TopAbs_EDGE ); break;
388         case TopAbs_EDGE:      insertDependence( sub.Value(), TopAbs_EDGE ); break;
389         case TopAbs_VERTEX:    insertDependence( sub.Value(), TopAbs_VERTEX ); break;
390         default:;
391         }
392     }
393   }
394   break;
395   case TopAbs_COMPSOLID: insertDependence( _subShape, TopAbs_SOLID ); break;
396   case TopAbs_SOLID:     insertDependence( _subShape, TopAbs_FACE );
397   { /*internal EDGE*/    insertDependence( _subShape, TopAbs_EDGE, TopAbs_WIRE ); break; }
398   case TopAbs_SHELL:     insertDependence( _subShape, TopAbs_FACE ); break;
399   case TopAbs_FACE:      insertDependence( _subShape, TopAbs_EDGE ); break;
400   case TopAbs_WIRE:      insertDependence( _subShape, TopAbs_EDGE ); break;
401   case TopAbs_EDGE:      insertDependence( _subShape, TopAbs_VERTEX ); break;
402   default:;
403   }
404   _dependenceAnalysed = true;
405   return _mapDepend;
406 }
407
408 //================================================================================
409 /*!
410  * \brief Return a key for SMESH_subMesh::_mapDepend map
411  */
412 //================================================================================
413
414 namespace
415 {
416   int dependsOnMapKey( TopAbs_ShapeEnum type, int shapeID )
417   {
418     int ordType = 9 - int(type);               // 2 = Vertex, 8 = CompSolid
419     int     cle = shapeID;
420     cle += 10000000 * ordType;    // sort map by ordType then index
421     return cle;
422   }
423   int dependsOnMapKey( const SMESH_subMesh* sm )
424   {
425     return dependsOnMapKey( sm->GetSubShape().ShapeType(), sm->GetId() );
426   }
427 }
428
429 //=============================================================================
430 /*!
431  * Add sub-meshes on sub-shapes of a given type into the dependence map.
432  */
433 //=============================================================================
434
435 void SMESH_subMesh::insertDependence(const TopoDS_Shape aShape,
436                                      TopAbs_ShapeEnum   aSubType,
437                                      TopAbs_ShapeEnum   avoidType)
438 {
439   TopExp_Explorer sub( aShape, aSubType, avoidType );
440   for ( ; sub.More(); sub.Next() )
441   {
442     SMESH_subMesh *aSubMesh = _father->GetSubMesh( sub.Current() );
443     if ( aSubMesh->GetId() == 0 )
444       continue;  // not a sub-shape of the shape to mesh
445     int cle = dependsOnMapKey( aSubMesh );
446     if ( _mapDepend.find( cle ) == _mapDepend.end())
447     {
448       _mapDepend[cle] = aSubMesh;
449       const map < int, SMESH_subMesh * > & subMap = aSubMesh->DependsOn();
450       _mapDepend.insert( subMap.begin(), subMap.end() );
451     }
452   }
453 }
454
455 //================================================================================
456 /*!
457  * \brief Return \c true if \a this sub-mesh depends on \a other
458  */
459 //================================================================================
460
461 bool SMESH_subMesh::DependsOn( const SMESH_subMesh* other ) const
462 {
463   return other ? _mapDepend.count( dependsOnMapKey( other )) : false;
464 }
465
466 //================================================================================
467 /*!
468  * \brief Return \c true if \a this sub-mesh depends on a \a shape
469  */
470 //================================================================================
471
472 bool SMESH_subMesh::DependsOn( const int shapeID ) const
473 {
474   return DependsOn( _father->GetSubMeshContaining( shapeID ));
475 }
476
477 //=============================================================================
478 /*!
479  * Return a shape of \a this sub-mesh
480  */
481 //=============================================================================
482
483 const TopoDS_Shape & SMESH_subMesh::GetSubShape() const
484 {
485   return _subShape;
486 }
487
488 //=======================================================================
489 //function : CanAddHypothesis
490 //purpose  : return true if theHypothesis can be attached to me:
491 //           its dimention is checked
492 //=======================================================================
493
494 bool SMESH_subMesh::CanAddHypothesis(const SMESH_Hypothesis* theHypothesis) const
495 {
496   int aHypDim   = theHypothesis->GetDim();
497   int aShapeDim = SMESH_Gen::GetShapeDim(_subShape);
498   // issue 21106. Forbid 3D mesh on the SHELL
499   // if (aHypDim == 3 && aShapeDim == 3) {
500   //   // check case of open shell
501   //   //if (_subShape.ShapeType() == TopAbs_SHELL && !_subShape.Closed())
502   //   if (_subShape.ShapeType() == TopAbs_SHELL && !BRep_Tool::IsClosed(_subShape))
503   //     return false;
504   // }
505   if ( aHypDim <= aShapeDim )
506     return true;
507
508   return false;
509 }
510
511 //=======================================================================
512 //function : IsApplicableHypotesis
513 //purpose  :
514 //=======================================================================
515
516 bool SMESH_subMesh::IsApplicableHypotesis(const SMESH_Hypothesis* theHypothesis,
517                                           const TopAbs_ShapeEnum  theShapeType)
518 {
519   if ( theHypothesis->GetType() > SMESHDS_Hypothesis::PARAM_ALGO)
520   {
521     // algorithm
522     if ( theHypothesis->GetShapeType() & (1<< theShapeType))
523       // issue 21106. Forbid 3D mesh on the SHELL
524       return !( theHypothesis->GetDim() == 3 && theShapeType == TopAbs_SHELL );
525     else
526       return false;
527   }
528
529   // hypothesis
530   switch ( theShapeType ) {
531   case TopAbs_VERTEX:
532   case TopAbs_EDGE:
533   case TopAbs_FACE:
534   case TopAbs_SOLID:
535     return SMESH_Gen::GetShapeDim( theShapeType ) == theHypothesis->GetDim();
536
537   case TopAbs_SHELL:
538     // Special case for algorithms, building 2D mesh on a whole shell.
539     // Before this fix there was a problem after restoring from study,
540     // because in that case algorithm is assigned before hypothesis
541     // (on shell in problem case) and hypothesis is checked on faces
542     // (because it is 2D), where we have NO_ALGO state.
543     // Now 2D hypothesis is also applicable to shells.
544     return (theHypothesis->GetDim() == 2 || theHypothesis->GetDim() == 3);
545
546 //   case TopAbs_WIRE:
547 //   case TopAbs_COMPSOLID:
548 //   case TopAbs_COMPOUND:
549   default:;
550   }
551   return false;
552 }
553
554 //================================================================================
555 /*!
556  * \brief Treats modification of hypotheses definition
557  *  \param [in] event - what happens
558  *  \param [in] anHyp - a hypothesis
559  *  \return SMESH_Hypothesis::Hypothesis_Status - a treatment result.
560  * 
561  * Optional description of a problematic situation (if any) can be retrieved
562  * via GetComputeError().
563  */
564 //================================================================================
565
566 SMESH_Hypothesis::Hypothesis_Status
567   SMESH_subMesh::AlgoStateEngine(algo_event event, SMESH_Hypothesis * anHyp)
568 {
569   // **** les retour des evenement shape sont significatifs
570   // (add ou remove fait ou non)
571   // le retour des evenement father n'indiquent pas que add ou remove fait
572
573   SMESH_Hypothesis::Hypothesis_Status aux_ret, ret = SMESH_Hypothesis::HYP_OK;
574   if ( _Id == 0 ) return ret; // not a sub-shape of the shape to mesh
575
576   SMESHDS_Mesh* meshDS =_father->GetMeshDS();
577   SMESH_Algo*   algo   = 0;
578   _algo = 0;
579
580   if (_subShape.ShapeType() == TopAbs_VERTEX )
581   {
582     if ( anHyp->GetDim() != 0) {
583       if (event == ADD_HYP || event == ADD_ALGO)
584         return SMESH_Hypothesis::HYP_BAD_DIM;
585       else
586         return SMESH_Hypothesis::HYP_OK;
587     }
588     // 0D hypothesis
589     else if ( _algoState == HYP_OK ) {
590       // update default _algoState
591       if ( event != REMOVE_FATHER_ALGO )
592       {
593         _algoState = NO_ALGO;
594         algo = GetAlgo();
595         if ( algo ) {
596           _algoState = MISSING_HYP;
597           if ( event == REMOVE_FATHER_HYP ||
598                algo->CheckHypothesis(*_father,_subShape, aux_ret))
599             _algoState = HYP_OK;
600         }
601       }
602     }
603   }
604
605   int oldAlgoState = _algoState;
606   bool modifiedHyp = (event == MODIF_HYP);  // if set to true, force event MODIF_ALGO_STATE
607   SMESH_Algo* algoRequiringCleaning = 0;
608
609   bool isApplicableHyp = IsApplicableHypotesis( anHyp );
610
611   if (event == ADD_ALGO || event == ADD_FATHER_ALGO)
612   {
613     // -------------------------------------------
614     // check if a shape needed by algo is present
615     // -------------------------------------------
616     algo = static_cast< SMESH_Algo* >( anHyp );
617     if ( !_father->HasShapeToMesh() && algo->NeedShape() )
618       return SMESH_Hypothesis::HYP_NEED_SHAPE;
619     // ----------------------
620     // check mesh conformity
621     // ----------------------
622     if (isApplicableHyp && !_father->IsNotConformAllowed() && !IsConform( algo ))
623       return SMESH_Hypothesis::HYP_NOTCONFORM;
624
625     // check if all-dimensional algo is hidden by other local one
626     if ( event == ADD_ALGO ) {
627       SMESH_HypoFilter filter( SMESH_HypoFilter::HasType( algo->GetType() ));
628       filter.Or( SMESH_HypoFilter::HasType( algo->GetType()+1 ));
629       filter.Or( SMESH_HypoFilter::HasType( algo->GetType()+2 ));
630       if ( SMESH_Algo * curAlgo = (SMESH_Algo*)_father->GetHypothesis( this, filter, true ))
631         if ( !curAlgo->NeedDiscreteBoundary() )
632           algoRequiringCleaning = curAlgo;
633     }
634   }
635
636   // ----------------------------------
637   // add a hypothesis to DS if possible
638   // ----------------------------------
639   if (event == ADD_HYP || event == ADD_ALGO)
640   {
641     if ( ! CanAddHypothesis( anHyp )) // check dimension
642       return SMESH_Hypothesis::HYP_BAD_DIM;
643
644     if ( !anHyp->IsAuxiliary() && getSimilarAttached( _subShape, anHyp ) )
645       return SMESH_Hypothesis::HYP_ALREADY_EXIST;
646
647     if ( !meshDS->AddHypothesis(_subShape, anHyp))
648       return SMESH_Hypothesis::HYP_ALREADY_EXIST;
649   }
650
651   // --------------------------
652   // remove a hypothesis from DS
653   // --------------------------
654   if (event == REMOVE_HYP || event == REMOVE_ALGO)
655   {
656     if (!meshDS->RemoveHypothesis(_subShape, anHyp))
657       return SMESH_Hypothesis::HYP_OK; // nothing changes
658
659     if (event == REMOVE_ALGO)
660     {
661       algo = dynamic_cast<SMESH_Algo*> (anHyp);
662       if (!algo->NeedDiscreteBoundary())
663         algoRequiringCleaning = algo;
664     }
665   }
666
667   // ------------------
668   // analyse algo state
669   // ------------------
670   if (!isApplicableHyp)
671     return ret; // not applicable hypotheses do not change algo state
672
673   if (( algo = GetAlgo()))
674     algo->InitComputeError();
675
676   switch (_algoState)
677   {
678
679     // ----------------------------------------------------------------------
680
681   case NO_ALGO:
682     switch (event) {
683     case ADD_HYP:
684       break;
685     case ADD_ALGO: {
686       algo = GetAlgo();
687       ASSERT(algo);
688       if (algo->CheckHypothesis((*_father),_subShape, aux_ret))
689         setAlgoState(HYP_OK);
690       else if ( algo->IsStatusFatal( aux_ret )) {
691         meshDS->RemoveHypothesis(_subShape, anHyp);
692         ret = aux_ret;
693       }
694       else
695         setAlgoState(MISSING_HYP);
696       break;
697     }
698     case REMOVE_HYP:
699     case REMOVE_ALGO:
700     case ADD_FATHER_HYP:
701       break;
702     case ADD_FATHER_ALGO: {    // Algo just added in father
703       algo = GetAlgo();
704       ASSERT(algo);
705       if ( algo == anHyp ) {
706         if ( algo->CheckHypothesis((*_father),_subShape, aux_ret))
707           setAlgoState(HYP_OK);
708         else
709           setAlgoState(MISSING_HYP);
710       }
711       break;
712     }
713     case REMOVE_FATHER_HYP:
714       break;
715     case REMOVE_FATHER_ALGO: {
716       algo = GetAlgo();
717       if (algo)
718       {
719         if ( algo->CheckHypothesis((*_father),_subShape, aux_ret ))
720             setAlgoState(HYP_OK);
721         else
722           setAlgoState(MISSING_HYP);
723       }
724       break;
725     }
726     case MODIF_HYP: break;
727     default:
728       ASSERT(0);
729       break;
730     }
731     break;
732
733     // ----------------------------------------------------------------------
734
735   case MISSING_HYP:
736     switch (event)
737     {
738     case ADD_HYP: {
739       algo = GetAlgo();
740       ASSERT(algo);
741       if ( algo->CheckHypothesis((*_father),_subShape, ret ))
742         setAlgoState(HYP_OK);
743       if (SMESH_Hypothesis::IsStatusFatal( ret ))
744         meshDS->RemoveHypothesis(_subShape, anHyp);
745       else if (!_father->IsUsedHypothesis( anHyp, this ))
746       {
747         meshDS->RemoveHypothesis(_subShape, anHyp);
748         ret = SMESH_Hypothesis::HYP_INCOMPATIBLE;
749       }
750       break;
751     }
752     case ADD_ALGO: {           //already existing algo : on father ?
753       algo = GetAlgo();
754       ASSERT(algo);
755       if ( algo->CheckHypothesis((*_father),_subShape, aux_ret ))// ignore hyp status
756         setAlgoState(HYP_OK);
757       else if ( algo->IsStatusFatal( aux_ret )) {
758         meshDS->RemoveHypothesis(_subShape, anHyp);
759         ret = aux_ret;
760       }
761       else
762         setAlgoState(MISSING_HYP);
763       break;
764     }
765     case REMOVE_HYP:
766       break;
767     case REMOVE_ALGO: {        // perhaps a father algo applies ?
768       algo = GetAlgo();
769       if (algo == NULL)  // no more algo applying on sub-shape...
770       {
771         setAlgoState(NO_ALGO);
772       }
773       else
774       {
775         if ( algo->CheckHypothesis((*_father),_subShape, aux_ret ))
776           setAlgoState(HYP_OK);
777         else
778           setAlgoState(MISSING_HYP);
779       }
780       break;
781     }
782     case MODIF_HYP: // assigned hypothesis value may become good
783     case ADD_FATHER_HYP: {
784       algo = GetAlgo();
785       ASSERT(algo);
786       if ( algo->CheckHypothesis((*_father),_subShape, aux_ret ))
787         setAlgoState(HYP_OK);
788       else
789         setAlgoState(MISSING_HYP);
790       break;
791     }
792     case ADD_FATHER_ALGO: { // new father algo
793       algo = GetAlgo();
794       ASSERT( algo );
795       if ( algo == anHyp ) {
796         if ( algo->CheckHypothesis((*_father),_subShape, aux_ret ))
797           setAlgoState(HYP_OK);
798         else
799           setAlgoState(MISSING_HYP);
800       }
801       break;
802     }
803     case REMOVE_FATHER_HYP:    // nothing to do
804       break;
805     case REMOVE_FATHER_ALGO: {
806       algo = GetAlgo();
807       if (algo == NULL)  // no more applying algo on father
808       {
809         setAlgoState(NO_ALGO);
810       }
811       else
812       {
813         if ( algo->CheckHypothesis((*_father),_subShape , aux_ret ))
814           setAlgoState(HYP_OK);
815         else
816           setAlgoState(MISSING_HYP);
817       }
818       break;
819     }
820     default:
821       ASSERT(0);
822       break;
823     }
824     break;
825
826     // ----------------------------------------------------------------------
827
828   case HYP_OK:
829     switch (event)
830     {
831     case ADD_HYP: {
832       algo = GetAlgo();
833       ASSERT(algo);
834       if (!algo->CheckHypothesis((*_father),_subShape, ret ))
835       {
836         if ( !SMESH_Hypothesis::IsStatusFatal( ret ))
837           // ret should be fatal: anHyp was not added
838           ret = SMESH_Hypothesis::HYP_INCOMPATIBLE;
839       }
840       else if (!_father->IsUsedHypothesis( anHyp, this ))
841         ret = SMESH_Hypothesis::HYP_INCOMPATIBLE;
842
843       if (SMESH_Hypothesis::IsStatusFatal( ret ))
844       {
845         MESSAGE("do not add extra hypothesis");
846         meshDS->RemoveHypothesis(_subShape, anHyp);
847       }
848       else
849       {
850         modifiedHyp = true;
851       }
852       break;
853     }
854     case ADD_ALGO: {           //already existing algo : on father ?
855       algo = GetAlgo();
856       if ( algo->CheckHypothesis((*_father),_subShape, aux_ret )) {
857         // check if algo changes
858         SMESH_HypoFilter f;
859         f.Init(   SMESH_HypoFilter::IsAlgo() );
860         f.And(    SMESH_HypoFilter::IsApplicableTo( _subShape ));
861         f.AndNot( SMESH_HypoFilter::Is( algo ));
862         const SMESH_Hypothesis * prevAlgo = _father->GetHypothesis( this, f, true );
863         if (prevAlgo &&
864             string( algo->GetName()) != prevAlgo->GetName())
865           modifiedHyp = true;
866       }
867       else
868         setAlgoState(MISSING_HYP);
869       break;
870     }
871     case REMOVE_HYP: {
872       algo = GetAlgo();
873       ASSERT(algo);
874       if ( algo->CheckHypothesis((*_father),_subShape, aux_ret ))
875         setAlgoState(HYP_OK);
876       else
877         setAlgoState(MISSING_HYP);
878       modifiedHyp = true;
879       break;
880     }
881     case REMOVE_ALGO: {         // perhaps a father algo applies ?
882       algo = GetAlgo();
883       if (algo == NULL)   // no more algo applying on sub-shape...
884       {
885         setAlgoState(NO_ALGO);
886       }
887       else
888       {
889         if ( algo->CheckHypothesis((*_father),_subShape, aux_ret )) {
890           // check if algo remains
891           if ( anHyp != algo && strcmp( anHyp->GetName(), algo->GetName()) )
892             modifiedHyp = true;
893         }
894         else
895           setAlgoState(MISSING_HYP);
896       }
897       break;
898     }
899     case MODIF_HYP: // hypothesis value may become bad
900     case ADD_FATHER_HYP: {  // new father hypothesis ?
901       algo = GetAlgo();
902       ASSERT(algo);
903       if ( algo->CheckHypothesis((*_father),_subShape, aux_ret ))
904       {
905         if (_father->IsUsedHypothesis( anHyp, this )) // new Hyp
906           modifiedHyp = true;
907       }
908       else
909         setAlgoState(MISSING_HYP);
910       break;
911     }
912     case ADD_FATHER_ALGO: {
913       algo = GetAlgo();
914       if ( algo == anHyp ) { // a new algo on father
915         if ( algo->CheckHypothesis((*_father),_subShape, aux_ret )) {
916           // check if algo changes
917           SMESH_HypoFilter f;
918           f.Init(   SMESH_HypoFilter::IsAlgo() );
919           f.And(    SMESH_HypoFilter::IsApplicableTo( _subShape ));
920           f.AndNot( SMESH_HypoFilter::Is( algo ));
921           const SMESH_Hypothesis* prevAlgo = _father->GetHypothesis( this, f, true );
922           if (prevAlgo &&
923               string(algo->GetName()) != string(prevAlgo->GetName()) )
924             modifiedHyp = true;
925         }
926         else
927           setAlgoState(MISSING_HYP);
928       }
929       break;
930     }
931     case REMOVE_FATHER_HYP: {
932       algo = GetAlgo();
933       ASSERT(algo);
934       if ( algo->CheckHypothesis((*_father),_subShape, aux_ret )) {
935         // is there the same local hyp or maybe a new father algo applied?
936         if ( !getSimilarAttached( _subShape, anHyp ) )
937           modifiedHyp = true;
938       }
939       else
940         setAlgoState(MISSING_HYP);
941       break;
942     }
943     case REMOVE_FATHER_ALGO: {
944       // IPAL21346. Edges not removed when Netgen 1d-2d is removed from a SOLID.
945       // CLEAN was not called at event REMOVE_ALGO because the algo is not applicable to SOLID.
946       algo = dynamic_cast<SMESH_Algo*> (anHyp);
947       if (!algo->NeedDiscreteBoundary())
948         algoRequiringCleaning = algo;
949       algo = GetAlgo();
950       if (algo == NULL)  // no more applying algo on father
951       {
952         setAlgoState(NO_ALGO);
953       }
954       else
955       {
956         if ( algo->CheckHypothesis((*_father),_subShape, aux_ret )) {
957           // check if algo changes
958           if ( string(algo->GetName()) != string( anHyp->GetName()) )
959             modifiedHyp = true;
960         }
961         else
962           setAlgoState(MISSING_HYP);
963       }
964       break;
965     }
966     default:
967       ASSERT(0);
968       break;
969     }
970     break;
971
972     // ----------------------------------------------------------------------
973
974   default:
975     ASSERT(0);
976     break;
977   }
978
979   // detect algorithm hiding
980   //
981   if ( ret == SMESH_Hypothesis::HYP_OK && 
982        ( event == ADD_ALGO || event == ADD_FATHER_ALGO ) && algo && 
983        algo->GetName() == anHyp->GetName() )
984   {
985     // is algo hidden?
986     SMESH_Gen* gen = _father->GetGen();
987     const std::vector< SMESH_subMesh * > & ancestors = GetAncestors();
988     for ( size_t iA = 0; ( ret == SMESH_Hypothesis::HYP_OK && iA < ancestors.size()); ++iA ) {
989       if ( SMESH_Algo* upperAlgo = ancestors[ iA ]->GetAlgo() )
990         if ( !upperAlgo->NeedDiscreteBoundary() && !upperAlgo->SupportSubmeshes())
991           ret = SMESH_Hypothesis::HYP_HIDDEN_ALGO;
992     }
993     // is algo hiding?
994     if ( ret == SMESH_Hypothesis::HYP_OK &&
995          !algo->NeedDiscreteBoundary()    &&
996          !algo->SupportSubmeshes())
997     {
998       TopoDS_Shape algoAssignedTo, otherAssignedTo;
999       gen->GetAlgo( this, &algoAssignedTo );
1000       map<int, SMESH_subMesh*>::reverse_iterator i_sm = _mapDepend.rbegin();
1001       for ( ; ( ret == SMESH_Hypothesis::HYP_OK && i_sm != _mapDepend.rend()) ; ++i_sm )
1002         if ( gen->GetAlgo( i_sm->second, &otherAssignedTo ) &&
1003              SMESH_MesherHelper::IsSubShape( /*sub=*/otherAssignedTo, /*main=*/algoAssignedTo ))
1004           ret = SMESH_Hypothesis::HYP_HIDING_ALGO;
1005     }
1006   }
1007
1008   if ( _algo ) { // get an error description set by _algo->CheckHypothesis()
1009     _computeError = _algo->GetComputeError();
1010     _algo->InitComputeError();
1011   }
1012
1013   bool stateChange = ( _algoState != oldAlgoState );
1014
1015   if ( stateChange && _algoState == HYP_OK ) // hyp becomes OK
1016     algo->SetEventListener( this );
1017
1018   if ( event == REMOVE_ALGO || event == REMOVE_FATHER_ALGO )
1019     _algo = 0;
1020
1021   notifyListenersOnEvent( event, ALGO_EVENT, anHyp );
1022
1023   if ( stateChange && oldAlgoState == HYP_OK ) { // hyp becomes KO
1024     deleteOwnListeners();
1025     SetIsAlwaysComputed( false );
1026     if (_subShape.ShapeType() == TopAbs_VERTEX ) {
1027       // restore default states
1028       _algoState = HYP_OK;
1029       _computeState = READY_TO_COMPUTE;
1030     }
1031   }
1032
1033   if ( algoRequiringCleaning ) {
1034     // added or removed algo is all-dimensional
1035     ComputeStateEngine( CLEAN );
1036     cleanDependsOn( algoRequiringCleaning );
1037     ComputeSubMeshStateEngine( CHECK_COMPUTE_STATE );
1038   }
1039
1040   if ( stateChange || modifiedHyp )
1041     ComputeStateEngine( MODIF_ALGO_STATE );
1042
1043   _realComputeCost = ( _algoState == HYP_OK ) ? computeCost() : 0;
1044
1045   return ret;
1046 }
1047
1048 //=======================================================================
1049 //function : IsConform
1050 //purpose  : check if a conform mesh will be produced by the Algo
1051 //=======================================================================
1052
1053 bool SMESH_subMesh::IsConform(const SMESH_Algo* theAlgo)
1054 {
1055 //  MESSAGE( "SMESH_subMesh::IsConform" );
1056   if ( !theAlgo ) return false;
1057
1058   // Suppose that theAlgo is applicable to _subShape, do not check it here
1059   //if ( !IsApplicableHypotesis( theAlgo )) return false;
1060
1061   // check only algo that doesn't NeedDiscreteBoundary(): because mesh made
1062   // on a sub-shape will be ignored by theAlgo
1063   if ( theAlgo->NeedDiscreteBoundary() ||
1064        !theAlgo->OnlyUnaryInput() ) // all adjacent shapes will be meshed by this algo?
1065     return true;
1066
1067   // only local algo is to be checked
1068   //if ( gen->IsGlobalHypothesis( theAlgo, *_father ))
1069   if ( _subShape.ShapeType() == _father->GetMeshDS()->ShapeToMesh().ShapeType() )
1070     return true;
1071
1072   // check algo attached to adjacent shapes
1073
1074   // loop on one level down sub-meshes
1075   TopoDS_Iterator itsub( _subShape );
1076   for (; itsub.More(); itsub.Next())
1077   {
1078     // loop on adjacent subShapes
1079     const std::vector< SMESH_subMesh * > & ancestors = GetAncestors();
1080     for ( size_t iA = 0; iA < ancestors.size(); ++iA )
1081     {
1082       const TopoDS_Shape& adjacent = ancestors[ iA ]->GetSubShape();
1083       if ( _subShape.IsSame( adjacent )) continue;
1084       if ( adjacent.ShapeType() != _subShape.ShapeType())
1085         break;
1086
1087       // check algo attached to smAdjacent
1088       SMESH_Algo * algo = ancestors[ iA ]->GetAlgo();
1089       if (algo &&
1090           !algo->NeedDiscreteBoundary() &&
1091           algo->OnlyUnaryInput())
1092         return false; // NOT CONFORM MESH WILL BE PRODUCED
1093     }
1094   }
1095
1096   return true;
1097 }
1098
1099 //=============================================================================
1100 /*!
1101  *
1102  */
1103 //=============================================================================
1104
1105 void SMESH_subMesh::setAlgoState(algo_state state)
1106 {
1107   _algoState = state;
1108 }
1109
1110 //================================================================================
1111 /*!
1112  * \brief Send an event to sub-meshes
1113  *  \param [in] event - the event
1114  *  \param [in] anHyp - an hypothesis
1115  *  \param [in] exitOnFatal - to stop iteration on sub-meshes if a sub-mesh
1116  *              reports a fatal result
1117  *  \return SMESH_Hypothesis::Hypothesis_Status - the worst result
1118  *
1119  * Optional description of a problematic situation (if any) can be retrieved
1120  * via GetComputeError().
1121  */
1122 //================================================================================
1123
1124 SMESH_Hypothesis::Hypothesis_Status
1125   SMESH_subMesh::SubMeshesAlgoStateEngine(algo_event         event,
1126                                           SMESH_Hypothesis * anHyp,
1127                                           bool               exitOnFatal)
1128 {
1129   SMESH_Hypothesis::Hypothesis_Status ret = SMESH_Hypothesis::HYP_OK;
1130   //EAP: a wire (dim==1) should notify edges (dim==1)
1131   //EAP: int dim = SMESH_Gen::GetShapeDim(_subShape);
1132   //if (_subShape.ShapeType() < TopAbs_EDGE ) // wire,face etc
1133   {
1134     SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,false);
1135     while ( smIt->more() ) {
1136       SMESH_subMesh* sm = smIt->next();
1137       SMESH_Hypothesis::Hypothesis_Status ret2 = sm->AlgoStateEngine(event, anHyp);
1138       if ( ret2 > ret )
1139       {
1140         ret = ret2;
1141         _computeError = sm->_computeError;
1142         sm->_computeError.reset();
1143         if ( exitOnFatal && SMESH_Hypothesis::IsStatusFatal( ret ))
1144           break;
1145       }
1146     }
1147   }
1148   return ret;
1149 }
1150
1151 //================================================================================
1152 /*!
1153  * \brief Remove elements from sub-meshes.
1154  *  \param algoRequiringCleaning - an all-dimensional algorithm whose presence
1155  *         causes the cleaning.
1156  */
1157 //================================================================================
1158
1159 void SMESH_subMesh::cleanDependsOn( SMESH_Algo* algoRequiringCleaning/*=0*/ )
1160 {
1161   SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,
1162                                                        /*complexShapeFirst=*/true);
1163   if ( _father->NbNodes() == 0 )
1164   {
1165     while ( smIt->more() )
1166       smIt->next()->ComputeStateEngine(CHECK_COMPUTE_STATE);
1167   }
1168   else if ( !algoRequiringCleaning || !algoRequiringCleaning->SupportSubmeshes() )
1169   {
1170     while ( smIt->more() )
1171       smIt->next()->ComputeStateEngine(CLEAN);
1172   }
1173   else if ( algoRequiringCleaning && algoRequiringCleaning->SupportSubmeshes() )
1174   {
1175     // find sub-meshes to keep elements on
1176     set< SMESH_subMesh* > smToKeep;
1177     TopAbs_ShapeEnum prevShapeType = TopAbs_SHAPE;
1178     bool toKeepPrevShapeType = false;
1179     while ( smIt->more() )
1180     {
1181       SMESH_subMesh* sm = smIt->next();
1182       sm->ComputeStateEngine(CHECK_COMPUTE_STATE);
1183       if ( !sm->IsEmpty() )
1184       {
1185         const bool sameShapeType = ( prevShapeType == sm->GetSubShape().ShapeType() );
1186         bool       keepSubMeshes = ( sameShapeType && toKeepPrevShapeType );
1187         if ( !sameShapeType )
1188         {
1189           // check if the algo allows presence of global algos of dimension the algo
1190           // can generate it-self;
1191           // always keep a node on VERTEX, as this node can be shared by segments
1192           // lying on EDGEs not shared by the VERTEX of sm, due to MergeNodes (PAL23068)
1193           int  shapeDim = SMESH_Gen::GetShapeDim( sm->GetSubShape() );
1194           keepSubMeshes = ( algoRequiringCleaning->NeedLowerHyps( shapeDim ) || shapeDim == 0 );
1195           prevShapeType = sm->GetSubShape().ShapeType();
1196           toKeepPrevShapeType = keepSubMeshes;
1197         }
1198         if ( !keepSubMeshes )
1199         {
1200           // look for a local algo used to mesh sm
1201           TopoDS_Shape algoShape = SMESH_MesherHelper::GetShapeOfHypothesis
1202             ( algoRequiringCleaning, _subShape, _father );
1203           SMESH_HypoFilter moreLocalAlgo;
1204           moreLocalAlgo.Init( SMESH_HypoFilter::IsMoreLocalThan( algoShape, *_father ));
1205           moreLocalAlgo.And ( SMESH_HypoFilter::IsAlgo() );
1206           bool localAlgoFound = _father->GetHypothesis( sm->_subShape, moreLocalAlgo, true );
1207           keepSubMeshes = localAlgoFound;
1208         }
1209         // remember all sub-meshes of sm
1210         if ( keepSubMeshes )
1211         {
1212           SMESH_subMeshIteratorPtr smIt2 = sm->getDependsOnIterator(true);
1213           while ( smIt2->more() )
1214             smToKeep.insert( smIt2->next() );
1215         }
1216       }
1217     }
1218     // remove elements
1219     SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,true);
1220     while ( smIt->more() )
1221     {
1222       SMESH_subMesh* sm = smIt->next();
1223       if ( !smToKeep.count( sm ))
1224         sm->ComputeStateEngine(CLEAN);
1225     }
1226   }
1227 }
1228
1229 //=============================================================================
1230 /*!
1231  *
1232  */
1233 //=============================================================================
1234
1235 void SMESH_subMesh::DumpAlgoState(bool isMain)
1236 {
1237   if (isMain)
1238   {
1239     const map < int, SMESH_subMesh * >&subMeshes = DependsOn();
1240
1241     map < int, SMESH_subMesh * >::const_iterator itsub;
1242     for (itsub = subMeshes.begin(); itsub != subMeshes.end(); itsub++)
1243     {
1244       SMESH_subMesh *sm = (*itsub).second;
1245       sm->DumpAlgoState(false);
1246     }
1247   }
1248   MESSAGE("dim = " << SMESH_Gen::GetShapeDim(_subShape) <<
1249           " type of shape " << _subShape.ShapeType());
1250   switch (_algoState)
1251   {
1252   case NO_ALGO          : MESSAGE(" AlgoState = NO_ALGO"); break;
1253   case MISSING_HYP      : MESSAGE(" AlgoState = MISSING_HYP"); break;
1254   case HYP_OK           : MESSAGE(" AlgoState = HYP_OK");break;
1255   }
1256   switch (_computeState)
1257   {
1258   case NOT_READY        : MESSAGE(" ComputeState = NOT_READY");break;
1259   case READY_TO_COMPUTE : MESSAGE(" ComputeState = READY_TO_COMPUTE");break;
1260   case COMPUTE_OK       : MESSAGE(" ComputeState = COMPUTE_OK");break;
1261   case FAILED_TO_COMPUTE: MESSAGE(" ComputeState = FAILED_TO_COMPUTE");break;
1262   }
1263 }
1264
1265 //================================================================================
1266 /*!
1267  * \brief Remove nodes and elements bound to submesh
1268   * \param subMesh - submesh containing nodes and elements
1269  */
1270 //================================================================================
1271
1272 static void cleanSubMesh( SMESH_subMesh * subMesh )
1273 {
1274   if (subMesh) {
1275     if (SMESHDS_SubMesh * subMeshDS = subMesh->GetSubMeshDS())
1276     {
1277       SMESHDS_Mesh * meshDS = subMesh->GetFather()->GetMeshDS();
1278       int nbElems = subMeshDS->NbElements();
1279       if ( nbElems > 0 )
1280       {
1281         // start from elem with max ID to avoid filling the pool of IDs
1282         const SMDS_MeshElement * lastElem = subMeshDS->GetElement( nbElems-1 );
1283         bool rev = ( lastElem->GetID() == meshDS->MaxElementID() );
1284         SMDS_ElemIteratorPtr ite = subMeshDS->GetElements( rev );
1285         while (ite->more()) {
1286           const SMDS_MeshElement * elt = ite->next();
1287           meshDS->RemoveFreeElement(elt, 0);
1288         }
1289       }
1290       int nbNodes = subMeshDS->NbNodes();
1291       if ( nbNodes > 0 )
1292       {
1293         const SMDS_MeshNode * lastNode = subMeshDS->GetNode( nbNodes-1 );
1294         bool rev = ( lastNode->GetID() == meshDS->MaxNodeID() );
1295         SMDS_NodeIteratorPtr itn = subMeshDS->GetNodes( rev );
1296         while (itn->more()) {
1297           const SMDS_MeshNode * node = itn->next();
1298           if ( node->NbInverseElements() == 0 )
1299             meshDS->RemoveFreeNode(node, 0);
1300           else // for StdMeshers_CompositeSegment_1D: node in one submesh, edge in another
1301             meshDS->RemoveNode(node);
1302         }
1303       }
1304       subMeshDS->Clear();
1305     }
1306   }
1307 }
1308
1309 //=============================================================================
1310 /*!
1311  *
1312  */
1313 //=============================================================================
1314
1315 bool SMESH_subMesh::ComputeStateEngine(compute_event event)
1316 {
1317   switch ( event ) {
1318   case MODIF_ALGO_STATE:
1319   case COMPUTE:
1320   case COMPUTE_SUBMESH:
1321     //case COMPUTE_CANCELED:
1322   case CLEAN:
1323     //case SUBMESH_COMPUTED:
1324     //case SUBMESH_RESTORED:
1325     //case SUBMESH_LOADED:
1326     //case MESH_ENTITY_REMOVED:
1327     //case CHECK_COMPUTE_STATE:
1328     _computeError.reset(); break;
1329   default:;
1330   }
1331
1332   if ( event == CLEAN )
1333     _alwaysComputed = false; // Unset 'true' set by MergeNodes() (issue 0022182)
1334
1335   if (_subShape.ShapeType() == TopAbs_VERTEX)
1336   {
1337     _computeState = READY_TO_COMPUTE;
1338     SMESHDS_SubMesh* smDS = GetSubMeshDS();
1339     if ( smDS && smDS->NbNodes() )
1340     {
1341       if ( event == CLEAN ) {
1342         cleanDependants();
1343         cleanSubMesh( this );
1344       }
1345       else
1346         _computeState = COMPUTE_OK;
1347     }
1348     else if (( event == COMPUTE || event == COMPUTE_SUBMESH )
1349              && !_alwaysComputed )
1350     {
1351       const TopoDS_Vertex & V = TopoDS::Vertex( _subShape );
1352       gp_Pnt P = BRep_Tool::Pnt(V);
1353       if ( SMDS_MeshNode * n = _father->GetMeshDS()->AddNode(P.X(), P.Y(), P.Z()) ) {
1354         _father->GetMeshDS()->SetNodeOnVertex(n,_Id);
1355         _computeState = COMPUTE_OK;
1356       }
1357     }
1358     if ( event == MODIF_ALGO_STATE )
1359       cleanDependants();
1360     return true;
1361   }
1362   SMESH_Gen *gen = _father->GetGen();
1363   SMESH_Algo *algo = 0;
1364   bool ret = true;
1365   SMESH_Hypothesis::Hypothesis_Status hyp_status;
1366   //algo_state oldAlgoState = (algo_state) GetAlgoState();
1367
1368   switch (_computeState)
1369   {
1370
1371     // ----------------------------------------------------------------------
1372
1373   case NOT_READY:
1374     switch (event)
1375     {
1376     case MODIF_ALGO_STATE:
1377       algo = GetAlgo();
1378       if (algo && !algo->NeedDiscreteBoundary())
1379         cleanDependsOn( algo ); // clean sub-meshes with event CLEAN
1380       if ( _algoState == HYP_OK )
1381         _computeState = READY_TO_COMPUTE;
1382       break;
1383     case COMPUTE:               // nothing to do
1384     case COMPUTE_SUBMESH:
1385       break;
1386     case COMPUTE_CANCELED:      // nothing to do
1387       break;
1388     case CLEAN:
1389       cleanDependants();
1390       removeSubMeshElementsAndNodes();
1391       break;
1392     case SUBMESH_COMPUTED:      // nothing to do
1393       break;
1394     case SUBMESH_RESTORED:
1395       ComputeSubMeshStateEngine( SUBMESH_RESTORED );
1396       break;
1397     case MESH_ENTITY_REMOVED:
1398       break;
1399     case SUBMESH_LOADED:
1400       loadDependentMeshes();
1401       ComputeSubMeshStateEngine( SUBMESH_LOADED );
1402       //break;
1403     case CHECK_COMPUTE_STATE:
1404       if ( IsMeshComputed() )
1405         _computeState = COMPUTE_OK;
1406       break;
1407     default:
1408       ASSERT(0);
1409       break;
1410     }
1411     break;
1412
1413     // ----------------------------------------------------------------------
1414
1415   case READY_TO_COMPUTE:
1416     switch (event)
1417     {
1418     case MODIF_ALGO_STATE:
1419       _computeState = NOT_READY;
1420       algo = GetAlgo();
1421       if (algo)
1422       {
1423         if (!algo->NeedDiscreteBoundary())
1424           cleanDependsOn( algo ); // clean sub-meshes with event CLEAN
1425         if ( _algoState == HYP_OK )
1426           _computeState = READY_TO_COMPUTE;
1427       }
1428       break;
1429     case COMPUTE:
1430     case COMPUTE_SUBMESH:
1431       {
1432         algo = GetAlgo();
1433         ASSERT(algo);
1434         ret = algo->CheckHypothesis((*_father), _subShape, hyp_status);
1435         if (!ret)
1436         {
1437           MESSAGE("***** verify compute state *****");
1438           _computeState = NOT_READY;
1439           setAlgoState(MISSING_HYP);
1440           break;
1441         }
1442         TopoDS_Shape shape = _subShape;
1443         algo->SubMeshesToCompute().assign( 1, this );
1444         // check submeshes needed
1445         if (_father->HasShapeToMesh() ) {
1446           bool subComputed = false, subFailed = false;
1447           if (!algo->OnlyUnaryInput()) {
1448             if ( event == COMPUTE /*&&
1449                  ( algo->NeedDiscreteBoundary() || algo->SupportSubmeshes() )*/)
1450               shape = getCollection( gen, algo, subComputed, subFailed, algo->SubMeshesToCompute());
1451             else
1452               subComputed = SubMeshesComputed( & subFailed );
1453           }
1454           else {
1455             subComputed = SubMeshesComputed();
1456           }
1457           ret = ( algo->NeedDiscreteBoundary() ? subComputed :
1458                   algo->SupportSubmeshes() ? !subFailed :
1459                   ( !subComputed || _father->IsNotConformAllowed() ));
1460           if (!ret)
1461           {
1462             _computeState = FAILED_TO_COMPUTE;
1463             if ( !algo->NeedDiscreteBoundary() && !subFailed )
1464               _computeError =
1465                 SMESH_ComputeError::New(COMPERR_BAD_INPUT_MESH,
1466                                         "Unexpected computed sub-mesh",algo);
1467             break; // goto exit
1468           }
1469         }
1470         // Compute
1471
1472         // to restore cout that may be redirected by algo
1473         std::streambuf* coutBuffer = std::cout.rdbuf();
1474
1475         //cleanDependants(); for "UseExisting_*D" algos
1476         //removeSubMeshElementsAndNodes();
1477         loadDependentMeshes();
1478         ret = false;
1479         _computeState = FAILED_TO_COMPUTE;
1480         _computeError = SMESH_ComputeError::New(COMPERR_OK,"",algo);
1481         try {
1482           OCC_CATCH_SIGNALS;
1483
1484           algo->InitComputeError();
1485
1486           MemoryReserve aMemoryReserve;
1487           SMDS_Mesh::CheckMemory();
1488           Kernel_Utils::Localizer loc;
1489           if ( !_father->HasShapeToMesh() ) // no shape
1490           {
1491             SMESH_MesherHelper helper( *_father );
1492             helper.SetSubShape( shape );
1493             helper.SetElementsOnShape( true );
1494             ret = algo->Compute(*_father, &helper );
1495           }
1496           else
1497           {
1498             ret = algo->Compute((*_father), shape);
1499           }
1500           // algo can set _computeError of submesh
1501           _computeError = SMESH_ComputeError::Worst( _computeError, algo->GetComputeError() );
1502         }
1503         catch ( ::SMESH_ComputeError& comperr ) {
1504           cout << " SMESH_ComputeError caught" << endl;
1505           if ( !_computeError ) _computeError = SMESH_ComputeError::New();
1506           *_computeError = comperr;
1507         }
1508         catch ( std::bad_alloc& exc ) {
1509           MESSAGE("std::bad_alloc thrown inside algo->Compute()");
1510           if ( _computeError ) {
1511             _computeError->myName = COMPERR_MEMORY_PB;
1512           }
1513           cleanSubMesh( this );
1514           throw exc;
1515         }
1516         catch ( Standard_OutOfMemory& exc ) {
1517           MESSAGE("Standard_OutOfMemory thrown inside algo->Compute()");
1518           if ( _computeError ) {
1519             _computeError->myName = COMPERR_MEMORY_PB;
1520           }
1521           cleanSubMesh( this );
1522           throw std::bad_alloc();
1523         }
1524         catch (Standard_Failure& ex) {
1525           if ( !_computeError ) _computeError = SMESH_ComputeError::New();
1526           _computeError->myName    = COMPERR_OCC_EXCEPTION;
1527           _computeError->myComment += ex.DynamicType()->Name();
1528           if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
1529             _computeError->myComment += ": ";
1530             _computeError->myComment += ex.GetMessageString();
1531           }
1532         }
1533         catch ( SALOME_Exception& S_ex ) {
1534           const int skipSalomeShift = 7; /* to skip "Salome " of
1535                                             "Salome Exception" prefix returned
1536                                             by SALOME_Exception::what() */
1537           if ( !_computeError ) _computeError = SMESH_ComputeError::New();
1538           _computeError->myName    = COMPERR_SLM_EXCEPTION;
1539           _computeError->myComment = S_ex.what() + skipSalomeShift;
1540         }
1541         catch ( std::exception& exc ) {
1542           if ( !_computeError ) _computeError = SMESH_ComputeError::New();
1543           _computeError->myName    = COMPERR_STD_EXCEPTION;
1544           _computeError->myComment = exc.what();
1545         }
1546         catch ( ... ) {
1547           if ( _computeError )
1548             _computeError->myName = COMPERR_EXCEPTION;
1549           else
1550             ret = false;
1551         }
1552         std::cout.rdbuf( coutBuffer ); // restore cout that could be redirected by algo
1553
1554         // check if an error reported on any sub-shape
1555         bool isComputeErrorSet = !checkComputeError( algo, ret, shape );
1556         if ( isComputeErrorSet )
1557           ret = false;
1558         // check if anything was built
1559         TopExp_Explorer subS(shape, _subShape.ShapeType());
1560         if ( ret )
1561         {
1562           for (; ret && subS.More(); subS.Next())
1563             if ( !_father->GetSubMesh( subS.Current() )->IsMeshComputed() &&
1564                  ( _subShape.ShapeType() != TopAbs_EDGE ||
1565                    !algo->isDegenerated( TopoDS::Edge( subS.Current() ))))
1566               ret = false;
1567         }
1568         // Set _computeError
1569         if ( !ret && !isComputeErrorSet )
1570         {
1571           for ( subS.ReInit(); subS.More(); subS.Next() )
1572           {
1573             SMESH_subMesh* sm = _father->GetSubMesh( subS.Current() );
1574             if ( !sm->IsMeshComputed() )
1575             {
1576               if ( !sm->_computeError )
1577                 sm->_computeError = SMESH_ComputeError::New();
1578               if ( sm->_computeError->IsOK() )
1579                 sm->_computeError->myName = COMPERR_ALGO_FAILED;
1580               sm->_computeState = FAILED_TO_COMPUTE;
1581               sm->_computeError->myAlgo = algo;
1582             }
1583           }
1584         }
1585         if ( ret && _computeError && _computeError->myName != COMPERR_WARNING )
1586         {
1587           _computeError.reset();
1588         }
1589
1590         // transform errors into warnings if it is caused by mesh edition (imp 0023068)
1591         if (!ret && _father->GetIsModified() )
1592         {
1593           for (subS.ReInit(); subS.More(); subS.Next())
1594           {
1595             SMESH_subMesh* sm = _father->GetSubMesh( subS.Current() );
1596             if ( !sm->IsMeshComputed() && sm->_computeError )
1597             {
1598               // check if there is a VERTEX w/o nodes
1599               // with READY_TO_COMPUTE state (after MergeNodes())
1600               SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(false,false);
1601               while ( smIt->more() )
1602               {
1603                 SMESH_subMesh * vertSM = smIt->next();
1604                 if ( vertSM->_subShape.ShapeType() != TopAbs_VERTEX ) break;
1605                 if ( vertSM->GetComputeState() == READY_TO_COMPUTE )
1606                 {
1607                   SMESHDS_SubMesh * ds = vertSM->GetSubMeshDS();
1608                   if ( !ds || ds->NbNodes() == 0 )
1609                   {
1610                     sm->_computeState = READY_TO_COMPUTE;
1611                     sm->_computeError->myName = COMPERR_WARNING;
1612                     break;
1613                   }
1614                 }
1615               }
1616             }
1617           }
1618         }
1619
1620         // send event SUBMESH_COMPUTED
1621         if ( ret ) {
1622           if ( !algo->NeedDiscreteBoundary() )
1623             // send SUBMESH_COMPUTED to dependants of all sub-meshes of shape
1624             for (subS.ReInit(); subS.More(); subS.Next())
1625             {
1626               SMESH_subMesh* sm = _father->GetSubMesh( subS.Current() );
1627               SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(false,false);
1628               while ( smIt->more() ) {
1629                 sm = smIt->next();
1630                 if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1631                   sm->updateDependantsState( SUBMESH_COMPUTED );
1632                 else
1633                   break;
1634               }
1635             }
1636           else
1637             updateDependantsState( SUBMESH_COMPUTED );
1638         }
1639       }
1640       break;
1641     case COMPUTE_CANCELED:               // nothing to do
1642       break;
1643     case CLEAN:
1644       cleanDependants();
1645       removeSubMeshElementsAndNodes();
1646       _computeState = NOT_READY;
1647       algo = GetAlgo();
1648       if (algo)
1649       {
1650         ret = algo->CheckHypothesis((*_father), _subShape, hyp_status);
1651         if (ret)
1652           _computeState = READY_TO_COMPUTE;
1653         else
1654           setAlgoState(MISSING_HYP);
1655       }
1656       break;
1657     case SUBMESH_COMPUTED:      // nothing to do
1658       break;
1659     case SUBMESH_RESTORED:
1660       // check if a mesh is already computed that may
1661       // happen after retrieval from a file
1662       ComputeStateEngine( CHECK_COMPUTE_STATE );
1663       ComputeSubMeshStateEngine( SUBMESH_RESTORED );
1664       algo = GetAlgo();
1665       if (algo) algo->SubmeshRestored( this );
1666       break;
1667     case MESH_ENTITY_REMOVED:
1668       break;
1669     case SUBMESH_LOADED:
1670       loadDependentMeshes();
1671       ComputeSubMeshStateEngine( SUBMESH_LOADED );
1672       //break;
1673     case CHECK_COMPUTE_STATE:
1674       if ( IsMeshComputed() )
1675         _computeState = COMPUTE_OK;
1676       else if ( _computeError && _computeError->IsKO() )
1677         _computeState = FAILED_TO_COMPUTE;
1678       break;
1679     default:
1680       ASSERT(0);
1681       break;
1682     }
1683     break;
1684
1685     // ----------------------------------------------------------------------
1686
1687   case COMPUTE_OK:
1688     switch (event)
1689     {
1690     case MODIF_ALGO_STATE:
1691       ComputeStateEngine( CLEAN );
1692       algo = GetAlgo();
1693       if (algo && !algo->NeedDiscreteBoundary())
1694         cleanDependsOn( algo ); // clean sub-meshes with event CLEAN
1695       break;
1696     case COMPUTE:               // nothing to do
1697       break;
1698     case COMPUTE_CANCELED:      // nothing to do
1699       break;
1700     case CLEAN:
1701       cleanDependants();  // clean sub-meshes, dependant on this one, with event CLEAN
1702       removeSubMeshElementsAndNodes();
1703       _computeState = NOT_READY;
1704       if ( _algoState == HYP_OK )
1705         _computeState = READY_TO_COMPUTE;
1706       break;
1707     case SUBMESH_COMPUTED:      // nothing to do
1708       break;
1709     case SUBMESH_RESTORED:
1710       ComputeStateEngine( CHECK_COMPUTE_STATE );
1711       ComputeSubMeshStateEngine( SUBMESH_RESTORED );
1712       algo = GetAlgo();
1713       if (algo) algo->SubmeshRestored( this );
1714       break;
1715     case MESH_ENTITY_REMOVED:
1716       updateDependantsState    ( CHECK_COMPUTE_STATE );
1717       ComputeStateEngine       ( CHECK_COMPUTE_STATE );
1718       ComputeSubMeshStateEngine( CHECK_COMPUTE_STATE );
1719       break;
1720     case CHECK_COMPUTE_STATE:
1721       if ( !IsMeshComputed() ) {
1722         if (_algoState == HYP_OK)
1723           _computeState = READY_TO_COMPUTE;
1724         else
1725           _computeState = NOT_READY;
1726       }
1727       break;
1728     case SUBMESH_LOADED:
1729       // already treated event, thanks to which _computeState == COMPUTE_OK
1730       break;
1731     default:
1732       ASSERT(0);
1733       break;
1734     }
1735     break;
1736
1737     // ----------------------------------------------------------------------
1738
1739   case FAILED_TO_COMPUTE:
1740     switch (event)
1741     {
1742     case MODIF_ALGO_STATE:
1743       if ( !IsEmpty() )
1744         ComputeStateEngine( CLEAN );
1745       algo = GetAlgo();
1746       if (algo && !algo->NeedDiscreteBoundary())
1747         cleanDependsOn( algo ); // clean sub-meshes with event CLEAN
1748       if (_algoState == HYP_OK)
1749         _computeState = READY_TO_COMPUTE;
1750       else
1751         _computeState = NOT_READY;
1752       break;
1753     case COMPUTE:        // nothing to do
1754     case COMPUTE_SUBMESH:
1755       break;
1756     case COMPUTE_CANCELED:
1757       {
1758         algo = GetAlgo();
1759         algo->CancelCompute();
1760       }
1761       break;
1762     case CLEAN:
1763       cleanDependants(); // submeshes dependent on me should be cleaned as well
1764       removeSubMeshElementsAndNodes();
1765       break;
1766     case SUBMESH_COMPUTED:      // allow retry compute
1767       if ( IsEmpty() ) // 23061
1768       {
1769         if (_algoState == HYP_OK)
1770           _computeState = READY_TO_COMPUTE;
1771         else
1772           _computeState = NOT_READY;
1773       }
1774       break;
1775     case SUBMESH_RESTORED:
1776       ComputeSubMeshStateEngine( SUBMESH_RESTORED );
1777       break;
1778     case MESH_ENTITY_REMOVED:
1779       break;
1780     case CHECK_COMPUTE_STATE:
1781       if ( IsMeshComputed() )
1782         _computeState = COMPUTE_OK;
1783       else
1784         if (_algoState == HYP_OK)
1785           _computeState = READY_TO_COMPUTE;
1786         else
1787           _computeState = NOT_READY;
1788       break;
1789     // case SUBMESH_LOADED:
1790     //   break;
1791     default:
1792       ASSERT(0);
1793       break;
1794     }
1795     break;
1796
1797     // ----------------------------------------------------------------------
1798   default:
1799     ASSERT(0);
1800     break;
1801   }
1802
1803   notifyListenersOnEvent( event, COMPUTE_EVENT );
1804
1805   return ret;
1806 }
1807
1808
1809 //=============================================================================
1810 /*!
1811  *
1812  */
1813 //=============================================================================
1814
1815 bool SMESH_subMesh::Evaluate(MapShapeNbElems& aResMap)
1816 {
1817   _computeError.reset();
1818
1819   bool ret = true;
1820
1821   if (_subShape.ShapeType() == TopAbs_VERTEX) {
1822     vector<int> aVec(SMDSEntity_Last,0);
1823     aVec[SMDSEntity_Node] = 1;
1824     aResMap.insert(make_pair(this,aVec));
1825     return ret;
1826   }
1827
1828   //SMESH_Gen *gen = _father->GetGen();
1829   SMESH_Algo *algo = 0;
1830   SMESH_Hypothesis::Hypothesis_Status hyp_status;
1831
1832   algo = GetAlgo();
1833   if( algo && !aResMap.count( this ))
1834   {
1835     ret = algo->CheckHypothesis((*_father), _subShape, hyp_status);
1836     if (!ret) return false;
1837
1838     if (_father->HasShapeToMesh() && algo->NeedDiscreteBoundary() )
1839     {
1840       // check submeshes needed
1841       bool subMeshEvaluated = true;
1842       int dimToCheck = SMESH_Gen::GetShapeDim( _subShape ) - 1;
1843       SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,/*complexShapeFirst=*/true);
1844       while ( smIt->more() && subMeshEvaluated )
1845       {
1846         SMESH_subMesh* sm = smIt->next();
1847         int dim = SMESH_Gen::GetShapeDim( sm->GetSubShape() );
1848         if (dim < dimToCheck) break; // the rest subMeshes are all of less dimension
1849         const vector<int> & nbs = aResMap[ sm ];
1850         subMeshEvaluated = (std::accumulate( nbs.begin(), nbs.end(), 0 ) > 0 );
1851       }
1852       if ( !subMeshEvaluated )
1853         return false;
1854     }
1855     _computeError = SMESH_ComputeError::New(COMPERR_OK,"",algo);
1856
1857     if ( IsMeshComputed() )
1858     {
1859       vector<int> & nbEntities = aResMap[ this ];
1860       nbEntities.resize( SMDSEntity_Last, 0 );
1861       if ( SMESHDS_SubMesh* sm = GetSubMeshDS() )
1862       {
1863         nbEntities[ SMDSEntity_Node ] = sm->NbNodes();
1864         SMDS_ElemIteratorPtr   elemIt = sm->GetElements();
1865         while ( elemIt->more() )
1866           nbEntities[ elemIt->next()->GetEntityType() ]++;
1867       }
1868     }
1869     else
1870     {
1871       ret = algo->Evaluate((*_father), _subShape, aResMap);
1872     }
1873     aResMap.insert( make_pair( this,vector<int>(0)));
1874   }
1875
1876   return ret;
1877 }
1878
1879
1880 //=======================================================================
1881 /*!
1882  * \brief Update compute_state by _computeError and send proper events to
1883  * dependent submeshes
1884   * \retval bool - true if _computeError is NOT set
1885  */
1886 //=======================================================================
1887
1888 bool SMESH_subMesh::checkComputeError(SMESH_Algo*         theAlgo,
1889                                       const bool          theComputeOK,
1890                                       const TopoDS_Shape& theShape)
1891 {
1892   bool noErrors = true;
1893
1894   if ( !theShape.IsNull() )
1895   {
1896     // Check state of submeshes
1897     if ( !theAlgo->NeedDiscreteBoundary())
1898     {
1899       SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,false);
1900       while ( smIt->more() )
1901         if ( !smIt->next()->checkComputeError( theAlgo, theComputeOK ))
1902           noErrors = false;
1903     }
1904
1905     // Check state of neighbours
1906     if ( !theAlgo->OnlyUnaryInput() &&
1907          theShape.ShapeType() == TopAbs_COMPOUND &&
1908          !theShape.IsSame( _subShape ))
1909     {
1910       for (TopoDS_Iterator subIt( theShape ); subIt.More(); subIt.Next()) {
1911         SMESH_subMesh* sm = _father->GetSubMesh( subIt.Value() );
1912         if ( sm != this ) {
1913           if ( !sm->checkComputeError( theAlgo, theComputeOK, sm->GetSubShape() ))
1914             noErrors = false;
1915           updateDependantsState( SUBMESH_COMPUTED ); // send event SUBMESH_COMPUTED
1916         }
1917       }
1918     }
1919   }
1920   {
1921
1922     // Set my _computeState
1923
1924     if ( !_computeError || _computeError->IsOK() )
1925     {
1926       // no error description is set to this sub-mesh, check if any mesh is computed
1927       _computeState = IsMeshComputed() ? COMPUTE_OK : FAILED_TO_COMPUTE;
1928       if ( _computeState != COMPUTE_OK )
1929       {
1930         if ( _subShape.ShapeType() == TopAbs_EDGE &&
1931              SMESH_Algo::isDegenerated( TopoDS::Edge( _subShape )) )
1932           _computeState = COMPUTE_OK;
1933         else if ( theComputeOK )
1934           _computeError = SMESH_ComputeError::New(COMPERR_NO_MESH_ON_SHAPE,"",theAlgo);
1935       }
1936     }
1937
1938     if ( _computeError && !_computeError->IsOK() )
1939     {
1940       if ( !_computeError->myAlgo )
1941         _computeError->myAlgo = theAlgo;
1942
1943       // Show error
1944       SMESH_Comment text;
1945       text << theAlgo->GetName() << " failed on sub-shape #" << _Id << " with error ";
1946       if (_computeError->IsCommon() )
1947         text << _computeError->CommonName();
1948       else
1949         text << _computeError->myName;
1950       if ( _computeError->myComment.size() > 0 )
1951         text << " \"" << _computeError->myComment << "\"";
1952
1953       INFOS( text );
1954
1955       _computeState = _computeError->IsKO() ? FAILED_TO_COMPUTE : COMPUTE_OK;
1956
1957       noErrors = false;
1958     }
1959   }
1960   return noErrors;
1961 }
1962
1963 //=======================================================================
1964 //function : updateSubMeshState
1965 //purpose  :
1966 //=======================================================================
1967
1968 void SMESH_subMesh::updateSubMeshState(const compute_state theState)
1969 {
1970   SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,false);
1971   while ( smIt->more() )
1972     smIt->next()->_computeState = theState;
1973 }
1974
1975 //=======================================================================
1976 //function : ComputeSubMeshStateEngine
1977 //purpose  :
1978 //=======================================================================
1979
1980 void SMESH_subMesh::ComputeSubMeshStateEngine(compute_event event, const bool includeSelf)
1981 {
1982   SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(includeSelf,false);
1983   while ( smIt->more() )
1984     smIt->next()->ComputeStateEngine(event);
1985 }
1986
1987 //=======================================================================
1988 //function : updateDependantsState
1989 //purpose  :
1990 //=======================================================================
1991
1992 void SMESH_subMesh::updateDependantsState(const compute_event theEvent)
1993 {
1994   const std::vector< SMESH_subMesh * > & ancestors = GetAncestors();
1995   for ( size_t iA = 0; iA < ancestors.size(); ++iA )
1996   {
1997     ancestors[ iA ]->ComputeStateEngine( theEvent );
1998   }
1999 }
2000
2001 //=======================================================================
2002 //function : cleanDependants
2003 //purpose  : 
2004 //=======================================================================
2005
2006 void SMESH_subMesh::cleanDependants()
2007 {
2008   int dimToClean = SMESH_Gen::GetShapeDim( _subShape ) + 1;
2009
2010   const std::vector< SMESH_subMesh * > & ancestors = GetAncestors();
2011   for ( size_t iA = 0; iA < ancestors.size(); ++iA )
2012   {
2013     const TopoDS_Shape& ancestor = ancestors[ iA ]->GetSubShape();
2014     if ( SMESH_Gen::GetShapeDim( ancestor ) == dimToClean )
2015     {
2016       // PAL8021. do not go upper than SOLID, else ComputeStateEngine(CLEAN)
2017       // will erase mesh on other shapes in a compound
2018       if ( ancestor.ShapeType() >= TopAbs_SOLID &&
2019            !ancestors[ iA ]->IsEmpty() )  // prevent infinite CLEAN via event lesteners
2020         ancestors[ iA ]->ComputeStateEngine(CLEAN);
2021     }
2022   }
2023 }
2024
2025 //=======================================================================
2026 //function : removeSubMeshElementsAndNodes
2027 //purpose  : 
2028 //=======================================================================
2029
2030 void SMESH_subMesh::removeSubMeshElementsAndNodes()
2031 {
2032   cleanSubMesh( this );
2033
2034   // algo may bind a submesh not to _subShape, eg 3D algo
2035   // sets nodes on SHELL while _subShape may be SOLID
2036
2037   int dim = SMESH_Gen::GetShapeDim( _subShape );
2038   int type = _subShape.ShapeType() + 1;
2039   for ( ; type <= TopAbs_EDGE; type++) {
2040     if ( dim == SMESH_Gen::GetShapeDim( (TopAbs_ShapeEnum) type ))
2041     {
2042       TopExp_Explorer exp( _subShape, (TopAbs_ShapeEnum) type );
2043       for ( ; exp.More(); exp.Next() )
2044         cleanSubMesh( _father->GetSubMeshContaining( exp.Current() ));
2045     }
2046     else
2047       break;
2048   }
2049 }
2050
2051 //=======================================================================
2052 //function : getCollection
2053 //purpose  : return a shape containing all sub-shapes of the MainShape that can be
2054 //           meshed at once along with _subShape
2055 //=======================================================================
2056
2057 TopoDS_Shape SMESH_subMesh::getCollection(SMESH_Gen * theGen,
2058                                           SMESH_Algo* theAlgo,
2059                                           bool &      theSubComputed,
2060                                           bool &      theSubFailed,
2061                                           std::vector<SMESH_subMesh*>& theSubs)
2062 {
2063   theSubComputed = SubMeshesComputed( & theSubFailed );
2064
2065   TopoDS_Shape mainShape = _father->GetMeshDS()->ShapeToMesh();
2066
2067   if ( mainShape.IsSame( _subShape ))
2068     return _subShape;
2069
2070   const bool skipAuxHyps = false;
2071   list<const SMESHDS_Hypothesis*> aUsedHyp =
2072     theAlgo->GetUsedHypothesis( *_father, _subShape, skipAuxHyps ); // copy
2073
2074   // put in a compound all shapes with the same hypothesis assigned
2075   // and a good ComputeState
2076
2077   TopoDS_Compound aCompound;
2078   BRep_Builder aBuilder;
2079   aBuilder.MakeCompound( aCompound );
2080
2081   theSubs.clear();
2082
2083   SMESH_subMeshIteratorPtr smIt = _father->GetSubMesh( mainShape )->getDependsOnIterator(false);
2084   while ( smIt->more() )
2085   {
2086     SMESH_subMesh* subMesh = smIt->next();
2087     const TopoDS_Shape&  S = subMesh->_subShape;
2088     if ( S.ShapeType() != this->_subShape.ShapeType() )
2089       continue;
2090     if ( subMesh == this )
2091     {
2092       aBuilder.Add( aCompound, S );
2093       theSubs.push_back( subMesh );
2094     }
2095     else if ( subMesh->GetComputeState() == READY_TO_COMPUTE )
2096     {
2097       SMESH_Algo* anAlgo = subMesh->GetAlgo();
2098       if (( anAlgo->IsSameName( *theAlgo )) && // same algo
2099           ( anAlgo->GetUsedHypothesis( *_father, S, skipAuxHyps ) == aUsedHyp )) // same hyps
2100       {
2101         aBuilder.Add( aCompound, S );
2102         if ( !subMesh->SubMeshesComputed() )
2103           theSubComputed = false;
2104         theSubs.push_back( subMesh );
2105       }
2106     }
2107   }
2108
2109   return aCompound;
2110 }
2111
2112 //=======================================================================
2113 //function : getSimilarAttached
2114 //purpose  : return a hypothesis attached to theShape.
2115 //           If theHyp is provided, similar but not same hypotheses
2116 //           is returned; else only applicable ones having theHypType
2117 //           is returned
2118 //=======================================================================
2119
2120 const SMESH_Hypothesis* SMESH_subMesh::getSimilarAttached(const TopoDS_Shape&      theShape,
2121                                                           const SMESH_Hypothesis * theHyp,
2122                                                           const int                theHypType)
2123 {
2124   SMESH_HypoFilter hypoKind;
2125   hypoKind.Init( hypoKind.HasType( theHyp ? theHyp->GetType() : theHypType ));
2126   if ( theHyp ) {
2127     hypoKind.And   ( hypoKind.HasDim( theHyp->GetDim() ));
2128     hypoKind.AndNot( hypoKind.Is( theHyp ));
2129     if ( theHyp->IsAuxiliary() )
2130       hypoKind.And( hypoKind.HasName( theHyp->GetName() ));
2131     else
2132       hypoKind.AndNot( hypoKind.IsAuxiliary());
2133   }
2134   else {
2135     hypoKind.And( hypoKind.IsApplicableTo( theShape ));
2136   }
2137
2138   return _father->GetHypothesis( theShape, hypoKind, false );
2139 }
2140
2141 //=======================================================================
2142 //function : CheckConcurentHypothesis
2143 //purpose  : check if there are several applicable hypothesis attached to
2144 //           ancestors
2145 //=======================================================================
2146
2147 SMESH_Hypothesis::Hypothesis_Status
2148   SMESH_subMesh::CheckConcurentHypothesis (const int theHypType)
2149 {
2150   MESSAGE ("SMESH_subMesh::CheckConcurentHypothesis");
2151
2152   // is there local hypothesis on me?
2153   if ( getSimilarAttached( _subShape, 0, theHypType ) )
2154     return SMESH_Hypothesis::HYP_OK;
2155
2156
2157   TopoDS_Shape aPrevWithHyp;
2158   const SMESH_Hypothesis* aPrevHyp = 0;
2159   TopTools_ListIteratorOfListOfShape it( _father->GetAncestors( _subShape ));
2160   for (; it.More(); it.Next())
2161   {
2162     const TopoDS_Shape& ancestor = it.Value();
2163     const SMESH_Hypothesis* hyp = getSimilarAttached( ancestor, 0, theHypType );
2164     if ( hyp )
2165     {
2166       if ( aPrevWithHyp.IsNull() || aPrevWithHyp.IsSame( ancestor ))
2167       {
2168         aPrevWithHyp = ancestor;
2169         aPrevHyp     = hyp;
2170       }
2171       else if ( aPrevWithHyp.ShapeType() == ancestor.ShapeType() && aPrevHyp != hyp )
2172         return SMESH_Hypothesis::HYP_CONCURENT;
2173       else
2174         return SMESH_Hypothesis::HYP_OK;
2175     }
2176   }
2177   return SMESH_Hypothesis::HYP_OK;
2178 }
2179
2180 //================================================================================
2181 /*!
2182  * \brief Constructor of OwnListenerData
2183  */
2184 //================================================================================
2185
2186 SMESH_subMesh::OwnListenerData::OwnListenerData( SMESH_subMesh* sm, EventListener* el):
2187   mySubMesh( sm ),
2188   myMeshID( sm ? sm->GetFather()->GetId() : -1 ),
2189   mySubMeshID( sm ? sm->GetId() : -1 ),
2190   myListener( el )
2191 {
2192 }
2193
2194 //================================================================================
2195 /*!
2196  * \brief Sets an event listener and its data to a submesh
2197  * \param listener - the listener to store
2198  * \param data - the listener data to store
2199  * \param where - the submesh to store the listener and it's data
2200  * 
2201  * It remembers the submesh where it puts the listener in order to delete
2202  * them when HYP_OK algo_state is lost
2203  * After being set, event listener is notified on each event of where submesh.
2204  */
2205 //================================================================================
2206
2207 void SMESH_subMesh::SetEventListener(EventListener*     listener,
2208                                      EventListenerData* data,
2209                                      SMESH_subMesh*     where)
2210 {
2211   if ( listener && where ) {
2212     where->setEventListener( listener, data );
2213     _ownListeners.push_back( OwnListenerData( where, listener ));
2214   }
2215 }
2216
2217 //================================================================================
2218 /*!
2219  * \brief Sets an event listener and its data to a submesh
2220  * \param listener - the listener to store
2221  * \param data - the listener data to store
2222  * 
2223  * After being set, event listener is notified on each event of a submesh.
2224  */
2225 //================================================================================
2226
2227 void SMESH_subMesh::setEventListener(EventListener*     listener,
2228                                      EventListenerData* data)
2229 {
2230   map< EventListener*, EventListenerData* >::iterator l_d =
2231     _eventListeners.find( listener );
2232   if ( l_d != _eventListeners.end() ) {
2233     EventListenerData* curData = l_d->second;
2234     if ( curData && curData != data && curData->IsDeletable() )
2235       delete curData;
2236     l_d->second = data;
2237   }
2238   else
2239   {
2240     for ( l_d = _eventListeners.begin(); l_d != _eventListeners.end(); ++l_d )
2241       if ( listener->GetName() == l_d->first->GetName() )
2242       {
2243         EventListenerData* curData = l_d->second;
2244         if ( curData && curData != data && curData->IsDeletable() )
2245           delete curData;
2246         if ( l_d->first != listener && l_d->first->IsDeletable() )
2247           delete l_d->first;
2248         _eventListeners.erase( l_d );
2249         break;
2250       }
2251     _eventListeners.insert( make_pair( listener, data ));
2252   }
2253 }
2254
2255 //================================================================================
2256 /*!
2257  * \brief Return an event listener data
2258  * \param listener - the listener whose data is
2259  * \param myOwn - if \c true, returns a listener set by this sub-mesh,
2260  *        else returns a listener listening to events of this sub-mesh
2261  * \retval EventListenerData* - found data, maybe NULL
2262  */
2263 //================================================================================
2264
2265 EventListenerData* SMESH_subMesh::GetEventListenerData(EventListener* listener,
2266                                                        const bool     myOwn) const
2267 {
2268   if ( myOwn )
2269   {
2270     list< OwnListenerData >::const_iterator d;
2271     for ( d = _ownListeners.begin(); d != _ownListeners.end(); ++d )
2272     {
2273       if ( d->myListener == listener && _father->MeshExists( d->myMeshID ))
2274         return d->mySubMesh->GetEventListenerData( listener, !myOwn );
2275     }
2276   }
2277   else
2278   {
2279     map< EventListener*, EventListenerData* >::const_iterator l_d =
2280       _eventListeners.find( listener );
2281     if ( l_d != _eventListeners.end() )
2282       return l_d->second;
2283   }
2284   return 0;
2285 }
2286
2287 //================================================================================
2288 /*!
2289  * \brief Return an event listener data
2290  * \param listenerName - the listener name
2291  * \param myOwn - if \c true, returns a listener set by this sub-mesh,
2292  *        else returns a listener listening to events of this sub-mesh
2293  * \retval EventListenerData* - found data, maybe NULL
2294  */
2295 //================================================================================
2296
2297 EventListenerData* SMESH_subMesh::GetEventListenerData(const string& listenerName,
2298                                                        const bool    myOwn) const
2299 {
2300   if ( myOwn )
2301   {
2302     list< OwnListenerData >::const_iterator d;
2303     for ( d = _ownListeners.begin(); d != _ownListeners.end(); ++d )
2304     {
2305       if ( _father->MeshExists( d->myMeshID ) && listenerName == d->myListener->GetName())
2306         return d->mySubMesh->GetEventListenerData( listenerName, !myOwn );
2307     }
2308   }
2309   else
2310   {
2311     map< EventListener*, EventListenerData* >::const_iterator l_d = _eventListeners.begin();
2312     for ( ; l_d != _eventListeners.end(); ++l_d )
2313       if ( listenerName == l_d->first->GetName() )
2314         return l_d->second;
2315   }
2316   return 0;
2317 }
2318
2319 //================================================================================
2320 /*!
2321  * \brief Notify stored event listeners on the occured event
2322  * \param event - algo_event or compute_event itself
2323  * \param eventType - algo_event or compute_event
2324  * \param hyp - hypothesis, if eventType is algo_event
2325  */
2326 //================================================================================
2327
2328 void SMESH_subMesh::notifyListenersOnEvent( const int         event,
2329                                             const event_type  eventType,
2330                                             SMESH_Hypothesis* hyp)
2331 {
2332   list< pair< EventListener*, EventListenerData* > > eventListeners( _eventListeners.begin(),
2333                                                                      _eventListeners.end());
2334   list< pair< EventListener*, EventListenerData* > >::iterator l_d = eventListeners.begin();
2335   for ( ; l_d != eventListeners.end(); ++l_d )
2336   {
2337     std::pair< EventListener*, EventListenerData* > li_da = *l_d;
2338     if ( !_eventListeners.count( li_da.first )) continue;
2339
2340     if ( li_da.first->myBusySM.insert( this ).second )
2341     {
2342       const bool isDeletable = li_da.first->IsDeletable();
2343
2344       li_da.first->ProcessEvent( event, eventType, this, li_da.second, hyp );
2345
2346       if ( !isDeletable || _eventListeners.count( li_da.first ))
2347         li_da.first->myBusySM.erase( this ); // a listener is hopefully not dead
2348     }
2349   }
2350 }
2351
2352 //================================================================================
2353 /*!
2354  * \brief Unregister the listener and delete listener's data
2355  * \param listener - the event listener
2356  */
2357 //================================================================================
2358
2359 void SMESH_subMesh::DeleteEventListener(EventListener* listener)
2360 {
2361   map< EventListener*, EventListenerData* >::iterator l_d =
2362     _eventListeners.find( listener );
2363   if ( l_d != _eventListeners.end() && l_d->first )
2364   {
2365     if ( l_d->second && l_d->second->IsDeletable() )
2366     {
2367       delete l_d->second;
2368     }
2369     l_d->first->myBusySM.erase( this );
2370     if ( l_d->first->IsDeletable() )
2371     {
2372       l_d->first->BeforeDelete( this, l_d->second );
2373       delete l_d->first;
2374     }
2375     _eventListeners.erase( l_d );
2376   }
2377 }
2378
2379 //================================================================================
2380 /*!
2381  * \brief Delete event listeners depending on algo of this submesh
2382  */
2383 //================================================================================
2384
2385 void SMESH_subMesh::deleteOwnListeners()
2386 {
2387   list< OwnListenerData >::iterator d;
2388   for ( d = _ownListeners.begin(); d != _ownListeners.end(); ++d )
2389   {
2390     SMESH_Mesh* mesh = _father->FindMesh( d->myMeshID );
2391     if ( !mesh || !mesh->GetSubMeshContaining( d->mySubMeshID ))
2392       continue;
2393     d->mySubMesh->DeleteEventListener( d->myListener );
2394   }
2395   _ownListeners.clear();
2396 }
2397
2398 //=======================================================================
2399 //function : loadDependentMeshes
2400 //purpose  : loads dependent meshes on SUBMESH_LOADED event
2401 //=======================================================================
2402
2403 void SMESH_subMesh::loadDependentMeshes()
2404 {
2405   list< OwnListenerData >::iterator d;
2406   for ( d = _ownListeners.begin(); d != _ownListeners.end(); ++d )
2407     if ( _father != d->mySubMesh->_father )
2408       d->mySubMesh->_father->Load();
2409
2410   // map< EventListener*, EventListenerData* >::iterator l_d = _eventListeners.begin();
2411   // for ( ; l_d != _eventListeners.end(); ++l_d )
2412   //   if ( l_d->second )
2413   //   {
2414   //     const list<SMESH_subMesh*>& smList = l_d->second->mySubMeshes;
2415   //     list<SMESH_subMesh*>::const_iterator sm = smList.begin();
2416   //     for ( ; sm != smList.end(); ++sm )
2417   //       if ( _father != (*sm)->_father )
2418   //         (*sm)->_father->Load();
2419   //   }
2420 }
2421
2422 //================================================================================
2423 /*!
2424  * \brief Do something on a certain event
2425  * \param event - algo_event or compute_event itself
2426  * \param eventType - algo_event or compute_event
2427  * \param subMesh - the submesh where the event occures
2428  * \param data - listener data stored in the subMesh
2429  * \param hyp - hypothesis, if eventType is algo_event
2430  * 
2431  * The base implementation translates CLEAN event to the subMesh
2432  * stored in listener data. Also it sends SUBMESH_COMPUTED event in case of
2433  * successful COMPUTE event.
2434  */
2435 //================================================================================
2436
2437 void SMESH_subMeshEventListener::ProcessEvent(const int          event,
2438                                               const int          eventType,
2439                                               SMESH_subMesh*     subMesh,
2440                                               EventListenerData* data,
2441                                               const SMESH_Hypothesis*  /*hyp*/)
2442 {
2443   if ( data && !data->mySubMeshes.empty() &&
2444        eventType == SMESH_subMesh::COMPUTE_EVENT)
2445   {
2446     ASSERT( data->mySubMeshes.front() != subMesh );
2447     list<SMESH_subMesh*>::iterator smIt = data->mySubMeshes.begin();
2448     list<SMESH_subMesh*>::iterator smEnd = data->mySubMeshes.end();
2449     switch ( event ) {
2450     case SMESH_subMesh::CLEAN:
2451       for ( ; smIt != smEnd; ++ smIt)
2452         (*smIt)->ComputeStateEngine( SMESH_subMesh::compute_event( event ));
2453       break;
2454     case SMESH_subMesh::COMPUTE:
2455     case SMESH_subMesh::COMPUTE_SUBMESH:
2456       if ( subMesh->GetComputeState() == SMESH_subMesh::COMPUTE_OK )
2457         for ( ; smIt != smEnd; ++ smIt)
2458           (*smIt)->ComputeStateEngine( SMESH_subMesh::SUBMESH_COMPUTED );
2459       break;
2460     default:;
2461     }
2462   }
2463 }
2464
2465 namespace {
2466
2467   //================================================================================
2468   /*!
2469    * \brief Iterator over submeshes and optionally prepended or appended one
2470    */
2471   //================================================================================
2472
2473   struct _Iterator : public SMDS_Iterator<SMESH_subMesh*>
2474   {
2475     _Iterator(SMDS_Iterator<SMESH_subMesh*>* subIt,
2476               SMESH_subMesh*                 prepend,
2477               SMESH_subMesh*                 append): myAppend(append), myIt(subIt)
2478     {
2479       myCur = prepend ? prepend : myIt->more() ? myIt->next() : append;
2480       if ( myCur == append ) append = 0;
2481     }
2482     /// Return true if and only if there are other object in this iterator
2483     virtual bool more()
2484     {
2485       return myCur;
2486     }
2487     /// Return the current object and step to the next one
2488     virtual SMESH_subMesh* next()
2489     {
2490       SMESH_subMesh* res = myCur;
2491       if ( myIt->more() ) { myCur = myIt->next(); }
2492       else                { myCur = myAppend; myAppend = 0; }
2493       return res;
2494     }
2495     /// ~
2496     ~_Iterator()
2497     { delete myIt; }
2498     ///
2499     SMESH_subMesh                 *myAppend, *myCur;
2500     SMDS_Iterator<SMESH_subMesh*> *myIt;
2501   };
2502 }
2503
2504 //================================================================================
2505 /*!
2506  * \brief  Return iterator on the submeshes this one depends on
2507   * \param includeSelf - this submesh to be returned also
2508   * \param reverse - if true, complex shape submeshes go first
2509  */
2510 //================================================================================
2511
2512 SMESH_subMeshIteratorPtr SMESH_subMesh::getDependsOnIterator(const bool includeSelf,
2513                                                              const bool reverse) const
2514 {
2515   SMESH_subMesh *me = (SMESH_subMesh*) this;
2516   SMESH_subMesh *prepend=0, *append=0;
2517   if ( includeSelf ) {
2518     if ( reverse ) prepend = me;
2519     else            append = me;
2520   }
2521   typedef map < int, SMESH_subMesh * > TMap;
2522   if ( reverse )
2523   {
2524     return SMESH_subMeshIteratorPtr
2525       ( new _Iterator( new SMDS_mapReverseIterator<TMap>( me->DependsOn() ), prepend, append ));
2526   }
2527   {
2528     return SMESH_subMeshIteratorPtr
2529       ( new _Iterator( new SMDS_mapIterator<TMap>( me->DependsOn() ), prepend, append ));
2530   }
2531 }
2532
2533 //================================================================================
2534 /*!
2535  * \brief Returns ancestor sub-meshes. Finds them if not yet found.
2536  */
2537 //================================================================================
2538
2539 const std::vector< SMESH_subMesh * > & SMESH_subMesh::GetAncestors() const
2540 {
2541   if ( _ancestors.empty() &&
2542        !_subShape.IsSame( _father->GetShapeToMesh() ))
2543   {
2544     const TopTools_ListOfShape& ancShapes = _father->GetAncestors( _subShape );
2545
2546     SMESH_subMesh* me = const_cast< SMESH_subMesh* >( this );
2547     me->_ancestors.reserve( ancShapes.Extent() );
2548
2549     TopTools_MapOfShape map;
2550    
2551     for ( TopTools_ListIteratorOfListOfShape it( ancShapes ); it.More(); it.Next() )
2552       if ( SMESH_subMesh* sm = _father->GetSubMeshContaining( it.Value() ))
2553         if ( map.Add( it.Value() ))
2554           me->_ancestors.push_back( sm );
2555   }
2556
2557   return _ancestors;
2558 }
2559
2560 //================================================================================
2561 /*!
2562  * \brief Clears the vector of ancestor sub-meshes
2563  */
2564 //================================================================================
2565
2566 void SMESH_subMesh::ClearAncestors()
2567 {
2568   _ancestors.clear();
2569 }
2570
2571 //================================================================================
2572 /*!
2573  * \brief  Find common submeshes (based on shared sub-shapes with other
2574   * \param theOther submesh to check
2575   * \param theSetOfCommon set of common submesh
2576  */
2577 //================================================================================
2578
2579 bool SMESH_subMesh::FindIntersection(const SMESH_subMesh*            theOther,
2580                                      std::set<const SMESH_subMesh*>& theSetOfCommon ) const
2581 {
2582   size_t oldNb = theSetOfCommon.size();
2583
2584   // check main submeshes
2585   const map <int, SMESH_subMesh*>::const_iterator otherEnd = theOther->_mapDepend.end();
2586   if ( theOther->_mapDepend.find(this->GetId()) != otherEnd )
2587     theSetOfCommon.insert( this );
2588   if ( _mapDepend.find(theOther->GetId()) != _mapDepend.end() )
2589     theSetOfCommon.insert( theOther );
2590
2591   // check common submeshes
2592   map <int, SMESH_subMesh*>::const_iterator mapIt = _mapDepend.begin();
2593   for( ; mapIt != _mapDepend.end(); mapIt++ )
2594     if ( theOther->_mapDepend.find((*mapIt).first) != otherEnd )
2595       theSetOfCommon.insert( (*mapIt).second );
2596   return oldNb < theSetOfCommon.size();
2597 }