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