Salome HOME
3745a2b77afe3dcce5911f5de6506c17cef6f2fc
[modules/smesh.git] / src / SMESH / SMESH_subMesh.cxx
1 // Copyright (C) 2007-2015  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  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 ( IsEmpty() ) // 23061
1865       {
1866         if (_algoState == HYP_OK)
1867           _computeState = READY_TO_COMPUTE;
1868         else
1869           _computeState = NOT_READY;
1870       }
1871       break;
1872     case SUBMESH_RESTORED:
1873       ComputeSubMeshStateEngine( SUBMESH_RESTORED );
1874       break;
1875     case MESH_ENTITY_REMOVED:
1876       break;
1877     case CHECK_COMPUTE_STATE:
1878       if ( IsMeshComputed() )
1879         _computeState = COMPUTE_OK;
1880       else
1881         if (_algoState == HYP_OK)
1882           _computeState = READY_TO_COMPUTE;
1883         else
1884           _computeState = NOT_READY;
1885       break;
1886     // case SUBMESH_LOADED:
1887     //   break;
1888     default:
1889       ASSERT(0);
1890       break;
1891     }
1892     break;
1893
1894     // ----------------------------------------------------------------------
1895   default:
1896     ASSERT(0);
1897     break;
1898   }
1899
1900   notifyListenersOnEvent( event, COMPUTE_EVENT );
1901
1902   return ret;
1903 }
1904
1905
1906 //=============================================================================
1907 /*!
1908  *
1909  */
1910 //=============================================================================
1911
1912 bool SMESH_subMesh::Evaluate(MapShapeNbElems& aResMap)
1913 {
1914   _computeError.reset();
1915
1916   bool ret = true;
1917
1918   if (_subShape.ShapeType() == TopAbs_VERTEX) {
1919     vector<int> aVec(SMDSEntity_Last,0);
1920     aVec[SMDSEntity_Node] = 1;
1921     aResMap.insert(make_pair(this,aVec));
1922     return ret;
1923   }
1924
1925   //SMESH_Gen *gen = _father->GetGen();
1926   SMESH_Algo *algo = 0;
1927   SMESH_Hypothesis::Hypothesis_Status hyp_status;
1928
1929   algo = GetAlgo();
1930   if(algo && !aResMap.count(this) )
1931   {
1932     ret = algo->CheckHypothesis((*_father), _subShape, hyp_status);
1933     if (!ret) return false;
1934
1935     if (_father->HasShapeToMesh() && algo->NeedDiscreteBoundary())
1936     {
1937       // check submeshes needed
1938       bool subMeshEvaluated = true;
1939       int dimToCheck = SMESH_Gen::GetShapeDim( _subShape ) - 1;
1940       SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,/*complexShapeFirst=*/true);
1941       while ( smIt->more() && subMeshEvaluated )
1942       {
1943         SMESH_subMesh* sm = smIt->next();
1944         int dim = SMESH_Gen::GetShapeDim( sm->GetSubShape() );
1945         if (dim < dimToCheck) break; // the rest subMeshes are all of less dimension
1946         const vector<int> & nbs = aResMap[ sm ];
1947         subMeshEvaluated = (std::accumulate( nbs.begin(), nbs.end(), 0 ) > 0 );
1948       }
1949       if ( !subMeshEvaluated )
1950         return false;
1951     }
1952     _computeError = SMESH_ComputeError::New(COMPERR_OK,"",algo);
1953     ret = algo->Evaluate((*_father), _subShape, aResMap);
1954
1955     aResMap.insert( make_pair( this,vector<int>(0)));
1956   }
1957
1958   return ret;
1959 }
1960
1961
1962 //=======================================================================
1963 /*!
1964  * \brief Update compute_state by _computeError and send proper events to
1965  * dependent submeshes
1966   * \retval bool - true if _computeError is NOT set
1967  */
1968 //=======================================================================
1969
1970 bool SMESH_subMesh::checkComputeError(SMESH_Algo*         theAlgo,
1971                                       const bool          theComputeOK,
1972                                       const TopoDS_Shape& theShape)
1973 {
1974   bool noErrors = true;
1975
1976   if ( !theShape.IsNull() )
1977   {
1978     // Check state of submeshes
1979     if ( !theAlgo->NeedDiscreteBoundary())
1980     {
1981       SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,false);
1982       while ( smIt->more() )
1983         if ( !smIt->next()->checkComputeError( theAlgo, theComputeOK ))
1984           noErrors = false;
1985     }
1986
1987     // Check state of neighbours
1988     if ( !theAlgo->OnlyUnaryInput() &&
1989          theShape.ShapeType() == TopAbs_COMPOUND &&
1990          !theShape.IsSame( _subShape ))
1991     {
1992       for (TopoDS_Iterator subIt( theShape ); subIt.More(); subIt.Next()) {
1993         SMESH_subMesh* sm = _father->GetSubMesh( subIt.Value() );
1994         if ( sm != this ) {
1995           if ( !sm->checkComputeError( theAlgo, theComputeOK, sm->GetSubShape() ))
1996             noErrors = false;
1997           updateDependantsState( SUBMESH_COMPUTED ); // send event SUBMESH_COMPUTED
1998         }
1999       }
2000     }
2001   }
2002   {
2003
2004     // Set my _computeState
2005
2006     if ( !_computeError || _computeError->IsOK() )
2007     {
2008       // no error description is set to this sub-mesh, check if any mesh is computed
2009       _computeState = IsMeshComputed() ? COMPUTE_OK : FAILED_TO_COMPUTE;
2010       if ( _computeState != COMPUTE_OK )
2011       {
2012         if ( _subShape.ShapeType() == TopAbs_EDGE &&
2013              SMESH_Algo::isDegenerated( TopoDS::Edge( _subShape )) )
2014           _computeState = COMPUTE_OK;
2015         else if ( theComputeOK )
2016           _computeError = SMESH_ComputeError::New(COMPERR_NO_MESH_ON_SHAPE,"",theAlgo);
2017       }
2018     }
2019
2020     if ( _computeError && !_computeError->IsOK() )
2021     {
2022       if ( !_computeError->myAlgo )
2023         _computeError->myAlgo = theAlgo;
2024
2025       // Show error
2026       SMESH_Comment text;
2027       text << theAlgo->GetName() << " failed on sub-shape #" << _Id << " with error ";
2028       if (_computeError->IsCommon() )
2029         text << _computeError->CommonName();
2030       else
2031         text << _computeError->myName;
2032       if ( _computeError->myComment.size() > 0 )
2033         text << " \"" << _computeError->myComment << "\"";
2034
2035       INFOS( text );
2036
2037       _computeState = _computeError->IsKO() ? FAILED_TO_COMPUTE : COMPUTE_OK;
2038
2039       noErrors = false;
2040     }
2041   }
2042   return noErrors;
2043 }
2044
2045 //=======================================================================
2046 //function : updateSubMeshState
2047 //purpose  :
2048 //=======================================================================
2049
2050 void SMESH_subMesh::updateSubMeshState(const compute_state theState)
2051 {
2052   SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,false);
2053   while ( smIt->more() )
2054     smIt->next()->_computeState = theState;
2055 }
2056
2057 //=======================================================================
2058 //function : ComputeSubMeshStateEngine
2059 //purpose  :
2060 //=======================================================================
2061
2062 void SMESH_subMesh::ComputeSubMeshStateEngine(int event, const bool includeSelf)
2063 {
2064   SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(includeSelf,false);
2065   while ( smIt->more() )
2066     smIt->next()->ComputeStateEngine(event);
2067 }
2068
2069 //=======================================================================
2070 //function : updateDependantsState
2071 //purpose  :
2072 //=======================================================================
2073
2074 void SMESH_subMesh::updateDependantsState(const compute_event theEvent)
2075 {
2076   const std::vector< SMESH_subMesh * > & ancestors = GetAncestors();
2077   for ( size_t iA = 0; iA < ancestors.size(); ++iA )
2078   {
2079     ancestors[ iA ]->ComputeStateEngine( theEvent );
2080   }
2081 }
2082
2083 //=============================================================================
2084 /*!
2085  *
2086  */
2087 //=============================================================================
2088
2089 void SMESH_subMesh::cleanDependants()
2090 {
2091   int dimToClean = SMESH_Gen::GetShapeDim( _subShape ) + 1;
2092
2093   const std::vector< SMESH_subMesh * > & ancestors = GetAncestors();
2094   for ( size_t iA = 0; iA < ancestors.size(); ++iA )
2095   {
2096     const TopoDS_Shape& ancestor = ancestors[ iA ]->GetSubShape();
2097     if ( SMESH_Gen::GetShapeDim( ancestor ) == dimToClean )
2098     {
2099       // PAL8021. do not go upper than SOLID, else ComputeStateEngine(CLEAN)
2100       // will erase mesh on other shapes in a compound
2101       if ( ancestor.ShapeType() >= TopAbs_SOLID &&
2102            !ancestors[ iA ]->IsEmpty() )  // prevent infinite CLEAN via event lesteners
2103         ancestors[ iA ]->ComputeStateEngine(CLEAN);
2104     }
2105   }
2106 }
2107
2108 //=============================================================================
2109 /*!
2110  *
2111  */
2112 //=============================================================================
2113
2114 void SMESH_subMesh::removeSubMeshElementsAndNodes()
2115 {
2116   cleanSubMesh( this );
2117
2118   // algo may bind a submesh not to _subShape, eg 3D algo
2119   // sets nodes on SHELL while _subShape may be SOLID
2120
2121   int dim = SMESH_Gen::GetShapeDim( _subShape );
2122   int type = _subShape.ShapeType() + 1;
2123   for ( ; type <= TopAbs_EDGE; type++) {
2124     if ( dim == SMESH_Gen::GetShapeDim( (TopAbs_ShapeEnum) type ))
2125     {
2126       TopExp_Explorer exp( _subShape, (TopAbs_ShapeEnum) type );
2127       for ( ; exp.More(); exp.Next() )
2128         cleanSubMesh( _father->GetSubMeshContaining( exp.Current() ));
2129     }
2130     else
2131       break;
2132   }
2133 }
2134
2135 //=======================================================================
2136 //function : getCollection
2137 //purpose  : return a shape containing all sub-shapes of the MainShape that can be
2138 //           meshed at once along with _subShape
2139 //=======================================================================
2140
2141 TopoDS_Shape SMESH_subMesh::getCollection(SMESH_Gen * theGen,
2142                                           SMESH_Algo* theAlgo,
2143                                           bool &      theSubComputed,
2144                                           bool &      theSubFailed,
2145                                           std::vector<SMESH_subMesh*>& theSubs)
2146 {
2147   theSubComputed = SubMeshesComputed( & theSubFailed );
2148
2149   TopoDS_Shape mainShape = _father->GetMeshDS()->ShapeToMesh();
2150
2151   if ( mainShape.IsSame( _subShape ))
2152     return _subShape;
2153
2154   const bool skipAuxHyps = false;
2155   list<const SMESHDS_Hypothesis*> aUsedHyp =
2156     theAlgo->GetUsedHypothesis( *_father, _subShape, skipAuxHyps ); // copy
2157
2158   // put in a compound all shapes with the same hypothesis assigned
2159   // and a good ComputeState
2160
2161   TopoDS_Compound aCompound;
2162   BRep_Builder aBuilder;
2163   aBuilder.MakeCompound( aCompound );
2164
2165   theSubs.clear();
2166
2167   SMESH_subMeshIteratorPtr smIt = _father->GetSubMesh( mainShape )->getDependsOnIterator(false);
2168   while ( smIt->more() )
2169   {
2170     SMESH_subMesh* subMesh = smIt->next();
2171     const TopoDS_Shape&  S = subMesh->_subShape;
2172     if ( S.ShapeType() != this->_subShape.ShapeType() )
2173       continue;
2174     theSubs.push_back( subMesh );
2175     if ( subMesh == this )
2176     {
2177       aBuilder.Add( aCompound, S );
2178     }
2179     else if ( subMesh->GetComputeState() == READY_TO_COMPUTE )
2180     {
2181       SMESH_Algo* anAlgo = subMesh->GetAlgo();
2182       if (( anAlgo->IsSameName( *theAlgo )) && // same algo
2183           ( anAlgo->GetUsedHypothesis( *_father, S, skipAuxHyps ) == aUsedHyp )) // same hyps
2184       {
2185         aBuilder.Add( aCompound, S );
2186         if ( !subMesh->SubMeshesComputed() )
2187           theSubComputed = false;
2188       }
2189     }
2190   }
2191
2192   return aCompound;
2193 }
2194
2195 //=======================================================================
2196 //function : getSimilarAttached
2197 //purpose  : return a hypothesis attached to theShape.
2198 //           If theHyp is provided, similar but not same hypotheses
2199 //           is returned; else only applicable ones having theHypType
2200 //           is returned
2201 //=======================================================================
2202
2203 const SMESH_Hypothesis* SMESH_subMesh::getSimilarAttached(const TopoDS_Shape&      theShape,
2204                                                           const SMESH_Hypothesis * theHyp,
2205                                                           const int                theHypType)
2206 {
2207   SMESH_HypoFilter hypoKind;
2208   hypoKind.Init( hypoKind.HasType( theHyp ? theHyp->GetType() : theHypType ));
2209   if ( theHyp ) {
2210     hypoKind.And   ( hypoKind.HasDim( theHyp->GetDim() ));
2211     hypoKind.AndNot( hypoKind.Is( theHyp ));
2212     if ( theHyp->IsAuxiliary() )
2213       hypoKind.And( hypoKind.HasName( theHyp->GetName() ));
2214     else
2215       hypoKind.AndNot( hypoKind.IsAuxiliary());
2216   }
2217   else {
2218     hypoKind.And( hypoKind.IsApplicableTo( theShape ));
2219   }
2220
2221   return _father->GetHypothesis( theShape, hypoKind, false );
2222 }
2223
2224 //=======================================================================
2225 //function : CheckConcurentHypothesis
2226 //purpose  : check if there are several applicable hypothesis attached to
2227 //           ancestors
2228 //=======================================================================
2229
2230 SMESH_Hypothesis::Hypothesis_Status
2231   SMESH_subMesh::CheckConcurentHypothesis (const int theHypType)
2232 {
2233   MESSAGE ("SMESH_subMesh::CheckConcurentHypothesis");
2234
2235   // is there local hypothesis on me?
2236   if ( getSimilarAttached( _subShape, 0, theHypType ) )
2237     return SMESH_Hypothesis::HYP_OK;
2238
2239
2240   TopoDS_Shape aPrevWithHyp;
2241   const SMESH_Hypothesis* aPrevHyp = 0;
2242   TopTools_ListIteratorOfListOfShape it( _father->GetAncestors( _subShape ));
2243   for (; it.More(); it.Next())
2244   {
2245     const TopoDS_Shape& ancestor = it.Value();
2246     const SMESH_Hypothesis* hyp = getSimilarAttached( ancestor, 0, theHypType );
2247     if ( hyp )
2248     {
2249       if ( aPrevWithHyp.IsNull() || aPrevWithHyp.IsSame( ancestor ))
2250       {
2251         aPrevWithHyp = ancestor;
2252         aPrevHyp     = hyp;
2253       }
2254       else if ( aPrevWithHyp.ShapeType() == ancestor.ShapeType() && aPrevHyp != hyp )
2255         return SMESH_Hypothesis::HYP_CONCURENT;
2256       else
2257         return SMESH_Hypothesis::HYP_OK;
2258     }
2259   }
2260   return SMESH_Hypothesis::HYP_OK;
2261 }
2262
2263 //================================================================================
2264 /*!
2265  * \brief Constructor of OwnListenerData
2266  */
2267 //================================================================================
2268
2269 SMESH_subMesh::OwnListenerData::OwnListenerData( SMESH_subMesh* sm, EventListener* el):
2270   mySubMesh( sm ),
2271   myMeshID( sm ? sm->GetFather()->GetId() : -1 ),
2272   mySubMeshID( sm ? sm->GetId() : -1 ),
2273   myListener( el )
2274 {
2275 }
2276
2277 //================================================================================
2278 /*!
2279  * \brief Sets an event listener and its data to a submesh
2280  * \param listener - the listener to store
2281  * \param data - the listener data to store
2282  * \param where - the submesh to store the listener and it's data
2283  * 
2284  * It remembers the submesh where it puts the listener in order to delete
2285  * them when HYP_OK algo_state is lost
2286  * After being set, event listener is notified on each event of where submesh.
2287  */
2288 //================================================================================
2289
2290 void SMESH_subMesh::SetEventListener(EventListener*     listener,
2291                                      EventListenerData* data,
2292                                      SMESH_subMesh*     where)
2293 {
2294   if ( listener && where ) {
2295     where->setEventListener( listener, data );
2296     _ownListeners.push_back( OwnListenerData( where, listener ));
2297   }
2298 }
2299
2300 //================================================================================
2301 /*!
2302  * \brief Sets an event listener and its data to a submesh
2303  * \param listener - the listener to store
2304  * \param data - the listener data to store
2305  * 
2306  * After being set, event listener is notified on each event of a submesh.
2307  */
2308 //================================================================================
2309
2310 void SMESH_subMesh::setEventListener(EventListener*     listener,
2311                                      EventListenerData* data)
2312 {
2313   map< EventListener*, EventListenerData* >::iterator l_d =
2314     _eventListeners.find( listener );
2315   if ( l_d != _eventListeners.end() ) {
2316     EventListenerData* curData = l_d->second;
2317     if ( curData && curData != data && curData->IsDeletable() )
2318       delete curData;
2319     l_d->second = data;
2320   }
2321   else
2322   {
2323     for ( l_d = _eventListeners.begin(); l_d != _eventListeners.end(); ++l_d )
2324       if ( listener->GetName() == l_d->first->GetName() )
2325       {
2326         EventListenerData* curData = l_d->second;
2327         if ( curData && curData != data && curData->IsDeletable() )
2328           delete curData;
2329         if ( l_d->first != listener && l_d->first->IsDeletable() )
2330           delete l_d->first;
2331         _eventListeners.erase( l_d );
2332         break;
2333       }
2334     _eventListeners.insert( make_pair( listener, data ));
2335   }
2336 }
2337
2338 //================================================================================
2339 /*!
2340  * \brief Return an event listener data
2341  * \param listener - the listener whose data is
2342  * \param myOwn - if \c true, returns a listener set by this sub-mesh,
2343  *        else returns a listener listening to events of this sub-mesh
2344  * \retval EventListenerData* - found data, maybe NULL
2345  */
2346 //================================================================================
2347
2348 EventListenerData* SMESH_subMesh::GetEventListenerData(EventListener* listener,
2349                                                        const bool     myOwn) const
2350 {
2351   if ( myOwn )
2352   {
2353     list< OwnListenerData >::const_iterator d;
2354     for ( d = _ownListeners.begin(); d != _ownListeners.end(); ++d )
2355     {
2356       if ( d->myListener == listener && _father->MeshExists( d->myMeshID ))
2357         return d->mySubMesh->GetEventListenerData( listener, !myOwn );
2358     }
2359   }
2360   else
2361   {
2362     map< EventListener*, EventListenerData* >::const_iterator l_d =
2363       _eventListeners.find( listener );
2364     if ( l_d != _eventListeners.end() )
2365       return l_d->second;
2366   }
2367   return 0;
2368 }
2369
2370 //================================================================================
2371 /*!
2372  * \brief Return an event listener data
2373  * \param listenerName - the listener name
2374  * \param myOwn - if \c true, returns a listener set by this sub-mesh,
2375  *        else returns a listener listening to events of this sub-mesh
2376  * \retval EventListenerData* - found data, maybe NULL
2377  */
2378 //================================================================================
2379
2380 EventListenerData* SMESH_subMesh::GetEventListenerData(const string& listenerName,
2381                                                        const bool    myOwn) const
2382 {
2383   if ( myOwn )
2384   {
2385     list< OwnListenerData >::const_iterator d;
2386     for ( d = _ownListeners.begin(); d != _ownListeners.end(); ++d )
2387     {
2388       if ( _father->MeshExists( d->myMeshID ) && listenerName == d->myListener->GetName())
2389         return d->mySubMesh->GetEventListenerData( listenerName, !myOwn );
2390     }
2391   }
2392   else
2393   {
2394     map< EventListener*, EventListenerData* >::const_iterator l_d = _eventListeners.begin();
2395     for ( ; l_d != _eventListeners.end(); ++l_d )
2396       if ( listenerName == l_d->first->GetName() )
2397         return l_d->second;
2398   }
2399   return 0;
2400 }
2401
2402 //================================================================================
2403 /*!
2404  * \brief Notify stored event listeners on the occured event
2405  * \param event - algo_event or compute_event itself
2406  * \param eventType - algo_event or compute_event
2407  * \param hyp - hypothesis, if eventType is algo_event
2408  */
2409 //================================================================================
2410
2411 void SMESH_subMesh::notifyListenersOnEvent( const int         event,
2412                                             const event_type  eventType,
2413                                             SMESH_Hypothesis* hyp)
2414 {
2415   list< pair< EventListener*, EventListenerData* > > eventListeners( _eventListeners.begin(),
2416                                                                      _eventListeners.end());
2417   list< pair< EventListener*, EventListenerData* > >::iterator l_d = eventListeners.begin();
2418   for ( ; l_d != eventListeners.end(); ++l_d )
2419   {
2420     std::pair< EventListener*, EventListenerData* > li_da = *l_d;
2421     if ( !_eventListeners.count( li_da.first )) continue;
2422
2423     if ( li_da.first->myBusySM.insert( this ).second )
2424     {
2425       const bool isDeletable = li_da.first->IsDeletable();
2426
2427       li_da.first->ProcessEvent( event, eventType, this, li_da.second, hyp );
2428
2429       if ( !isDeletable || _eventListeners.count( li_da.first ))
2430         li_da.first->myBusySM.erase( this ); // a listener is hopefully not dead
2431     }
2432   }
2433 }
2434
2435 //================================================================================
2436 /*!
2437  * \brief Unregister the listener and delete listener's data
2438  * \param listener - the event listener
2439  */
2440 //================================================================================
2441
2442 void SMESH_subMesh::DeleteEventListener(EventListener* listener)
2443 {
2444   map< EventListener*, EventListenerData* >::iterator l_d =
2445     _eventListeners.find( listener );
2446   if ( l_d != _eventListeners.end() && l_d->first )
2447   {
2448     if ( l_d->second && l_d->second->IsDeletable() )
2449     {
2450       delete l_d->second;
2451     }
2452     l_d->first->myBusySM.erase( this );
2453     if ( l_d->first->IsDeletable() )
2454     {
2455       l_d->first->BeforeDelete( this, l_d->second );
2456       delete l_d->first;
2457     }
2458     _eventListeners.erase( l_d );
2459   }
2460 }
2461
2462 //================================================================================
2463 /*!
2464  * \brief Delete event listeners depending on algo of this submesh
2465  */
2466 //================================================================================
2467
2468 void SMESH_subMesh::deleteOwnListeners()
2469 {
2470   list< OwnListenerData >::iterator d;
2471   for ( d = _ownListeners.begin(); d != _ownListeners.end(); ++d )
2472   {
2473     SMESH_Mesh* mesh = _father->FindMesh( d->myMeshID );
2474     if ( !mesh || !mesh->GetSubMeshContaining( d->mySubMeshID ))
2475       continue;
2476     d->mySubMesh->DeleteEventListener( d->myListener );
2477   }
2478   _ownListeners.clear();
2479 }
2480
2481 //=======================================================================
2482 //function : loadDependentMeshes
2483 //purpose  : loads dependent meshes on SUBMESH_LOADED event
2484 //=======================================================================
2485
2486 void SMESH_subMesh::loadDependentMeshes()
2487 {
2488   list< OwnListenerData >::iterator d;
2489   for ( d = _ownListeners.begin(); d != _ownListeners.end(); ++d )
2490     if ( _father != d->mySubMesh->_father )
2491       d->mySubMesh->_father->Load();
2492
2493   // map< EventListener*, EventListenerData* >::iterator l_d = _eventListeners.begin();
2494   // for ( ; l_d != _eventListeners.end(); ++l_d )
2495   //   if ( l_d->second )
2496   //   {
2497   //     const list<SMESH_subMesh*>& smList = l_d->second->mySubMeshes;
2498   //     list<SMESH_subMesh*>::const_iterator sm = smList.begin();
2499   //     for ( ; sm != smList.end(); ++sm )
2500   //       if ( _father != (*sm)->_father )
2501   //         (*sm)->_father->Load();
2502   //   }
2503 }
2504
2505 //================================================================================
2506 /*!
2507  * \brief Do something on a certain event
2508  * \param event - algo_event or compute_event itself
2509  * \param eventType - algo_event or compute_event
2510  * \param subMesh - the submesh where the event occures
2511  * \param data - listener data stored in the subMesh
2512  * \param hyp - hypothesis, if eventType is algo_event
2513  * 
2514  * The base implementation translates CLEAN event to the subMesh
2515  * stored in listener data. Also it sends SUBMESH_COMPUTED event in case of
2516  * successful COMPUTE event.
2517  */
2518 //================================================================================
2519
2520 void SMESH_subMeshEventListener::ProcessEvent(const int          event,
2521                                               const int          eventType,
2522                                               SMESH_subMesh*     subMesh,
2523                                               EventListenerData* data,
2524                                               const SMESH_Hypothesis*  /*hyp*/)
2525 {
2526   if ( data && !data->mySubMeshes.empty() &&
2527        eventType == SMESH_subMesh::COMPUTE_EVENT)
2528   {
2529     ASSERT( data->mySubMeshes.front() != subMesh );
2530     list<SMESH_subMesh*>::iterator smIt = data->mySubMeshes.begin();
2531     list<SMESH_subMesh*>::iterator smEnd = data->mySubMeshes.end();
2532     switch ( event ) {
2533     case SMESH_subMesh::CLEAN:
2534       for ( ; smIt != smEnd; ++ smIt)
2535         (*smIt)->ComputeStateEngine( event );
2536       break;
2537     case SMESH_subMesh::COMPUTE:
2538     case SMESH_subMesh::COMPUTE_SUBMESH:
2539       if ( subMesh->GetComputeState() == SMESH_subMesh::COMPUTE_OK )
2540         for ( ; smIt != smEnd; ++ smIt)
2541           (*smIt)->ComputeStateEngine( SMESH_subMesh::SUBMESH_COMPUTED );
2542       break;
2543     default:;
2544     }
2545   }
2546 }
2547
2548 namespace {
2549
2550   //================================================================================
2551   /*!
2552    * \brief Iterator over submeshes and optionally prepended or appended one
2553    */
2554   //================================================================================
2555
2556   struct _Iterator : public SMDS_Iterator<SMESH_subMesh*>
2557   {
2558     _Iterator(SMDS_Iterator<SMESH_subMesh*>* subIt,
2559               SMESH_subMesh*                 prepend,
2560               SMESH_subMesh*                 append): myIt(subIt),myAppend(append)
2561     {
2562       myCur = prepend ? prepend : myIt->more() ? myIt->next() : append;
2563       if ( myCur == append ) append = 0;
2564     }
2565     /// Return true if and only if there are other object in this iterator
2566     virtual bool more()
2567     {
2568       return myCur;
2569     }
2570     /// Return the current object and step to the next one
2571     virtual SMESH_subMesh* next()
2572     {
2573       SMESH_subMesh* res = myCur;
2574       if ( myIt->more() ) { myCur = myIt->next(); }
2575       else                { myCur = myAppend; myAppend = 0; }
2576       return res;
2577     }
2578     /// ~
2579     ~_Iterator()
2580     { delete myIt; }
2581     ///
2582     SMESH_subMesh                 *myAppend, *myCur;
2583     SMDS_Iterator<SMESH_subMesh*> *myIt;
2584   };
2585 }
2586
2587 //================================================================================
2588 /*!
2589  * \brief  Return iterator on the submeshes this one depends on
2590   * \param includeSelf - this submesh to be returned also
2591   * \param reverse - if true, complex shape submeshes go first
2592  */
2593 //================================================================================
2594
2595 SMESH_subMeshIteratorPtr SMESH_subMesh::getDependsOnIterator(const bool includeSelf,
2596                                                              const bool reverse) const
2597 {
2598   SMESH_subMesh *me = (SMESH_subMesh*) this;
2599   SMESH_subMesh *prepend=0, *append=0;
2600   if ( includeSelf ) {
2601     if ( reverse ) prepend = me;
2602     else            append = me;
2603   }
2604   typedef map < int, SMESH_subMesh * > TMap;
2605   if ( reverse )
2606   {
2607     return SMESH_subMeshIteratorPtr
2608       ( new _Iterator( new SMDS_mapReverseIterator<TMap>( me->DependsOn() ), prepend, append ));
2609   }
2610   {
2611     return SMESH_subMeshIteratorPtr
2612       ( new _Iterator( new SMDS_mapIterator<TMap>( me->DependsOn() ), prepend, append ));
2613   }
2614 }
2615
2616 //================================================================================
2617 /*!
2618  * \brief Returns ancestor sub-meshes. Finds them if not yet found.
2619  */
2620 //================================================================================
2621
2622 const std::vector< SMESH_subMesh * > & SMESH_subMesh::GetAncestors() const
2623 {
2624   if ( _ancestors.empty() &&
2625        !_subShape.IsSame( _father->GetShapeToMesh() ))
2626   {
2627     const TopTools_ListOfShape& ancShapes = _father->GetAncestors( _subShape );
2628
2629     SMESH_subMesh* me = const_cast< SMESH_subMesh* >( this );
2630     me->_ancestors.reserve( ancShapes.Extent() );
2631
2632     TopTools_MapOfShape map;
2633    
2634     for ( TopTools_ListIteratorOfListOfShape it( ancShapes ); it.More(); it.Next() )
2635       if ( SMESH_subMesh* sm = _father->GetSubMeshContaining( it.Value() ))
2636         if ( map.Add( it.Value() ))
2637           me->_ancestors.push_back( sm );
2638   }
2639
2640   return _ancestors;
2641 }
2642
2643 //================================================================================
2644 /*!
2645  * \brief Clears the vector of ancestor sub-meshes
2646  */
2647 //================================================================================
2648
2649 void SMESH_subMesh::ClearAncestors()
2650 {
2651   _ancestors.clear();
2652 }
2653
2654 //================================================================================
2655 /*!
2656  * \brief  Find common submeshes (based on shared sub-shapes with other
2657   * \param theOther submesh to check
2658   * \param theSetOfCommon set of common submesh
2659  */
2660 //================================================================================
2661
2662 bool SMESH_subMesh::FindIntersection(const SMESH_subMesh* theOther,
2663                                      std::set<const SMESH_subMesh*>& theSetOfCommon ) const
2664 {
2665   int oldNb = theSetOfCommon.size();
2666   // check main submeshes
2667   const map <int, SMESH_subMesh*>::const_iterator otherEnd = theOther->_mapDepend.end();
2668   if ( theOther->_mapDepend.find(this->GetId()) != otherEnd )
2669     theSetOfCommon.insert( this );
2670   if ( _mapDepend.find(theOther->GetId()) != _mapDepend.end() )
2671     theSetOfCommon.insert( theOther );
2672   // check common submeshes
2673   map <int, SMESH_subMesh*>::const_iterator mapIt = _mapDepend.begin();
2674   for( ; mapIt != _mapDepend.end(); mapIt++ )
2675     if ( theOther->_mapDepend.find((*mapIt).first) != otherEnd )
2676       theSetOfCommon.insert( (*mapIt).second );
2677   return oldNb < theSetOfCommon.size();
2678 }