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