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