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