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