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