Salome HOME
+ // commented for issue 0020557, other related ones: 0020526, PAL19080
[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       // IPAL21346. Edges not removed when Netgen 1d-2d is removed from a SOLID.
950       // CLEAN was not called at event REMOVE_ALGO because the algo is not applicable to SOLID.
951       algo = dynamic_cast<SMESH_Algo*> (anHyp);
952       if (!algo->NeedDescretBoundary())
953         needFullClean = true;
954
955       algo = gen->GetAlgo((*_father), _subShape);
956       if (algo == NULL)  // no more applying algo on father
957       {
958         SetAlgoState(NO_ALGO);
959       }
960       else
961       {
962         if ( algo->CheckHypothesis((*_father),_subShape, aux_ret )) {
963           // check if algo changes
964           if ( string(algo->GetName()) != string( anHyp->GetName()) )
965             modifiedHyp = true;
966         }
967         else
968           SetAlgoState(MISSING_HYP);
969       }
970       break;
971     }
972     default:
973       ASSERT(0);
974       break;
975     }
976     break;
977
978     // ----------------------------------------------------------------------
979
980   default:
981     ASSERT(0);
982     break;
983   }
984
985   // detect algorithm hiding
986   //
987   if ( ret == SMESH_Hypothesis::HYP_OK &&
988        ( event == ADD_ALGO || event == ADD_FATHER_ALGO ) &&
989        algo->GetName() == anHyp->GetName() )
990   {
991     // is algo hidden?
992     SMESH_Gen* gen = _father->GetGen();
993     TopTools_ListIteratorOfListOfShape it( _father->GetAncestors( _subShape ));
994     for ( ; ( ret == SMESH_Hypothesis::HYP_OK && it.More()); it.Next() ) {
995       if ( SMESH_Algo* upperAlgo = gen->GetAlgo( *_father, it.Value() ))
996         if ( !upperAlgo->NeedDescretBoundary() && !upperAlgo->SupportSubmeshes())
997           ret = SMESH_Hypothesis::HYP_HIDDEN_ALGO;
998     }
999     // is algo hiding?
1000     if ( ret == SMESH_Hypothesis::HYP_OK &&
1001          !algo->NeedDescretBoundary()    &&
1002          !algo->SupportSubmeshes()) {
1003       map<int, SMESH_subMesh*>::reverse_iterator i_sm = _mapDepend.rbegin();
1004       for ( ; ( ret == SMESH_Hypothesis::HYP_OK && i_sm != _mapDepend.rend()) ; ++i_sm )
1005         if ( gen->GetAlgo( *_father, i_sm->second->_subShape ))
1006           ret = SMESH_Hypothesis::HYP_HIDING_ALGO;
1007     }
1008   }
1009
1010   bool stateChange = ( _algoState != oldAlgoState );
1011
1012   if ( stateChange && _algoState == HYP_OK ) // hyp becomes OK
1013     algo->SetEventListener( this );
1014
1015   NotifyListenersOnEvent( event, ALGO_EVENT, anHyp );
1016
1017   if ( stateChange && oldAlgoState == HYP_OK ) { // hyp becomes KO
1018     DeleteOwnListeners();
1019     SetIsAlwaysComputed( false );
1020     if (_subShape.ShapeType() == TopAbs_VERTEX ) {
1021       // restore default states
1022       _algoState = HYP_OK;
1023       _computeState = READY_TO_COMPUTE;
1024     }
1025   }
1026
1027   if ( needFullClean ) {
1028     // added or removed algo is all-dimensional
1029     ComputeStateEngine( CLEAN );
1030     CleanDependsOn();
1031     ComputeSubMeshStateEngine( CHECK_COMPUTE_STATE );
1032   }
1033
1034   if (stateChange || modifiedHyp)
1035     ComputeStateEngine(MODIF_ALGO_STATE);
1036
1037   return ret;
1038 }
1039
1040 //=======================================================================
1041 //function : IsConform
1042 //purpose  : check if a conform mesh will be produced by the Algo
1043 //=======================================================================
1044
1045 bool SMESH_subMesh::IsConform(const SMESH_Algo* theAlgo)
1046 {
1047 //  MESSAGE( "SMESH_subMesh::IsConform" );
1048   if ( !theAlgo ) return false;
1049
1050   // Suppose that theAlgo is applicable to _subShape, do not check it here
1051   //if ( !IsApplicableHypotesis( theAlgo )) return false;
1052
1053   // check only algo that doesn't NeedDescretBoundary(): because mesh made
1054   // on a sub-shape will be ignored by theAlgo
1055   if ( theAlgo->NeedDescretBoundary() ||
1056        !theAlgo->OnlyUnaryInput() ) // all adjacent shapes will be meshed by this algo?
1057     return true;
1058
1059   SMESH_Gen* gen =_father->GetGen();
1060
1061   // only local algo is to be checked
1062   //if ( gen->IsGlobalHypothesis( theAlgo, *_father ))
1063   if ( _subShape.ShapeType() == _father->GetMeshDS()->ShapeToMesh().ShapeType() )
1064     return true;
1065
1066   // check algo attached to adjacent shapes
1067
1068   // loop on one level down sub-meshes
1069   TopoDS_Iterator itsub( _subShape );
1070   for (; itsub.More(); itsub.Next())
1071   {
1072     // loop on adjacent subShapes
1073     TopTools_ListIteratorOfListOfShape it( _father->GetAncestors( itsub.Value() ));
1074     for (; it.More(); it.Next())
1075     {
1076       const TopoDS_Shape& adjacent = it.Value();
1077       if ( _subShape.IsSame( adjacent )) continue;
1078       if ( adjacent.ShapeType() != _subShape.ShapeType())
1079         break;
1080
1081       // check algo attached to smAdjacent
1082       SMESH_Algo * algo = gen->GetAlgo((*_father), adjacent);
1083       if (algo &&
1084           !algo->NeedDescretBoundary() &&
1085           algo->OnlyUnaryInput())
1086         return false; // NOT CONFORM MESH WILL BE PRODUCED
1087     }
1088   }
1089
1090   return true;
1091 }
1092
1093 //=============================================================================
1094 /*!
1095  *
1096  */
1097 //=============================================================================
1098
1099 void SMESH_subMesh::SetAlgoState(int state)
1100 {
1101   _algoState = state;
1102 }
1103
1104 //=============================================================================
1105 /*!
1106  *
1107  */
1108 //=============================================================================
1109 SMESH_Hypothesis::Hypothesis_Status
1110   SMESH_subMesh::SubMeshesAlgoStateEngine(int event,
1111                                           SMESH_Hypothesis * anHyp)
1112 {
1113   SMESH_Hypothesis::Hypothesis_Status ret = SMESH_Hypothesis::HYP_OK;
1114   //EAP: a wire (dim==1) should notify edges (dim==1)
1115   //EAP: int dim = SMESH_Gen::GetShapeDim(_subShape);
1116   //if (_subShape.ShapeType() < TopAbs_EDGE ) // wire,face etc
1117   {
1118     SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,false);
1119     while ( smIt->more() ) {
1120       SMESH_Hypothesis::Hypothesis_Status ret2 =
1121         smIt->next()->AlgoStateEngine(event, anHyp);
1122       if ( ret2 > ret )
1123         ret = ret2;
1124     }
1125   }
1126   return ret;
1127 }
1128
1129 //=============================================================================
1130 /*!
1131  *
1132  */
1133 //=============================================================================
1134
1135 void SMESH_subMesh::CleanDependsOn()
1136 {
1137   SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,false);
1138   while ( smIt->more() )
1139     smIt->next()->ComputeStateEngine(CLEAN);
1140 }
1141
1142 //=============================================================================
1143 /*!
1144  *
1145  */
1146 //=============================================================================
1147
1148 void SMESH_subMesh::DumpAlgoState(bool isMain)
1149 {
1150         int dim = SMESH_Gen::GetShapeDim(_subShape);
1151 //   if (dim < 1) return;
1152         if (isMain)
1153         {
1154                 const map < int, SMESH_subMesh * >&subMeshes = DependsOn();
1155
1156                 map < int, SMESH_subMesh * >::const_iterator itsub;
1157                 for (itsub = subMeshes.begin(); itsub != subMeshes.end(); itsub++)
1158                 {
1159                         SMESH_subMesh *sm = (*itsub).second;
1160                         sm->DumpAlgoState(false);
1161                 }
1162         }
1163         int type = _subShape.ShapeType();
1164         MESSAGE("dim = " << dim << " type of shape " << type);
1165         switch (_algoState)
1166         {
1167         case NO_ALGO:
1168                 MESSAGE(" AlgoState = NO_ALGO");
1169                 break;
1170         case MISSING_HYP:
1171                 MESSAGE(" AlgoState = MISSING_HYP");
1172                 break;
1173         case HYP_OK:
1174                 MESSAGE(" AlgoState = HYP_OK");
1175                 break;
1176         }
1177         switch (_computeState)
1178         {
1179         case NOT_READY:
1180                 MESSAGE(" ComputeState = NOT_READY");
1181                 break;
1182         case READY_TO_COMPUTE:
1183                 MESSAGE(" ComputeState = READY_TO_COMPUTE");
1184                 break;
1185         case COMPUTE_OK:
1186                 MESSAGE(" ComputeState = COMPUTE_OK");
1187                 break;
1188         case FAILED_TO_COMPUTE:
1189                 MESSAGE(" ComputeState = FAILED_TO_COMPUTE");
1190                 break;
1191         }
1192 }
1193
1194 //================================================================================
1195 /*!
1196  * \brief Remove nodes and elements bound to submesh
1197   * \param subMesh - submesh containing nodes and elements
1198  */
1199 //================================================================================
1200
1201 static void cleanSubMesh( SMESH_subMesh * subMesh )
1202 {
1203   if (subMesh) {
1204     if (SMESHDS_SubMesh * subMeshDS = subMesh->GetSubMeshDS()) {
1205       SMESHDS_Mesh * meshDS = subMesh->GetFather()->GetMeshDS();
1206       SMDS_ElemIteratorPtr ite = subMeshDS->GetElements();
1207       while (ite->more()) {
1208         const SMDS_MeshElement * elt = ite->next();
1209         //MESSAGE( " RM elt: "<<elt->GetID()<<" ( "<<elt->NbNodes()<<" )" );
1210         //meshDS->RemoveElement(elt);
1211         meshDS->RemoveFreeElement(elt, subMeshDS);
1212       }
1213
1214       SMDS_NodeIteratorPtr itn = subMeshDS->GetNodes();
1215       while (itn->more()) {
1216         const SMDS_MeshNode * node = itn->next();
1217         //MESSAGE( " RM node: "<<node->GetID());
1218         if ( node->NbInverseElements() == 0 )
1219           meshDS->RemoveFreeNode(node, subMeshDS);
1220         else // for StdMeshers_CompositeSegment_1D: node in one submesh, edge in another
1221           meshDS->RemoveNode(node);
1222       }
1223     }
1224   }
1225 }
1226
1227 //=============================================================================
1228 /*!
1229  *
1230  */
1231 //=============================================================================
1232
1233 bool SMESH_subMesh::ComputeStateEngine(int event)
1234 {
1235   _computeError.reset();
1236
1237   //MESSAGE("SMESH_subMesh::ComputeStateEngine");
1238   //SCRUTE(_computeState);
1239   //SCRUTE(event);
1240
1241   if (_subShape.ShapeType() == TopAbs_VERTEX)
1242   {
1243     _computeState = READY_TO_COMPUTE;
1244     SMESHDS_SubMesh* smDS = GetSubMeshDS();
1245     if ( smDS && smDS->NbNodes() ) {
1246       if ( event == CLEAN ) {
1247         CleanDependants();
1248         cleanSubMesh( this );
1249       }
1250       else
1251         _computeState = COMPUTE_OK;
1252     }
1253     else if ( event == COMPUTE && !_alwaysComputed ) {
1254       const TopoDS_Vertex & V = TopoDS::Vertex( _subShape );
1255       gp_Pnt P = BRep_Tool::Pnt(V);
1256       if ( SMDS_MeshNode * n = _father->GetMeshDS()->AddNode(P.X(), P.Y(), P.Z()) ) {
1257         _father->GetMeshDS()->SetNodeOnVertex(n,_Id);
1258         _computeState = COMPUTE_OK;
1259       }
1260     }
1261     if ( event == MODIF_ALGO_STATE )
1262       CleanDependants();
1263     return true;
1264   }
1265   SMESH_Gen *gen = _father->GetGen();
1266   SMESH_Algo *algo = 0;
1267   bool ret = true;
1268   SMESH_Hypothesis::Hypothesis_Status hyp_status;
1269   //algo_state oldAlgoState = (algo_state) GetAlgoState();
1270
1271   switch (_computeState)
1272   {
1273
1274     // ----------------------------------------------------------------------
1275
1276   case NOT_READY:
1277     switch (event)
1278     {
1279     case MODIF_ALGO_STATE:
1280       algo = gen->GetAlgo((*_father), _subShape);
1281       if (algo && !algo->NeedDescretBoundary())
1282         CleanDependsOn(); // clean sub-meshes with event CLEAN
1283       if ( _algoState == HYP_OK )
1284         _computeState = READY_TO_COMPUTE;
1285       break;
1286     case COMPUTE:               // nothing to do
1287       break;
1288     case CLEAN:
1289       CleanDependants();
1290       RemoveSubMeshElementsAndNodes();
1291       break;
1292     case SUBMESH_COMPUTED:      // nothing to do
1293       break;
1294     case SUBMESH_RESTORED:
1295       ComputeSubMeshStateEngine( SUBMESH_RESTORED );
1296       break;
1297     case MESH_ENTITY_REMOVED:
1298       break;
1299     case CHECK_COMPUTE_STATE:
1300       if ( IsMeshComputed() )
1301         _computeState = COMPUTE_OK;
1302       break;
1303     default:
1304       ASSERT(0);
1305       break;
1306     }
1307     break;
1308
1309     // ----------------------------------------------------------------------
1310
1311   case READY_TO_COMPUTE:
1312     switch (event)
1313     {
1314     case MODIF_ALGO_STATE:
1315       _computeState = NOT_READY;
1316       algo = gen->GetAlgo((*_father), _subShape);
1317       if (algo)
1318       {
1319         if (!algo->NeedDescretBoundary())
1320           CleanDependsOn(); // clean sub-meshes with event CLEAN
1321         if ( _algoState == HYP_OK )
1322           _computeState = READY_TO_COMPUTE;
1323       }
1324       break;
1325     case COMPUTE:
1326       {
1327         algo = gen->GetAlgo((*_father), _subShape);
1328         ASSERT(algo);
1329         ret = algo->CheckHypothesis((*_father), _subShape, hyp_status);
1330         if (!ret)
1331         {
1332           MESSAGE("***** verify compute state *****");
1333           _computeState = NOT_READY;
1334           SetAlgoState(MISSING_HYP);
1335           break;
1336         }
1337         TopoDS_Shape shape = _subShape;
1338         // check submeshes needed
1339         if (_father->HasShapeToMesh() ) {
1340           bool subComputed = false;
1341           if (!algo->OnlyUnaryInput())
1342             shape = GetCollection( gen, algo, subComputed );
1343           else
1344             subComputed = SubMeshesComputed();
1345           ret = ( algo->NeedDescretBoundary() ? subComputed :
1346                   algo->SupportSubmeshes() ? true :
1347                   ( !subComputed || _father->IsNotConformAllowed() ));
1348           if (!ret) {
1349             _computeState = FAILED_TO_COMPUTE;
1350             if ( !algo->NeedDescretBoundary() )
1351               _computeError =
1352                 SMESH_ComputeError::New(COMPERR_BAD_INPUT_MESH,
1353                                         "Unexpected computed submesh",algo);
1354             break;
1355           }
1356         }
1357         // compute
1358 //         CleanDependants(); for "UseExisting_*D" algos
1359 //         RemoveSubMeshElementsAndNodes();
1360         ret = false;
1361         _computeState = FAILED_TO_COMPUTE;
1362         _computeError = SMESH_ComputeError::New(COMPERR_OK,"",algo);
1363         try {
1364 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
1365           OCC_CATCH_SIGNALS;
1366 #endif
1367           algo->InitComputeError();
1368           MemoryReserve aMemoryReserve;
1369           SMDS_Mesh::CheckMemory();
1370           if ( !_father->HasShapeToMesh() ) // no shape
1371           {
1372             SMESH_MesherHelper helper( *_father );
1373             helper.SetSubShape( shape );
1374             helper.SetElementsOnShape( true );
1375             ret = algo->Compute(*_father, &helper );
1376           }
1377           else
1378           {
1379             ret = algo->Compute((*_father), shape);
1380           }
1381           if ( !_computeError || ( !ret && _computeError->IsOK() ) ) // algo can set _computeError of submesh
1382             _computeError = algo->GetComputeError();
1383         }
1384         catch ( std::bad_alloc& exc ) {
1385           MESSAGE("std::bad_alloc thrown inside algo->Compute()");
1386           if ( _computeError ) {
1387             _computeError->myName = COMPERR_MEMORY_PB;
1388             //_computeError->myComment = exc.what();
1389           }
1390           cleanSubMesh( this );
1391           throw exc;
1392         }
1393         catch ( Standard_OutOfMemory& exc ) {
1394           MESSAGE("Standard_OutOfMemory thrown inside algo->Compute()");
1395           if ( _computeError ) {
1396             _computeError->myName = COMPERR_MEMORY_PB;
1397             //_computeError->myComment = exc.what();
1398           }
1399           cleanSubMesh( this );
1400           throw std::bad_alloc();
1401         }
1402         catch (Standard_Failure& ex) {
1403           if ( !_computeError ) _computeError = SMESH_ComputeError::New();
1404           _computeError->myName    = COMPERR_OCC_EXCEPTION;
1405           _computeError->myComment += ex.DynamicType()->Name();
1406           if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
1407             _computeError->myComment += ": ";
1408             _computeError->myComment += ex.GetMessageString();
1409           }
1410         }
1411         catch ( SALOME_Exception& S_ex ) {
1412           if ( !_computeError ) _computeError = SMESH_ComputeError::New();
1413           _computeError->myName    = COMPERR_SLM_EXCEPTION;
1414           _computeError->myComment = S_ex.what();
1415         }
1416         catch ( std::exception& exc ) {
1417           if ( !_computeError ) _computeError = SMESH_ComputeError::New();
1418           _computeError->myName    = COMPERR_STD_EXCEPTION;
1419           _computeError->myComment = exc.what();
1420         }
1421         catch ( ... ) {
1422           if ( _computeError )
1423             _computeError->myName = COMPERR_EXCEPTION;
1424           else
1425             ret = false;
1426         }
1427         if (ret && !_alwaysComputed && shape == _subShape) { // check if anything was built
1428           ret = ( GetSubMeshDS() && ( GetSubMeshDS()->NbElements() || GetSubMeshDS()->NbNodes() ));
1429         }
1430         bool isComputeErrorSet = !CheckComputeError( algo, shape );
1431         if (!ret && !isComputeErrorSet)
1432         {
1433           // Set _computeError
1434           if ( !_computeError )
1435             _computeError = SMESH_ComputeError::New();
1436           if ( _computeError->IsOK() )
1437             _computeError->myName = COMPERR_ALGO_FAILED;
1438           _computeState = FAILED_TO_COMPUTE;
1439         }
1440         if (ret)
1441         {
1442           _computeError.reset();
1443         }
1444         UpdateDependantsState( SUBMESH_COMPUTED ); // send event SUBMESH_COMPUTED
1445       }
1446       break;
1447     case CLEAN:
1448       CleanDependants();
1449       RemoveSubMeshElementsAndNodes();
1450       _computeState = NOT_READY;
1451       algo = gen->GetAlgo((*_father), _subShape);
1452       if (algo)
1453       {
1454         ret = algo->CheckHypothesis((*_father), _subShape, hyp_status);
1455         if (ret)
1456           _computeState = READY_TO_COMPUTE;
1457         else
1458           SetAlgoState(MISSING_HYP);
1459       }
1460       break;
1461     case SUBMESH_COMPUTED:      // nothing to do
1462       break;
1463     case SUBMESH_RESTORED:
1464       // check if a mesh is already computed that may
1465       // happen after retrieval from a file
1466       ComputeStateEngine( CHECK_COMPUTE_STATE );
1467       ComputeSubMeshStateEngine( SUBMESH_RESTORED );
1468       algo = gen->GetAlgo(*_father, _subShape);
1469       if (algo) algo->SubmeshRestored( this );
1470       break;
1471     case MESH_ENTITY_REMOVED:
1472       break;
1473     case CHECK_COMPUTE_STATE:
1474       if ( IsMeshComputed() )
1475         _computeState = COMPUTE_OK;
1476       break;
1477     default:
1478       ASSERT(0);
1479       break;
1480     }
1481     break;
1482
1483     // ----------------------------------------------------------------------
1484
1485   case COMPUTE_OK:
1486     switch (event)
1487     {
1488     case MODIF_ALGO_STATE:
1489       ComputeStateEngine( CLEAN );
1490       algo = gen->GetAlgo((*_father), _subShape);
1491       if (algo && !algo->NeedDescretBoundary())
1492         CleanDependsOn(); // clean sub-meshes with event CLEAN
1493       break;
1494     case COMPUTE:               // nothing to do
1495       break;
1496     case CLEAN:
1497       CleanDependants();  // clean sub-meshes, dependant on this one, with event CLEAN
1498       RemoveSubMeshElementsAndNodes();
1499       _computeState = NOT_READY;
1500       if ( _algoState == HYP_OK )
1501         _computeState = READY_TO_COMPUTE;
1502       break;
1503     case SUBMESH_COMPUTED:      // nothing to do
1504       break;
1505     case SUBMESH_RESTORED:
1506       ComputeStateEngine( CHECK_COMPUTE_STATE );
1507       ComputeSubMeshStateEngine( SUBMESH_RESTORED );
1508       algo = gen->GetAlgo(*_father, _subShape);
1509       if (algo) algo->SubmeshRestored( this );
1510       break;
1511     case MESH_ENTITY_REMOVED:
1512       UpdateDependantsState( CHECK_COMPUTE_STATE );
1513       ComputeStateEngine( CHECK_COMPUTE_STATE );
1514       ComputeSubMeshStateEngine( CHECK_COMPUTE_STATE );
1515       break;
1516     case CHECK_COMPUTE_STATE:
1517       if ( !IsMeshComputed() )
1518         if (_algoState == HYP_OK)
1519           _computeState = READY_TO_COMPUTE;
1520         else
1521           _computeState = NOT_READY;
1522       break;
1523     default:
1524       ASSERT(0);
1525       break;
1526     }
1527     break;
1528
1529     // ----------------------------------------------------------------------
1530
1531   case FAILED_TO_COMPUTE:
1532     switch (event)
1533     {
1534     case MODIF_ALGO_STATE:
1535       algo = gen->GetAlgo((*_father), _subShape);
1536       if (algo && !algo->NeedDescretBoundary())
1537         CleanDependsOn(); // clean sub-meshes with event CLEAN
1538       if (_algoState == HYP_OK)
1539         _computeState = READY_TO_COMPUTE;
1540       else
1541         _computeState = NOT_READY;
1542       break;
1543     case COMPUTE:      // nothing to do
1544       break;
1545     case CLEAN:
1546       CleanDependants(); // submeshes dependent on me should be cleaned as well
1547       RemoveSubMeshElementsAndNodes();
1548       break;
1549     case SUBMESH_COMPUTED:      // allow retry compute
1550       if (_algoState == HYP_OK)
1551         _computeState = READY_TO_COMPUTE;
1552       else
1553         _computeState = NOT_READY;
1554       break;
1555     case SUBMESH_RESTORED:
1556       ComputeSubMeshStateEngine( SUBMESH_RESTORED );
1557       break;
1558     case MESH_ENTITY_REMOVED:
1559       break;
1560     case CHECK_COMPUTE_STATE:
1561       if ( IsMeshComputed() )
1562         _computeState = COMPUTE_OK;
1563       else
1564         if (_algoState == HYP_OK)
1565           _computeState = READY_TO_COMPUTE;
1566         else
1567           _computeState = NOT_READY;
1568       break;
1569     default:
1570       ASSERT(0);
1571       break;
1572     }
1573     break;
1574
1575     // ----------------------------------------------------------------------
1576   default:
1577     ASSERT(0);
1578     break;
1579   }
1580
1581   NotifyListenersOnEvent( event, COMPUTE_EVENT );
1582
1583   return ret;
1584 }
1585
1586 //=======================================================================
1587 /*!
1588  * \brief Update compute_state by _computeError and send proper events to
1589  * dependent submeshes
1590   * \retval bool - true if _computeError is NOT set
1591  */
1592 //=======================================================================
1593
1594 bool SMESH_subMesh::CheckComputeError(SMESH_Algo* theAlgo, const TopoDS_Shape& theShape)
1595 {
1596   bool noErrors = true;
1597
1598   if ( !theShape.IsNull() )
1599   {
1600     // Check state of submeshes
1601     if ( !theAlgo->NeedDescretBoundary())
1602     {
1603       SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,false);
1604       while ( smIt->more() )
1605         if ( !smIt->next()->CheckComputeError( theAlgo ))
1606           noErrors = false;
1607     }
1608
1609     // Check state of neighbours
1610     if ( !theAlgo->OnlyUnaryInput() &&
1611          theShape.ShapeType() == TopAbs_COMPOUND &&
1612          !theShape.IsSame( _subShape ))
1613     {
1614       for (TopoDS_Iterator subIt( theShape ); subIt.More(); subIt.Next()) {
1615         SMESH_subMesh* sm = _father->GetSubMesh( subIt.Value() );
1616         if ( sm != this ) {
1617           if ( !sm->CheckComputeError( theAlgo, sm->GetSubShape() ))
1618             noErrors = false;
1619           UpdateDependantsState( SUBMESH_COMPUTED ); // send event SUBMESH_COMPUTED
1620         }
1621       }
1622     }
1623   }
1624   {
1625     // Check my state
1626     if ( !_computeError || _computeError->IsOK() )
1627     {
1628       _computeState = COMPUTE_OK;
1629     }
1630     else
1631     {
1632       if ( !_computeError->myAlgo )
1633         _computeError->myAlgo = theAlgo;
1634
1635       // Show error
1636       SMESH_Comment text;
1637       text << theAlgo->GetName() << " failed on subshape #" << _Id << " with error ";
1638       if (_computeError->IsCommon() )
1639         text << _computeError->CommonName();
1640       else
1641         text << _computeError->myName;
1642       if ( _computeError->myComment.size() > 0 )
1643         text << " \"" << _computeError->myComment << "\"";
1644
1645 #ifdef _DEBUG_
1646       MESSAGE_BEGIN ( text );
1647       // Show vertices location of a failed shape
1648       TopTools_IndexedMapOfShape vMap;
1649       TopExp::MapShapes( _subShape, TopAbs_VERTEX, vMap );
1650       MESSAGE_ADD ( "Subshape vertices " << ( vMap.Extent()>10 ? "(first 10):" : ":") );
1651       for ( int iv = 1; iv <= vMap.Extent() && iv < 11; ++iv ) {
1652         gp_Pnt P( BRep_Tool::Pnt( TopoDS::Vertex( vMap( iv ) )));
1653         MESSAGE_ADD ( "#" << _father->GetMeshDS()->ShapeToIndex( vMap( iv )) << " "
1654                    << P.X() << " " << P.Y() << " " << P.Z() << " " );
1655       }
1656 #else
1657       INFOS( text );
1658 #endif
1659       _computeState = FAILED_TO_COMPUTE;
1660       noErrors = false;
1661     }
1662   }
1663   return noErrors;
1664 }
1665
1666 //=======================================================================
1667 //function : ApplyToCollection
1668 //purpose  : Apply theAlgo to all subshapes in theCollection
1669 //=======================================================================
1670
1671 bool SMESH_subMesh::ApplyToCollection (SMESH_Algo*         theAlgo,
1672                                        const TopoDS_Shape& theCollection)
1673 {
1674   MESSAGE("SMESH_subMesh::ApplyToCollection");
1675   ASSERT ( !theAlgo->NeedDescretBoundary() );
1676
1677   if ( _computeError )
1678     _computeError->myName = COMPERR_OK;
1679
1680   bool ok = theAlgo->Compute( *_father, theCollection );
1681
1682   // set _computeState of subshapes
1683   TopExp_Explorer anExplorer( theCollection, _subShape.ShapeType() );
1684   for ( ; anExplorer.More(); anExplorer.Next() )
1685   {
1686     if ( SMESH_subMesh* subMesh = _father->GetSubMeshContaining( anExplorer.Current() ))
1687     {
1688       bool localOK = subMesh->CheckComputeError( theAlgo );
1689       if ( !ok && localOK && !subMesh->IsMeshComputed() )
1690       {
1691         subMesh->_computeError = theAlgo->GetComputeError();
1692         if ( subMesh->_computeError->IsOK() )
1693           _computeError = SMESH_ComputeError::New(COMPERR_ALGO_FAILED);
1694         localOK = CheckComputeError( theAlgo );
1695       }
1696       if ( localOK )
1697         subMesh->UpdateDependantsState( SUBMESH_COMPUTED );
1698       subMesh->UpdateSubMeshState( localOK ? COMPUTE_OK : FAILED_TO_COMPUTE );
1699     }
1700   }
1701
1702   return true;
1703 }
1704
1705
1706 //=======================================================================
1707 //function : UpdateSubMeshState
1708 //purpose  :
1709 //=======================================================================
1710
1711 void SMESH_subMesh::UpdateSubMeshState(const compute_state theState)
1712 {
1713   SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,false);
1714   while ( smIt->more() )
1715     smIt->next()->_computeState = theState;
1716 }
1717
1718 //=======================================================================
1719 //function : ComputeSubMeshStateEngine
1720 //purpose  :
1721 //=======================================================================
1722
1723 void SMESH_subMesh::ComputeSubMeshStateEngine(int event)
1724 {
1725   SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,false);
1726   while ( smIt->more() )
1727     smIt->next()->ComputeStateEngine(event);
1728 }
1729
1730 //=======================================================================
1731 //function : UpdateDependantsState
1732 //purpose  :
1733 //=======================================================================
1734
1735 void SMESH_subMesh::UpdateDependantsState(const compute_event theEvent)
1736 {
1737   //MESSAGE("SMESH_subMesh::UpdateDependantsState");
1738   TopTools_ListIteratorOfListOfShape it( _father->GetAncestors( _subShape ));
1739   for (; it.More(); it.Next())
1740   {
1741     const TopoDS_Shape& ancestor = it.Value();
1742     SMESH_subMesh *aSubMesh =
1743       _father->GetSubMeshContaining(ancestor);
1744     if (aSubMesh)
1745       aSubMesh->ComputeStateEngine( theEvent );
1746   }
1747 }
1748
1749 //=============================================================================
1750 /*!
1751  *
1752  */
1753 //=============================================================================
1754
1755 void SMESH_subMesh::CleanDependants()
1756 {
1757   int dimToClean = SMESH_Gen::GetShapeDim( _subShape ) + 1;
1758
1759   TopTools_ListIteratorOfListOfShape it( _father->GetAncestors( _subShape ));
1760   for (; it.More(); it.Next())
1761   {
1762     const TopoDS_Shape& ancestor = it.Value();
1763     if ( SMESH_Gen::GetShapeDim( ancestor ) == dimToClean ) {
1764       // PAL8021. do not go upper than SOLID, else ComputeStateEngine(CLEAN)
1765       // will erase mesh on other shapes in a compound
1766       if ( ancestor.ShapeType() >= TopAbs_SOLID ) {
1767         SMESH_subMesh *aSubMesh = _father->GetSubMeshContaining(ancestor);
1768         if (aSubMesh)
1769           aSubMesh->ComputeStateEngine(CLEAN);
1770       }
1771     }
1772   }
1773 }
1774
1775 //=============================================================================
1776 /*!
1777  *
1778  */
1779 //=============================================================================
1780
1781 void SMESH_subMesh::RemoveSubMeshElementsAndNodes()
1782 {
1783   //SCRUTE(_subShape.ShapeType());
1784
1785   cleanSubMesh( this );
1786
1787   // algo may bind a submesh not to _subShape, eg 3D algo
1788   // sets nodes on SHELL while _subShape may be SOLID
1789
1790   int dim = SMESH_Gen::GetShapeDim( _subShape );
1791   int type = _subShape.ShapeType() + 1;
1792   for ( ; type <= TopAbs_EDGE; type++) {
1793     if ( dim == SMESH_Gen::GetShapeDim( (TopAbs_ShapeEnum) type ))
1794     {
1795       TopExp_Explorer exp( _subShape, (TopAbs_ShapeEnum) type );
1796       for ( ; exp.More(); exp.Next() )
1797         cleanSubMesh( _father->GetSubMeshContaining( exp.Current() ));
1798     }
1799     else
1800       break;
1801   }
1802 }
1803
1804 //=======================================================================
1805 //function : GetCollection
1806 //purpose  : return a shape containing all sub-shapes of the MainShape that can be
1807 //           meshed at once along with _subShape
1808 //=======================================================================
1809
1810 TopoDS_Shape SMESH_subMesh::GetCollection(SMESH_Gen * theGen,
1811                                           SMESH_Algo* theAlgo,
1812                                           bool &      theSubComputed)
1813 {
1814   MESSAGE("SMESH_subMesh::GetCollection");
1815
1816   theSubComputed = SubMeshesComputed();
1817
1818   TopoDS_Shape mainShape = _father->GetMeshDS()->ShapeToMesh();
1819
1820   if ( mainShape.IsSame( _subShape ))
1821     return _subShape;
1822
1823   const bool ignoreAuxiliaryHyps = false;
1824   list<const SMESHDS_Hypothesis*> aUsedHyp =
1825     theAlgo->GetUsedHypothesis( *_father, _subShape, ignoreAuxiliaryHyps ); // copy
1826
1827   // put in a compound all shapes with the same hypothesis assigned
1828   // and a good ComputState
1829
1830   TopoDS_Compound aCompound;
1831   BRep_Builder aBuilder;
1832   aBuilder.MakeCompound( aCompound );
1833
1834   TopExp_Explorer anExplorer( mainShape, _subShape.ShapeType() );
1835   for ( ; anExplorer.More(); anExplorer.Next() )
1836   {
1837     const TopoDS_Shape& S = anExplorer.Current();
1838     SMESH_subMesh* subMesh = _father->GetSubMesh( S );
1839     if ( subMesh == this )
1840     {
1841       aBuilder.Add( aCompound, S );
1842     }
1843     else if ( subMesh->GetComputeState() == READY_TO_COMPUTE )
1844     {
1845       SMESH_Algo* anAlgo = theGen->GetAlgo( *_father, S );
1846       if (strcmp( anAlgo->GetName(), theAlgo->GetName()) == 0 && // same algo
1847           anAlgo->GetUsedHypothesis( *_father, S, ignoreAuxiliaryHyps ) == aUsedHyp) // same hyps
1848         aBuilder.Add( aCompound, S );
1849       if ( !subMesh->SubMeshesComputed() )
1850         theSubComputed = false;
1851     }
1852   }
1853
1854   return aCompound;
1855 }
1856
1857 //=======================================================================
1858 //function : GetSimilarAttached
1859 //purpose  : return a hypothesis attached to theShape.
1860 //           If theHyp is provided, similar but not same hypotheses
1861 //           is returned; else only applicable ones having theHypType
1862 //           is returned
1863 //=======================================================================
1864
1865 const SMESH_Hypothesis* SMESH_subMesh::GetSimilarAttached(const TopoDS_Shape&      theShape,
1866                                                           const SMESH_Hypothesis * theHyp,
1867                                                           const int                theHypType)
1868 {
1869   SMESH_HypoFilter hypoKind;
1870   hypoKind.Init( hypoKind.HasType( theHyp ? theHyp->GetType() : theHypType ));
1871   if ( theHyp ) {
1872     hypoKind.And   ( hypoKind.HasDim( theHyp->GetDim() ));
1873     hypoKind.AndNot( hypoKind.Is( theHyp ));
1874     if ( theHyp->IsAuxiliary() )
1875       hypoKind.And( hypoKind.HasName( theHyp->GetName() ));
1876     else
1877       hypoKind.AndNot( hypoKind.IsAuxiliary());
1878   }
1879   else {
1880     hypoKind.And( hypoKind.IsApplicableTo( theShape ));
1881   }
1882
1883   return _father->GetHypothesis( theShape, hypoKind, false );
1884 }
1885
1886 //=======================================================================
1887 //function : CheckConcurentHypothesis
1888 //purpose  : check if there are several applicable hypothesis attached to
1889 //           ancestors
1890 //=======================================================================
1891
1892 SMESH_Hypothesis::Hypothesis_Status
1893   SMESH_subMesh::CheckConcurentHypothesis (const int theHypType)
1894 {
1895   MESSAGE ("SMESH_subMesh::CheckConcurentHypothesis");
1896
1897   // is there local hypothesis on me?
1898   if ( GetSimilarAttached( _subShape, 0, theHypType ) )
1899     return SMESH_Hypothesis::HYP_OK;
1900
1901
1902   TopoDS_Shape aPrevWithHyp;
1903   const SMESH_Hypothesis* aPrevHyp = 0;
1904   TopTools_ListIteratorOfListOfShape it( _father->GetAncestors( _subShape ));
1905   for (; it.More(); it.Next())
1906   {
1907     const TopoDS_Shape& ancestor = it.Value();
1908     const SMESH_Hypothesis* hyp = GetSimilarAttached( ancestor, 0, theHypType );
1909     if ( hyp )
1910     {
1911       if ( aPrevWithHyp.IsNull() || aPrevWithHyp.IsSame( ancestor ))
1912       {
1913         aPrevWithHyp = ancestor;
1914         aPrevHyp     = hyp;
1915       }
1916       else if ( aPrevWithHyp.ShapeType() == ancestor.ShapeType() && aPrevHyp != hyp )
1917         return SMESH_Hypothesis::HYP_CONCURENT;
1918       else
1919         return SMESH_Hypothesis::HYP_OK;
1920     }
1921   }
1922   return SMESH_Hypothesis::HYP_OK;
1923 }
1924
1925 //================================================================================
1926 /*!
1927  * \brief Sets an event listener and its data to a submesh
1928  * \param listener - the listener to store
1929  * \param data - the listener data to store
1930  * \param where - the submesh to store the listener and it's data
1931  * \param deleteListener - if true then the listener will be deleted as
1932  *        it is removed from where submesh
1933  * 
1934  * It remembers the submesh where it puts the listener in order to delete
1935  * them when HYP_OK algo_state is lost
1936  * After being set, event listener is notified on each event of where submesh.
1937  */
1938 //================================================================================
1939
1940 void SMESH_subMesh::SetEventListener(EventListener*     listener,
1941                                      EventListenerData* data,
1942                                      SMESH_subMesh*     where)
1943 {
1944   if ( listener && where ) {
1945     where->SetEventListener( listener, data );
1946     myOwnListeners.push_back( make_pair( where, listener ));
1947   }
1948 }
1949
1950 //================================================================================
1951 /*!
1952  * \brief Sets an event listener and its data to a submesh
1953  * \param listener - the listener to store
1954  * \param data - the listener data to store
1955  * 
1956  * After being set, event listener is notified on each event of a submesh.
1957  */
1958 //================================================================================
1959
1960 void SMESH_subMesh::SetEventListener(EventListener* listener, EventListenerData* data)
1961 {
1962   map< EventListener*, EventListenerData* >::iterator l_d =
1963     myEventListeners.find( listener );
1964   if ( l_d != myEventListeners.end() ) {
1965     EventListenerData* curData = l_d->second;
1966     if ( curData && curData != data && curData->IsDeletable() )
1967       delete curData;
1968     l_d->second = data;
1969   }
1970   else 
1971     myEventListeners.insert( make_pair( listener, data ));
1972 }
1973
1974 //================================================================================
1975 /*!
1976  * \brief Return an event listener data
1977  * \param listener - the listener whose data is
1978  * \retval EventListenerData* - found data, maybe NULL
1979  */
1980 //================================================================================
1981
1982 EventListenerData* SMESH_subMesh::GetEventListenerData(EventListener* listener) const
1983 {
1984   map< EventListener*, EventListenerData* >::const_iterator l_d =
1985     myEventListeners.find( listener );
1986   if ( l_d != myEventListeners.end() )
1987     return l_d->second;
1988   return 0;
1989 }
1990
1991 //================================================================================
1992 /*!
1993  * \brief Notify stored event listeners on the occured event
1994  * \param event - algo_event or compute_event itself
1995  * \param eventType - algo_event or compute_event
1996  * \param subMesh - the submesh where the event occures
1997  * \param data - listener data stored in the subMesh
1998  * \param hyp - hypothesis, if eventType is algo_event
1999  */
2000 //================================================================================
2001
2002 void SMESH_subMesh::NotifyListenersOnEvent( const int         event,
2003                                             const event_type  eventType,
2004                                             SMESH_Hypothesis* hyp)
2005 {
2006   map< EventListener*, EventListenerData* >::iterator l_d = myEventListeners.begin();
2007   for ( ; l_d != myEventListeners.end(); ++l_d )
2008     l_d->first->ProcessEvent( event, eventType, this, l_d->second, hyp );
2009 }
2010
2011 //================================================================================
2012 /*!
2013  * \brief Unregister the listener and delete listener's data
2014  * \param listener - the event listener
2015  */
2016 //================================================================================
2017
2018 void SMESH_subMesh::DeleteEventListener(EventListener* listener)
2019 {
2020   map< EventListener*, EventListenerData* >::iterator l_d =
2021     myEventListeners.find( listener );
2022   if ( l_d != myEventListeners.end() ) {
2023     if ( l_d->first  && l_d->first->IsDeletable() )  delete l_d->first;
2024     if ( l_d->second && l_d->second->IsDeletable() ) delete l_d->second;
2025     myEventListeners.erase( l_d );
2026   }
2027 }
2028
2029 //================================================================================
2030 /*!
2031  * \brief Delete event listeners depending on algo of this submesh
2032  */
2033 //================================================================================
2034
2035 void SMESH_subMesh::DeleteOwnListeners()
2036 {
2037   list< pair< SMESH_subMesh*, EventListener* > >::iterator sm_l;
2038   for ( sm_l = myOwnListeners.begin(); sm_l != myOwnListeners.end(); ++sm_l)
2039     sm_l->first->DeleteEventListener( sm_l->second );
2040   myOwnListeners.clear();
2041 }
2042
2043 //================================================================================
2044 /*!
2045  * \brief Do something on a certain event
2046  * \param event - algo_event or compute_event itself
2047  * \param eventType - algo_event or compute_event
2048  * \param subMesh - the submesh where the event occures
2049  * \param data - listener data stored in the subMesh
2050  * \param hyp - hypothesis, if eventType is algo_event
2051  * 
2052  * The base implementation translates CLEAN event to the subMesh
2053  * stored in listener data. Also it sends SUBMESH_COMPUTED event in case of
2054  * successful COMPUTE event.
2055  */
2056 //================================================================================
2057
2058 void SMESH_subMeshEventListener::ProcessEvent(const int          event,
2059                                               const int          eventType,
2060                                               SMESH_subMesh*     subMesh,
2061                                               EventListenerData* data,
2062                                               const SMESH_Hypothesis*  /*hyp*/)
2063 {
2064   if ( data && !data->mySubMeshes.empty() &&
2065        eventType == SMESH_subMesh::COMPUTE_EVENT)
2066   {
2067     ASSERT( data->mySubMeshes.front() != subMesh );
2068     list<SMESH_subMesh*>::iterator smIt = data->mySubMeshes.begin();
2069     list<SMESH_subMesh*>::iterator smEnd = data->mySubMeshes.end();
2070     switch ( event ) {
2071     case SMESH_subMesh::CLEAN:
2072       for ( ; smIt != smEnd; ++ smIt)
2073         (*smIt)->ComputeStateEngine( event );
2074       break;
2075     case SMESH_subMesh::COMPUTE:
2076       if ( subMesh->GetComputeState() == SMESH_subMesh::COMPUTE_OK )
2077         for ( ; smIt != smEnd; ++ smIt)
2078           (*smIt)->ComputeStateEngine( SMESH_subMesh::SUBMESH_COMPUTED );
2079       break;
2080     default:;
2081     }
2082   }
2083 }
2084
2085 namespace {
2086
2087   //================================================================================
2088   /*!
2089    * \brief Iterator over submeshes and optionally prepended or appended one
2090    */
2091   //================================================================================
2092
2093   struct _Iterator : public SMDS_Iterator<SMESH_subMesh*>
2094   {
2095     _Iterator(SMDS_Iterator<SMESH_subMesh*>* subIt,
2096               SMESH_subMesh*                 prepend,
2097               SMESH_subMesh*                 append): myIt(subIt),myAppend(append)
2098     {
2099       myCur = prepend ? prepend : myIt->more() ? myIt->next() : append;
2100       if ( myCur == append ) append = 0;
2101     }
2102     /// Return true if and only if there are other object in this iterator
2103     virtual bool more()
2104     {
2105       return myCur;
2106     }
2107     /// Return the current object and step to the next one
2108     virtual SMESH_subMesh* next()
2109     {
2110       SMESH_subMesh* res = myCur;
2111       if ( myIt->more() ) { myCur = myIt->next(); }
2112       else                { myCur = myAppend; myAppend = 0; }
2113       return res;
2114     }
2115     /// ~
2116     ~_Iterator()
2117     { delete myIt; }
2118     ///
2119     SMESH_subMesh                 *myAppend, *myCur;
2120     SMDS_Iterator<SMESH_subMesh*> *myIt;
2121   };
2122 }
2123
2124 //================================================================================
2125 /*!
2126  * \brief  Return iterator on the submeshes this one depends on
2127   * \param includeSelf - this submesh to be returned also
2128   * \param reverse - if true, complex shape submeshes go first
2129  */
2130 //================================================================================
2131
2132 SMESH_subMeshIteratorPtr SMESH_subMesh::getDependsOnIterator(const bool includeSelf,
2133                                                              const bool reverse)
2134 {
2135   SMESH_subMesh *prepend=0, *append=0;
2136   if ( includeSelf ) {
2137     if ( reverse ) prepend = this;
2138     else            append = this;
2139   }
2140   typedef map < int, SMESH_subMesh * > TMap;
2141   if ( reverse )
2142   {
2143     return SMESH_subMeshIteratorPtr
2144       ( new _Iterator( new SMDS_mapReverseIterator<TMap>( DependsOn() ), prepend, append ));
2145   }
2146   {
2147     return SMESH_subMeshIteratorPtr
2148       ( new _Iterator( new SMDS_mapIterator<TMap>( DependsOn() ), prepend, append ));
2149   }
2150 }