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