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