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