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