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