Salome HOME
d870ae59f91f1874888803303d87b0bcc9ccb944
[modules/smesh.git] / src / SMESH / SMESH_Mesh.cxx
1 //  SMESH SMESH : implementaion of SMESH idl descriptions
2 //
3 //  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS 
5 // 
6 //  This library is free software; you can redistribute it and/or 
7 //  modify it under the terms of the GNU Lesser General Public 
8 //  License as published by the Free Software Foundation; either 
9 //  version 2.1 of the License. 
10 // 
11 //  This library is distributed in the hope that it will be useful, 
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of 
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
14 //  Lesser General Public License for more details. 
15 // 
16 //  You should have received a copy of the GNU Lesser General Public 
17 //  License along with this library; if not, write to the Free Software 
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA 
19 // 
20 //  See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
21 //
22 //
23 //
24 //  File   : SMESH_Mesh.cxx
25 //  Author : Paul RASCLE, EDF
26 //  Module : SMESH
27 //  $Header$
28
29 #include "SMESH_Mesh.hxx"
30 #include "SMESH_subMesh.hxx"
31 #include "SMESH_Gen.hxx"
32 #include "SMESH_Hypothesis.hxx"
33 #include "SMESH_Group.hxx"
34 #include "SMESH_HypoFilter.hxx"
35 #include "SMESHDS_Group.hxx"
36 #include "SMESHDS_Script.hxx"
37 #include "SMESHDS_GroupOnGeom.hxx"
38 #include "SMDS_MeshVolume.hxx"
39
40 #include "utilities.h"
41
42 #include "DriverMED_W_SMESHDS_Mesh.h"
43 #include "DriverDAT_W_SMDS_Mesh.h"
44 #include "DriverUNV_W_SMDS_Mesh.h"
45 #include "DriverSTL_W_SMDS_Mesh.h"
46
47 #include "DriverMED_R_SMESHDS_Mesh.h"
48 #include "DriverUNV_R_SMDS_Mesh.h"
49 #include "DriverSTL_R_SMDS_Mesh.h"
50
51 #include <BRepTools_WireExplorer.hxx>
52 #include <BRep_Builder.hxx>
53 #include <gp_Pnt.hxx>
54
55 #include <TCollection_AsciiString.hxx>
56 #include <TopExp.hxx>
57 #include <TopTools_ListOfShape.hxx>
58 #include <TopTools_Array1OfShape.hxx>
59 #include <TopTools_ListIteratorOfListOfShape.hxx>
60 #include <TopTools_MapOfShape.hxx>
61
62 #include <memory>
63
64 #include "Utils_ExceptHandlers.hxx"
65
66 // maximum stored group name length in MED file
67 #define MAX_MED_GROUP_NAME_LENGTH 80
68
69 #ifdef _DEBUG_
70 static int MYDEBUG = 0;
71 #else
72 static int MYDEBUG = 0;
73 #endif
74
75
76 //=============================================================================
77 /*!
78  * 
79  */
80 //=============================================================================
81
82 SMESH_Mesh::SMESH_Mesh(int theLocalId, 
83                        int theStudyId, 
84                        SMESH_Gen* theGen,
85                        bool theIsEmbeddedMode,
86                        SMESHDS_Document* theDocument):
87   _groupId( 0 )
88 {
89   INFOS("SMESH_Mesh::SMESH_Mesh(int localId)");
90   _id = theLocalId;
91   _studyId = theStudyId;
92   _gen = theGen;
93   _myDocument = theDocument;
94   _idDoc = theDocument->NewMesh(theIsEmbeddedMode);
95   _myMeshDS = theDocument->GetMesh(_idDoc);
96   _isShapeToMesh = false;
97 }
98
99 //=============================================================================
100 /*!
101  * 
102  */
103 //=============================================================================
104
105 SMESH_Mesh::~SMESH_Mesh()
106 {
107   INFOS("SMESH_Mesh::~SMESH_Mesh");
108
109   // delete groups
110   map < int, SMESH_Group * >::iterator itg;
111   for (itg = _mapGroup.begin(); itg != _mapGroup.end(); itg++) {
112     SMESH_Group *aGroup = (*itg).second;
113     delete aGroup;
114   }
115 }
116
117 //=============================================================================
118 /*!
119  * 
120  */
121 //=============================================================================
122
123 void SMESH_Mesh::ShapeToMesh(const TopoDS_Shape & aShape)
124 {
125   if(MYDEBUG) MESSAGE("SMESH_Mesh::ShapeToMesh");
126
127   if ( !_myMeshDS->ShapeToMesh().IsNull() && aShape.IsNull() )
128   {
129     // removal of a shape to mesh, delete objects referring to sub-shapes:
130     // - sub-meshes
131     map <int, SMESH_subMesh *>::iterator i_sm = _mapSubMesh.begin();
132     for ( ; i_sm != _mapSubMesh.end(); ++i_sm )
133       delete i_sm->second;
134     _mapSubMesh.clear();
135     //  - groups on geometry
136     map <int, SMESH_Group *>::iterator i_gr = _mapGroup.begin();
137     while ( i_gr != _mapGroup.end() ) {
138       if ( dynamic_cast<SMESHDS_GroupOnGeom*>( i_gr->second->GetGroupDS() )) {
139         _myMeshDS->RemoveGroup( i_gr->second->GetGroupDS() );
140         delete i_gr->second;
141         _mapGroup.erase( i_gr++ );
142       }
143       else
144         i_gr++;
145     }
146     _mapPropagationChains.Clear();
147   }
148   else
149   {
150     if (_isShapeToMesh)
151       throw SALOME_Exception(LOCALIZED ("a shape to mesh has already been defined"));
152   }
153   _isShapeToMesh = true;
154   _myMeshDS->ShapeToMesh(aShape);
155
156   // fill _mapAncestors
157   _mapAncestors.Clear();
158   int desType, ancType;
159   for ( desType = TopAbs_VERTEX; desType > TopAbs_COMPOUND; desType-- )
160     for ( ancType = desType - 1; ancType >= TopAbs_COMPOUND; ancType-- )
161       TopExp::MapShapesAndAncestors ( aShape,
162                                      (TopAbs_ShapeEnum) desType,
163                                      (TopAbs_ShapeEnum) ancType,
164                                      _mapAncestors );
165
166   // NRI : 24/02/03
167   //EAP: 1/9/04 TopExp::MapShapes(aShape, _subShapes); USE the same map of _myMeshDS
168 }
169
170 //=======================================================================
171 //function : UNVToMesh
172 //purpose  : 
173 //=======================================================================
174
175 int SMESH_Mesh::UNVToMesh(const char* theFileName)
176 {
177   if(MYDEBUG) MESSAGE("UNVToMesh - theFileName = "<<theFileName);
178   if(_isShapeToMesh)
179     throw SALOME_Exception(LOCALIZED("a shape to mesh has already been defined"));
180   _isShapeToMesh = true;
181   DriverUNV_R_SMDS_Mesh myReader;
182   myReader.SetMesh(_myMeshDS);
183   myReader.SetFile(theFileName);
184   myReader.SetMeshId(-1);
185   myReader.Perform();
186   if(MYDEBUG){
187     MESSAGE("UNVToMesh - _myMeshDS->NbNodes() = "<<_myMeshDS->NbNodes());
188     MESSAGE("UNVToMesh - _myMeshDS->NbEdges() = "<<_myMeshDS->NbEdges());
189     MESSAGE("UNVToMesh - _myMeshDS->NbFaces() = "<<_myMeshDS->NbFaces());
190     MESSAGE("UNVToMesh - _myMeshDS->NbVolumes() = "<<_myMeshDS->NbVolumes());
191   }
192   SMDS_MeshGroup* aGroup = (SMDS_MeshGroup*) myReader.GetGroup();
193   if (aGroup != 0) {
194     TGroupNamesMap aGroupNames = myReader.GetGroupNamesMap();
195     //const TGroupIdMap& aGroupId = myReader.GetGroupIdMap();
196     aGroup->InitSubGroupsIterator();
197     while (aGroup->MoreSubGroups()) {
198       SMDS_MeshGroup* aSubGroup = (SMDS_MeshGroup*) aGroup->NextSubGroup();
199       std::string aName = aGroupNames[aSubGroup];
200       int aId;
201
202       SMESH_Group* aSMESHGroup = AddGroup( aSubGroup->GetType(), aName.c_str(), aId );
203       if ( aSMESHGroup ) {
204         if(MYDEBUG) MESSAGE("UNVToMesh - group added: "<<aName);      
205         SMESHDS_Group* aGroupDS = dynamic_cast<SMESHDS_Group*>( aSMESHGroup->GetGroupDS() );
206         if ( aGroupDS ) {
207           aGroupDS->SetStoreName(aName.c_str());
208           aSubGroup->InitIterator();
209           const SMDS_MeshElement* aElement = 0;
210           while (aSubGroup->More()) {
211             aElement = aSubGroup->Next();
212             if (aElement) {
213               aGroupDS->SMDSGroup().Add(aElement);
214             }
215           }
216           if (aElement)
217             aGroupDS->SetType(aElement->GetType());
218         }
219       }
220     }
221   }
222   return 1;
223 }
224
225 //=======================================================================
226 //function : MEDToMesh
227 //purpose  : 
228 //=======================================================================
229
230 int SMESH_Mesh::MEDToMesh(const char* theFileName, const char* theMeshName)
231 {
232   if(MYDEBUG) MESSAGE("MEDToMesh - theFileName = "<<theFileName<<", mesh name = "<<theMeshName);
233   if(_isShapeToMesh)
234     throw SALOME_Exception(LOCALIZED("a shape to mesh has already been defined"));
235   _isShapeToMesh = true;
236   DriverMED_R_SMESHDS_Mesh myReader;
237   myReader.SetMesh(_myMeshDS);
238   myReader.SetMeshId(-1);
239   myReader.SetFile(theFileName);
240   myReader.SetMeshName(theMeshName);
241   Driver_Mesh::Status status = myReader.Perform();
242   if(MYDEBUG){
243     MESSAGE("MEDToMesh - _myMeshDS->NbNodes() = "<<_myMeshDS->NbNodes());
244     MESSAGE("MEDToMesh - _myMeshDS->NbEdges() = "<<_myMeshDS->NbEdges());
245     MESSAGE("MEDToMesh - _myMeshDS->NbFaces() = "<<_myMeshDS->NbFaces());
246     MESSAGE("MEDToMesh - _myMeshDS->NbVolumes() = "<<_myMeshDS->NbVolumes());
247   }
248
249   // Reading groups (sub-meshes are out of scope of MED import functionality)
250   list<TNameAndType> aGroupNames = myReader.GetGroupNamesAndTypes();
251   if(MYDEBUG) MESSAGE("MEDToMesh - Nb groups = "<<aGroupNames.size()); 
252   int anId;
253   list<TNameAndType>::iterator name_type = aGroupNames.begin();
254   for ( ; name_type != aGroupNames.end(); name_type++ ) {
255     SMESH_Group* aGroup = AddGroup( name_type->second, name_type->first.c_str(), anId );
256     if ( aGroup ) {
257       if(MYDEBUG) MESSAGE("MEDToMesh - group added: "<<name_type->first.c_str());      
258       SMESHDS_Group* aGroupDS = dynamic_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
259       if ( aGroupDS ) {
260         aGroupDS->SetStoreName( name_type->first.c_str() );
261         myReader.GetGroup( aGroupDS );
262       }
263     }
264   }
265   return (int) status;
266 }
267
268 //=======================================================================
269 //function : STLToMesh
270 //purpose  : 
271 //=======================================================================
272
273 int SMESH_Mesh::STLToMesh(const char* theFileName)
274 {
275   if(MYDEBUG) MESSAGE("STLToMesh - theFileName = "<<theFileName);
276   if(_isShapeToMesh)
277     throw SALOME_Exception(LOCALIZED("a shape to mesh has already been defined"));
278   _isShapeToMesh = true;
279   DriverSTL_R_SMDS_Mesh myReader;
280   myReader.SetMesh(_myMeshDS);
281   myReader.SetFile(theFileName);
282   myReader.SetMeshId(-1);
283   myReader.Perform();
284   if(MYDEBUG){
285     MESSAGE("STLToMesh - _myMeshDS->NbNodes() = "<<_myMeshDS->NbNodes());
286     MESSAGE("STLToMesh - _myMeshDS->NbEdges() = "<<_myMeshDS->NbEdges());
287     MESSAGE("STLToMesh - _myMeshDS->NbFaces() = "<<_myMeshDS->NbFaces());
288     MESSAGE("STLToMesh - _myMeshDS->NbVolumes() = "<<_myMeshDS->NbVolumes());
289   }
290   return 1;
291 }
292
293 //=============================================================================
294 /*!
295  * 
296  */
297 //=============================================================================
298
299 SMESH_Hypothesis::Hypothesis_Status
300   SMESH_Mesh::AddHypothesis(const TopoDS_Shape & aSubShape,
301                             int                  anHypId  ) throw(SALOME_Exception)
302 {
303   Unexpect aCatch(SalomeException);
304   if(MYDEBUG) MESSAGE("SMESH_Mesh::AddHypothesis");
305
306   SMESH_subMesh *subMesh = GetSubMesh(aSubShape);
307   if ( !subMesh || !subMesh->GetId())
308     return SMESH_Hypothesis::HYP_BAD_SUBSHAPE;
309
310   SMESHDS_SubMesh *subMeshDS = subMesh->GetSubMeshDS();
311   if ( subMeshDS && subMeshDS->IsComplexSubmesh() ) // group of sub-shapes and maybe of not sub-
312   {
313     MESSAGE("AddHypothesis() to complex submesh");
314     // return the worst but not fatal state of all group memebers
315     SMESH_Hypothesis::Hypothesis_Status aBestRet, aWorstNotFatal, ret;
316     aBestRet = SMESH_Hypothesis::HYP_BAD_DIM;
317     aWorstNotFatal = SMESH_Hypothesis::HYP_OK;
318     for ( TopoDS_Iterator itS ( aSubShape ); itS.More(); itS.Next())
319     {
320       if ( !GetMeshDS()->ShapeToIndex( itS.Value() ))
321         continue; // not sub-shape
322       ret = AddHypothesis( itS.Value(), anHypId );
323       if ( !SMESH_Hypothesis::IsStatusFatal( ret ) && ret > aWorstNotFatal )
324         aWorstNotFatal = ret;
325       if ( ret < aBestRet )
326         aBestRet = ret;
327     }
328     if ( SMESH_Hypothesis::IsStatusFatal( aBestRet ))
329       return aBestRet;
330     return aWorstNotFatal;
331   }
332
333   StudyContextStruct *sc = _gen->GetStudyContext(_studyId);
334   if (sc->mapHypothesis.find(anHypId) == sc->mapHypothesis.end())
335   {
336     if(MYDEBUG) MESSAGE("Hypothesis ID does not give an hypothesis");
337     if(MYDEBUG) {
338       SCRUTE(_studyId);
339       SCRUTE(anHypId);
340     }
341     throw SALOME_Exception(LOCALIZED("hypothesis does not exist"));
342   }
343
344   SMESH_Hypothesis *anHyp = sc->mapHypothesis[anHypId];
345   MESSAGE( "SMESH_Mesh::AddHypothesis " << anHyp->GetName() );
346
347   bool isGlobalHyp = IsMainShape( aSubShape );
348
349   // NotConformAllowed can be only global
350   if ( !isGlobalHyp )
351   {
352     string hypName = anHyp->GetName();
353     if ( hypName == "NotConformAllowed" )
354     {
355       if(MYDEBUG) MESSAGE( "Hypotesis <NotConformAllowed> can be only global" );
356       return SMESH_Hypothesis::HYP_INCOMPATIBLE;
357     }
358   }
359
360   // shape 
361
362   int event;
363   if (anHyp->GetType() == SMESHDS_Hypothesis::PARAM_ALGO)
364     event = SMESH_subMesh::ADD_HYP;
365   else
366     event = SMESH_subMesh::ADD_ALGO;
367   SMESH_Hypothesis::Hypothesis_Status ret = subMesh->AlgoStateEngine(event, anHyp);
368
369   // subShapes
370   if (!SMESH_Hypothesis::IsStatusFatal(ret) &&
371       !subMesh->IsApplicableHypotesis( anHyp )) // is added on father
372   {
373     if (anHyp->GetType() == SMESHDS_Hypothesis::PARAM_ALGO)
374       event = SMESH_subMesh::ADD_FATHER_HYP;
375     else
376       event = SMESH_subMesh::ADD_FATHER_ALGO;
377     SMESH_Hypothesis::Hypothesis_Status ret2 =
378       subMesh->SubMeshesAlgoStateEngine(event, anHyp);
379     if (ret2 > ret)
380       ret = ret2;
381
382     // check concurent hypotheses on ansestors
383     if (ret < SMESH_Hypothesis::HYP_CONCURENT && !isGlobalHyp )
384     {
385       const map < int, SMESH_subMesh * >& smMap = subMesh->DependsOn();
386       map < int, SMESH_subMesh * >::const_iterator smIt = smMap.begin();
387       for ( ; smIt != smMap.end(); smIt++ ) {
388         if ( smIt->second->IsApplicableHypotesis( anHyp )) {
389           ret2 = smIt->second->CheckConcurentHypothesis( anHyp->GetType() );
390           if (ret2 > ret) {
391             ret = ret2;
392             break;
393           }
394         }
395       }
396     }
397   }
398
399   if(MYDEBUG) subMesh->DumpAlgoState(true);
400   SCRUTE(ret);
401   return ret;
402 }
403
404 //=============================================================================
405 /*!
406  * 
407  */
408 //=============================================================================
409
410 SMESH_Hypothesis::Hypothesis_Status
411   SMESH_Mesh::RemoveHypothesis(const TopoDS_Shape & aSubShape,
412                                int anHypId)throw(SALOME_Exception)
413 {
414   Unexpect aCatch(SalomeException);
415   if(MYDEBUG) MESSAGE("SMESH_Mesh::RemoveHypothesis");
416   
417   SMESH_subMesh *subMesh = GetSubMesh(aSubShape);
418   SMESHDS_SubMesh *subMeshDS = subMesh->GetSubMeshDS();
419   if ( subMeshDS && subMeshDS->IsComplexSubmesh() )
420   {
421     // return the worst but not fatal state of all group memebers
422     SMESH_Hypothesis::Hypothesis_Status aBestRet, aWorstNotFatal, ret;
423     aBestRet = SMESH_Hypothesis::HYP_BAD_DIM;
424     aWorstNotFatal = SMESH_Hypothesis::HYP_OK;
425     for ( TopoDS_Iterator itS ( aSubShape ); itS.More(); itS.Next())
426     {
427       if ( !GetMeshDS()->ShapeToIndex( itS.Value() ))
428         continue; // not sub-shape
429       ret = RemoveHypothesis( itS.Value(), anHypId );
430       if ( !SMESH_Hypothesis::IsStatusFatal( ret ) && ret > aWorstNotFatal )
431         aWorstNotFatal = ret;
432       if ( ret < aBestRet )
433         aBestRet = ret;
434     }
435     if ( SMESH_Hypothesis::IsStatusFatal( aBestRet ))
436       return aBestRet;
437     return aWorstNotFatal;
438   }
439
440   StudyContextStruct *sc = _gen->GetStudyContext(_studyId);
441   if (sc->mapHypothesis.find(anHypId) == sc->mapHypothesis.end())
442     throw SALOME_Exception(LOCALIZED("hypothesis does not exist"));
443   
444   SMESH_Hypothesis *anHyp = sc->mapHypothesis[anHypId];
445   int hypType = anHyp->GetType();
446   if(MYDEBUG) SCRUTE(hypType);
447   int event;
448   
449   // shape 
450   
451   if (anHyp->GetType() == SMESHDS_Hypothesis::PARAM_ALGO)
452     event = SMESH_subMesh::REMOVE_HYP;
453   else
454     event = SMESH_subMesh::REMOVE_ALGO;
455   SMESH_Hypothesis::Hypothesis_Status ret = subMesh->AlgoStateEngine(event, anHyp);
456
457   // there may appear concurrent hyps that were covered by the removed hyp
458   if (ret < SMESH_Hypothesis::HYP_CONCURENT &&
459       subMesh->IsApplicableHypotesis( anHyp ) &&
460       subMesh->CheckConcurentHypothesis( anHyp->GetType() ) != SMESH_Hypothesis::HYP_OK)
461     ret = SMESH_Hypothesis::HYP_CONCURENT;
462
463   // subShapes
464   if (!SMESH_Hypothesis::IsStatusFatal(ret) &&
465       !subMesh->IsApplicableHypotesis( anHyp )) // is removed from father
466   {
467     if (anHyp->GetType() == SMESHDS_Hypothesis::PARAM_ALGO)
468       event = SMESH_subMesh::REMOVE_FATHER_HYP;
469     else
470       event = SMESH_subMesh::REMOVE_FATHER_ALGO;
471     SMESH_Hypothesis::Hypothesis_Status ret2 =
472       subMesh->SubMeshesAlgoStateEngine(event, anHyp);
473     if (ret2 > ret) // more severe
474       ret = ret2;
475
476     // check concurent hypotheses on ansestors
477     if (ret < SMESH_Hypothesis::HYP_CONCURENT && !IsMainShape( aSubShape ) )
478     {
479       const map < int, SMESH_subMesh * >& smMap = subMesh->DependsOn();
480       map < int, SMESH_subMesh * >::const_iterator smIt = smMap.begin();
481       for ( ; smIt != smMap.end(); smIt++ ) {
482         if ( smIt->second->IsApplicableHypotesis( anHyp )) {
483           ret2 = smIt->second->CheckConcurentHypothesis( anHyp->GetType() );
484           if (ret2 > ret) {
485             ret = ret2;
486             break;
487           }
488         }
489       }
490     }
491   }
492   
493   if(MYDEBUG) subMesh->DumpAlgoState(true);
494   if(MYDEBUG) SCRUTE(ret);
495   return ret;
496 }
497
498 //=============================================================================
499 /*!
500  * 
501  */
502 //=============================================================================
503
504 SMESHDS_Mesh * SMESH_Mesh::GetMeshDS()
505 {
506   return _myMeshDS;
507 }
508
509 //=============================================================================
510 /*!
511  * 
512  */
513 //=============================================================================
514
515 const list<const SMESHDS_Hypothesis*>&
516 SMESH_Mesh::GetHypothesisList(const TopoDS_Shape & aSubShape) const
517   throw(SALOME_Exception)
518 {
519   Unexpect aCatch(SalomeException);
520   return _myMeshDS->GetHypothesis(aSubShape);
521 }
522
523 //=======================================================================
524 //function : GetHypothesis
525 //purpose  : 
526 //=======================================================================
527
528 const SMESH_Hypothesis * SMESH_Mesh::GetHypothesis(const TopoDS_Shape &    aSubShape,
529                                                    const SMESH_HypoFilter& aFilter,
530                                                    const bool              andAncestors) const
531 {
532   {
533     const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(aSubShape);
534     list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
535     for ( ; hyp != hypList.end(); hyp++ ) {
536       const SMESH_Hypothesis * h = static_cast<const SMESH_Hypothesis*>( *hyp );
537       if ( aFilter.IsOk( h, aSubShape))
538         return h;
539     }
540   }
541   if ( andAncestors )
542   {
543     TopTools_ListIteratorOfListOfShape it( GetAncestors( aSubShape ));
544     for (; it.More(); it.Next() )
545     {
546       const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(it.Value());
547       list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
548       for ( ; hyp != hypList.end(); hyp++ ) {
549         const SMESH_Hypothesis * h = static_cast<const SMESH_Hypothesis*>( *hyp );
550         if (aFilter.IsOk( h, it.Value() ))
551           return h;
552       }
553     }
554   }
555   return 0;
556 }
557
558 //=======================================================================
559 //function : GetHypotheses
560 //purpose  : 
561 //=======================================================================
562
563 //================================================================================
564 /*!
565  * \brief Return hypothesis assigned to the shape
566   * \param aSubShape - the shape to check
567   * \param aFilter - the hypothesis filter
568   * \param aHypList - the list of the found hypotheses
569   * \param andAncestors - flag to check hypos assigned to ancestors of the shape
570   * \retval int - number of unique hypos in aHypList
571  */
572 //================================================================================
573
574 int SMESH_Mesh::GetHypotheses(const TopoDS_Shape &                aSubShape,
575                               const SMESH_HypoFilter&             aFilter,
576                               list <const SMESHDS_Hypothesis * >& aHypList,
577                               const bool                          andAncestors) const
578 {
579   set<string> hypTypes; // to exclude same type hypos from the result list
580   int nbHyps = 0;
581
582   // fill in hypTypes
583   list<const SMESHDS_Hypothesis*>::const_iterator hyp;
584   for ( hyp = aHypList.begin(); hyp != aHypList.end(); hyp++ )
585     if ( hypTypes.insert( (*hyp)->GetName() ).second )
586       nbHyps++;
587
588   // get hypos from aSubShape
589   {
590     const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(aSubShape);
591     for ( hyp = hypList.begin(); hyp != hypList.end(); hyp++ )
592       if ( aFilter.IsOk (static_cast<const SMESH_Hypothesis*>( *hyp ), aSubShape) &&
593            hypTypes.insert( (*hyp)->GetName() ).second )
594       {
595         aHypList.push_back( *hyp );
596         nbHyps++;
597       }
598   }
599
600   // get hypos from ancestors of aSubShape
601   if ( andAncestors )
602   {
603     TopTools_MapOfShape map;
604     TopTools_ListIteratorOfListOfShape it( GetAncestors( aSubShape ));
605     for (; it.More(); it.Next() )
606     {
607      if ( !map.Add( it.Value() ))
608         continue;
609       const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(it.Value());
610       for ( hyp = hypList.begin(); hyp != hypList.end(); hyp++ )
611         if (aFilter.IsOk( static_cast<const SMESH_Hypothesis*>( *hyp ), it.Value() ) &&
612             hypTypes.insert( (*hyp)->GetName() ).second ) {
613           aHypList.push_back( *hyp );
614           nbHyps++;
615         }
616     }
617   }
618   return nbHyps;
619 }
620
621 //=============================================================================
622 /*!
623  * 
624  */
625 //=============================================================================
626
627 const list<SMESHDS_Command*> & SMESH_Mesh::GetLog() throw(SALOME_Exception)
628 {
629   Unexpect aCatch(SalomeException);
630   if(MYDEBUG) MESSAGE("SMESH_Mesh::GetLog");
631   return _myMeshDS->GetScript()->GetCommands();
632 }
633
634 //=============================================================================
635 /*!
636  * 
637  */
638 //=============================================================================
639 void SMESH_Mesh::ClearLog() throw(SALOME_Exception)
640 {
641   Unexpect aCatch(SalomeException);
642   if(MYDEBUG) MESSAGE("SMESH_Mesh::ClearLog");
643   _myMeshDS->GetScript()->Clear();
644 }
645
646 //=============================================================================
647 /*!
648  * 
649  */
650 //=============================================================================
651
652 int SMESH_Mesh::GetId()
653 {
654   if(MYDEBUG) MESSAGE("SMESH_Mesh::GetId");
655   return _id;
656 }
657
658 //=============================================================================
659 /*!
660  * 
661  */
662 //=============================================================================
663
664 SMESH_Gen *SMESH_Mesh::GetGen()
665 {
666   return _gen;
667 }
668
669 //=============================================================================
670 /*!
671  * Get or Create the SMESH_subMesh object implementation
672  */
673 //=============================================================================
674
675 SMESH_subMesh *SMESH_Mesh::GetSubMesh(const TopoDS_Shape & aSubShape)
676   throw(SALOME_Exception)
677 {
678   Unexpect aCatch(SalomeException);
679   SMESH_subMesh *aSubMesh;
680   int index = _myMeshDS->ShapeToIndex(aSubShape);
681
682   // for submeshes on GEOM Group
683   if ( !index && aSubShape.ShapeType() == TopAbs_COMPOUND ) {
684     TopoDS_Iterator it( aSubShape );
685     if ( it.More() )
686       index = _myMeshDS->AddCompoundSubmesh( aSubShape, it.Value().ShapeType() );
687   }
688 //   if ( !index )
689 //     return NULL; // neither sub-shape nor a group
690
691   map <int, SMESH_subMesh *>::iterator i_sm = _mapSubMesh.find(index);
692   if ( i_sm != _mapSubMesh.end())
693   {
694     aSubMesh = i_sm->second;
695   }
696   else
697   {
698     aSubMesh = new SMESH_subMesh(index, this, _myMeshDS, aSubShape);
699     _mapSubMesh[index] = aSubMesh;
700   }
701   return aSubMesh;
702 }
703
704 //=============================================================================
705 /*!
706  * Get the SMESH_subMesh object implementation. Dont create it, return null
707  * if it does not exist.
708  */
709 //=============================================================================
710
711 SMESH_subMesh *SMESH_Mesh::GetSubMeshContaining(const TopoDS_Shape & aSubShape)
712   throw(SALOME_Exception)
713 {
714   Unexpect aCatch(SalomeException);
715   SMESH_subMesh *aSubMesh = NULL;
716   
717   int index = _myMeshDS->ShapeToIndex(aSubShape);
718
719   map <int, SMESH_subMesh *>::iterator i_sm = _mapSubMesh.find(index);
720   if ( i_sm != _mapSubMesh.end())
721     aSubMesh = i_sm->second;
722
723   return aSubMesh;
724 }
725
726 //=============================================================================
727 /*!
728  * Get the SMESH_subMesh object implementation. Dont create it, return null
729  * if it does not exist.
730  */
731 //=============================================================================
732
733 SMESH_subMesh *SMESH_Mesh::GetSubMeshContaining(const int aShapeID)
734 throw(SALOME_Exception)
735 {
736   Unexpect aCatch(SalomeException);
737   
738   map <int, SMESH_subMesh *>::iterator i_sm = _mapSubMesh.find(aShapeID);
739   if (i_sm == _mapSubMesh.end())
740     return NULL;
741   return i_sm->second;
742 }
743
744 //=======================================================================
745 //function : IsUsedHypothesis
746 //purpose  : Return True if anHyp is used to mesh aSubShape
747 //=======================================================================
748
749 bool SMESH_Mesh::IsUsedHypothesis(SMESHDS_Hypothesis * anHyp,
750                                   const SMESH_subMesh* aSubMesh)
751 {
752   SMESH_Hypothesis* hyp = static_cast<SMESH_Hypothesis*>(anHyp);
753
754   // check if anHyp can be used to mesh aSubMesh
755   if ( !aSubMesh || !aSubMesh->IsApplicableHypotesis( hyp ))
756     return false;
757
758   const TopoDS_Shape & aSubShape = const_cast<SMESH_subMesh*>( aSubMesh )->GetSubShape();
759
760   SMESH_Algo *algo = _gen->GetAlgo(*this, aSubShape );
761
762   // algorithm
763   if (anHyp->GetType() > SMESHDS_Hypothesis::PARAM_ALGO)
764     return ( anHyp == algo );
765
766   // algorithm parameter
767   if (algo)
768   {
769     // look trough hypotheses used by algo
770     SMESH_HypoFilter hypoKind;
771     if ( algo->InitCompatibleHypoFilter( hypoKind, !hyp->IsAuxiliary() )) {
772       list <const SMESHDS_Hypothesis * > usedHyps;
773       if ( GetHypotheses( aSubShape, hypoKind, usedHyps, true ))
774         return ( find( usedHyps.begin(), usedHyps.end(), anHyp ) != usedHyps.end() );
775     }
776   }
777
778   // look through all assigned hypotheses
779   //SMESH_HypoFilter filter( SMESH_HypoFilter::Is( hyp ));
780   return false; //GetHypothesis( aSubShape, filter, true );
781 }
782
783 //=============================================================================
784 /*!
785  *
786  */
787 //=============================================================================
788
789 const list < SMESH_subMesh * >&
790 SMESH_Mesh::GetSubMeshUsingHypothesis(SMESHDS_Hypothesis * anHyp)
791   throw(SALOME_Exception)
792 {
793   Unexpect aCatch(SalomeException);
794   if(MYDEBUG) MESSAGE("SMESH_Mesh::GetSubMeshUsingHypothesis");
795   map < int, SMESH_subMesh * >::iterator itsm;
796   _subMeshesUsingHypothesisList.clear();
797   for (itsm = _mapSubMesh.begin(); itsm != _mapSubMesh.end(); itsm++)
798   {
799     SMESH_subMesh *aSubMesh = (*itsm).second;
800     if ( IsUsedHypothesis ( anHyp, aSubMesh ))
801       _subMeshesUsingHypothesisList.push_back(aSubMesh);
802   }
803   return _subMeshesUsingHypothesisList;
804 }
805
806 //=======================================================================
807 //function : NotifySubMeshesHypothesisModification
808 //purpose  : Say all submeshes using theChangedHyp that it has been modified
809 //=======================================================================
810
811 void SMESH_Mesh::NotifySubMeshesHypothesisModification(const SMESH_Hypothesis* theChangedHyp)
812 {
813   Unexpect aCatch(SalomeException);
814
815   const SMESH_Hypothesis* hyp = static_cast<const SMESH_Hypothesis*>(theChangedHyp);
816
817   const SMESH_Algo *foundAlgo = 0;
818   SMESH_HypoFilter algoKind( SMESH_HypoFilter::IsAlgo() );
819   SMESH_HypoFilter compatibleHypoKind;
820   list <const SMESHDS_Hypothesis * > usedHyps;
821
822
823   map < int, SMESH_subMesh * >::iterator itsm;
824   for (itsm = _mapSubMesh.begin(); itsm != _mapSubMesh.end(); itsm++)
825   {
826     SMESH_subMesh *aSubMesh = (*itsm).second;
827     if ( aSubMesh->IsApplicableHypotesis( hyp ))
828     {
829       const TopoDS_Shape & aSubShape = aSubMesh->GetSubShape();
830
831       if ( !foundAlgo ) // init filter for algo search
832         algoKind.And( algoKind.IsApplicableTo( aSubShape ));
833       
834       const SMESH_Algo *algo = static_cast<const SMESH_Algo*>
835         ( GetHypothesis( aSubShape, algoKind, true ));
836
837       if ( algo )
838       {
839         bool sameAlgo = ( algo == foundAlgo );
840         if ( !sameAlgo && foundAlgo )
841           sameAlgo = ( strcmp( algo->GetName(), foundAlgo->GetName() ) == 0);
842
843         if ( !sameAlgo ) { // init filter for used hypos search
844           if ( !algo->InitCompatibleHypoFilter( compatibleHypoKind, !hyp->IsAuxiliary() ))
845             continue; // algo does not use any hypothesis
846           foundAlgo = algo;
847         }
848
849         // check if hyp is used by algo
850         usedHyps.clear();
851         if ( GetHypotheses( aSubShape, compatibleHypoKind, usedHyps, true ) &&
852              find( usedHyps.begin(), usedHyps.end(), hyp ) != usedHyps.end() )
853         {
854           aSubMesh->ComputeStateEngine(SMESH_subMesh::MODIF_HYP);
855
856           if ( algo->GetDim() == 1 && IsPropagationHypothesis( aSubShape ))
857             CleanMeshOnPropagationChain( aSubShape );
858         }
859       }
860     }
861   }
862 }
863
864 //=============================================================================
865 /*! Export* methods.
866  *  To store mesh contents on disk in different formats.
867  */
868 //=============================================================================
869
870 bool SMESH_Mesh::HasDuplicatedGroupNamesMED()
871 {
872   set<string> aGroupNames;
873   for ( map<int, SMESH_Group*>::iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ ) {
874     SMESH_Group* aGroup = it->second;
875     string aGroupName = aGroup->GetName();
876     aGroupName.resize(MAX_MED_GROUP_NAME_LENGTH);
877     if (!aGroupNames.insert(aGroupName).second)
878       return true;
879   }
880
881   return false;
882 }
883
884 void SMESH_Mesh::ExportMED(const char *file, 
885                            const char* theMeshName, 
886                            bool theAutoGroups,
887                            int theVersion) 
888   throw(SALOME_Exception)
889 {
890   Unexpect aCatch(SalomeException);
891
892   DriverMED_W_SMESHDS_Mesh myWriter;
893   myWriter.SetFile    ( file, MED::EVersion(theVersion) );
894   myWriter.SetMesh    ( _myMeshDS   );
895   if ( !theMeshName ) 
896     myWriter.SetMeshId  ( _idDoc      );
897   else {
898     myWriter.SetMeshId  ( -1          );
899     myWriter.SetMeshName( theMeshName );
900   }
901
902   if ( theAutoGroups ) {
903     myWriter.AddGroupOfNodes();
904     myWriter.AddGroupOfEdges();
905     myWriter.AddGroupOfFaces();
906     myWriter.AddGroupOfVolumes();
907   }
908
909   // Pass groups to writer. Provide unique group names.
910   set<string> aGroupNames;
911   char aString [256];
912   int maxNbIter = 10000; // to guarantee cycle finish
913   for ( map<int, SMESH_Group*>::iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ ) {
914     SMESH_Group*       aGroup   = it->second;
915     SMESHDS_GroupBase* aGroupDS = aGroup->GetGroupDS();
916     if ( aGroupDS ) {
917       string aGroupName0 = aGroup->GetName();
918       aGroupName0.resize(MAX_MED_GROUP_NAME_LENGTH);
919       string aGroupName = aGroupName0;
920       for (int i = 1; !aGroupNames.insert(aGroupName).second && i < maxNbIter; i++) {
921         sprintf(&aString[0], "GR_%d_%s", i, aGroupName0.c_str());
922         aGroupName = aString;
923         aGroupName.resize(MAX_MED_GROUP_NAME_LENGTH);
924       }
925       aGroupDS->SetStoreName( aGroupName.c_str() );
926       myWriter.AddGroup( aGroupDS );
927     }
928   }
929
930   // Perform export
931   myWriter.Perform();
932 }
933
934 void SMESH_Mesh::ExportDAT(const char *file) throw(SALOME_Exception)
935 {
936   Unexpect aCatch(SalomeException);
937   DriverDAT_W_SMDS_Mesh myWriter;
938   myWriter.SetFile(string(file));
939   myWriter.SetMesh(_myMeshDS);
940   myWriter.SetMeshId(_idDoc);
941   myWriter.Perform();
942 }
943
944 void SMESH_Mesh::ExportUNV(const char *file) throw(SALOME_Exception)
945 {
946   Unexpect aCatch(SalomeException);
947   DriverUNV_W_SMDS_Mesh myWriter;
948   myWriter.SetFile(string(file));
949   myWriter.SetMesh(_myMeshDS);
950   myWriter.SetMeshId(_idDoc);
951   //  myWriter.SetGroups(_mapGroup);
952   myWriter.Perform();
953 }
954
955 void SMESH_Mesh::ExportSTL(const char *file, const bool isascii) throw(SALOME_Exception)
956 {
957   Unexpect aCatch(SalomeException);
958   DriverSTL_W_SMDS_Mesh myWriter;
959   myWriter.SetFile(string(file));
960   myWriter.SetIsAscii( isascii );
961   myWriter.SetMesh(_myMeshDS);
962   myWriter.SetMeshId(_idDoc);
963   myWriter.Perform();
964 }
965
966 //=============================================================================
967 /*!
968  *  
969  */
970 //=============================================================================
971 int SMESH_Mesh::NbNodes() throw(SALOME_Exception)
972 {
973   Unexpect aCatch(SalomeException);
974   return _myMeshDS->NbNodes();
975 }
976
977 //=============================================================================
978 /*!
979  *  
980  */
981 //=============================================================================
982 int SMESH_Mesh::NbEdges(ElementOrder order) throw(SALOME_Exception)
983 {
984   Unexpect aCatch(SalomeException);
985   if (order == ORDER_ANY)
986     return _myMeshDS->NbEdges();
987
988   int Nb = 0;
989   SMDS_EdgeIteratorPtr it = _myMeshDS->edgesIterator();
990   while (it->more()) {
991     const SMDS_MeshEdge* cur = it->next();
992     if ( order == ORDER_LINEAR && !cur->IsQuadratic() ||
993          order == ORDER_SQUARE && cur->IsQuadratic() )
994       Nb++;
995   }
996   return Nb;
997 }
998
999 //=============================================================================
1000 /*!
1001  *  
1002  */
1003 //=============================================================================
1004 int SMESH_Mesh::NbFaces(ElementOrder order) throw(SALOME_Exception)
1005 {
1006   Unexpect aCatch(SalomeException);
1007   if (order == ORDER_ANY)
1008     return _myMeshDS->NbFaces();
1009
1010   int Nb = 0;
1011   SMDS_FaceIteratorPtr it = _myMeshDS->facesIterator();
1012   while (it->more()) {
1013     const SMDS_MeshFace* cur = it->next();
1014     if ( order == ORDER_LINEAR && !cur->IsQuadratic() ||
1015          order == ORDER_SQUARE && cur->IsQuadratic() )
1016       Nb++;
1017   }
1018   return Nb;
1019 }
1020
1021 ///////////////////////////////////////////////////////////////////////////////
1022 /// Return the number of 3 nodes faces in the mesh. This method run in O(n)
1023 ///////////////////////////////////////////////////////////////////////////////
1024 int SMESH_Mesh::NbTriangles(ElementOrder order) throw(SALOME_Exception)
1025 {
1026   Unexpect aCatch(SalomeException);
1027   int Nb = 0;
1028   
1029   SMDS_FaceIteratorPtr itFaces=_myMeshDS->facesIterator();
1030   while (itFaces->more()) {
1031     const SMDS_MeshFace* curFace = itFaces->next();
1032     int nbnod = curFace->NbNodes();
1033     if ( !curFace->IsPoly() && 
1034          ( order == ORDER_ANY && (nbnod==3 || nbnod==6) ||
1035            order == ORDER_LINEAR && nbnod==3 ||
1036            order == ORDER_SQUARE && nbnod==6 ) )
1037       Nb++;
1038   }
1039   return Nb;
1040 }
1041
1042 ///////////////////////////////////////////////////////////////////////////////
1043 /// Return the number of 4 nodes faces in the mesh. This method run in O(n)
1044 ///////////////////////////////////////////////////////////////////////////////
1045 int SMESH_Mesh::NbQuadrangles(ElementOrder order) throw(SALOME_Exception)
1046 {
1047   Unexpect aCatch(SalomeException);
1048   int Nb = 0;
1049   
1050   SMDS_FaceIteratorPtr itFaces=_myMeshDS->facesIterator();
1051   while (itFaces->more()) {
1052     const SMDS_MeshFace* curFace = itFaces->next();
1053     int nbnod = curFace->NbNodes();
1054     if ( !curFace->IsPoly() && 
1055          ( order == ORDER_ANY && (nbnod==4 || nbnod==8) ||
1056            order == ORDER_LINEAR && nbnod==4 ||
1057            order == ORDER_SQUARE && nbnod==8 ) )
1058       Nb++;
1059   }
1060   return Nb;
1061 }
1062
1063 ///////////////////////////////////////////////////////////////////////////////
1064 /// Return the number of polygonal faces in the mesh. This method run in O(n)
1065 ///////////////////////////////////////////////////////////////////////////////
1066 int SMESH_Mesh::NbPolygons() throw(SALOME_Exception)
1067 {
1068   Unexpect aCatch(SalomeException);
1069   int Nb = 0;
1070   SMDS_FaceIteratorPtr itFaces = _myMeshDS->facesIterator();
1071   while (itFaces->more())
1072     if (itFaces->next()->IsPoly()) Nb++;
1073   return Nb;
1074 }
1075
1076 //=============================================================================
1077 /*!
1078  *  
1079  */
1080 //=============================================================================
1081 int SMESH_Mesh::NbVolumes(ElementOrder order) throw(SALOME_Exception)
1082 {
1083   Unexpect aCatch(SalomeException);
1084   if (order == ORDER_ANY)
1085     return _myMeshDS->NbVolumes();
1086
1087   int Nb = 0;
1088   SMDS_VolumeIteratorPtr it = _myMeshDS->volumesIterator();
1089   while (it->more()) {
1090     const SMDS_MeshVolume* cur = it->next();
1091     if ( order == ORDER_LINEAR && !cur->IsQuadratic() ||
1092          order == ORDER_SQUARE && cur->IsQuadratic() )
1093       Nb++;
1094   }
1095   return Nb;
1096 }
1097
1098 int SMESH_Mesh::NbTetras(ElementOrder order) throw(SALOME_Exception)
1099 {
1100   Unexpect aCatch(SalomeException);
1101   int Nb = 0;
1102   SMDS_VolumeIteratorPtr itVolumes=_myMeshDS->volumesIterator();
1103   while (itVolumes->more()) {
1104     const SMDS_MeshVolume* curVolume = itVolumes->next();
1105     int nbnod = curVolume->NbNodes();
1106     if ( !curVolume->IsPoly() && 
1107          ( order == ORDER_ANY && (nbnod==4 || nbnod==10) ||
1108            order == ORDER_LINEAR && nbnod==4 ||
1109            order == ORDER_SQUARE && nbnod==10 ) )
1110       Nb++;
1111   }
1112   return Nb;
1113 }
1114
1115 int SMESH_Mesh::NbHexas(ElementOrder order) throw(SALOME_Exception)
1116 {
1117   Unexpect aCatch(SalomeException);
1118   int Nb = 0;
1119   SMDS_VolumeIteratorPtr itVolumes=_myMeshDS->volumesIterator();
1120   while (itVolumes->more()) {
1121     const SMDS_MeshVolume* curVolume = itVolumes->next();
1122     int nbnod = curVolume->NbNodes();
1123     if ( !curVolume->IsPoly() && 
1124          ( order == ORDER_ANY && (nbnod==8 || nbnod==20) ||
1125            order == ORDER_LINEAR && nbnod==8 ||
1126            order == ORDER_SQUARE && nbnod==20 ) )
1127       Nb++;
1128   }
1129   return Nb;
1130 }
1131
1132 int SMESH_Mesh::NbPyramids(ElementOrder order) throw(SALOME_Exception)
1133 {
1134   Unexpect aCatch(SalomeException);
1135   int Nb = 0;
1136   SMDS_VolumeIteratorPtr itVolumes=_myMeshDS->volumesIterator();
1137   while (itVolumes->more()) {
1138     const SMDS_MeshVolume* curVolume = itVolumes->next();
1139     int nbnod = curVolume->NbNodes();
1140     if ( !curVolume->IsPoly() && 
1141          ( order == ORDER_ANY && (nbnod==5 || nbnod==13) ||
1142            order == ORDER_LINEAR && nbnod==5 ||
1143            order == ORDER_SQUARE && nbnod==13 ) )
1144       Nb++;
1145   }
1146   return Nb;
1147 }
1148
1149 int SMESH_Mesh::NbPrisms(ElementOrder order) throw(SALOME_Exception)
1150 {
1151   Unexpect aCatch(SalomeException);
1152   int Nb = 0;
1153   SMDS_VolumeIteratorPtr itVolumes=_myMeshDS->volumesIterator();
1154   while (itVolumes->more()) {
1155     const SMDS_MeshVolume* curVolume = itVolumes->next();
1156     int nbnod = curVolume->NbNodes();
1157     if ( !curVolume->IsPoly() && 
1158          ( order == ORDER_ANY && (nbnod==6 || nbnod==15) ||
1159            order == ORDER_LINEAR && nbnod==6 ||
1160            order == ORDER_SQUARE && nbnod==15 ) )
1161       Nb++;
1162   }
1163   return Nb;
1164 }
1165
1166 int SMESH_Mesh::NbPolyhedrons() throw(SALOME_Exception)
1167 {
1168   Unexpect aCatch(SalomeException);
1169   int Nb = 0;
1170   SMDS_VolumeIteratorPtr itVolumes = _myMeshDS->volumesIterator();
1171   while (itVolumes->more())
1172     if (itVolumes->next()->IsPoly()) Nb++;
1173   return Nb;
1174 }
1175
1176 //=============================================================================
1177 /*!
1178  *  
1179  */
1180 //=============================================================================
1181 int SMESH_Mesh::NbSubMesh() throw(SALOME_Exception)
1182 {
1183   Unexpect aCatch(SalomeException);
1184   return _myMeshDS->NbSubMesh();
1185 }
1186
1187 //=======================================================================
1188 //function : IsNotConformAllowed
1189 //purpose  : check if a hypothesis alowing notconform mesh is present
1190 //=======================================================================
1191
1192 bool SMESH_Mesh::IsNotConformAllowed() const
1193 {
1194   if(MYDEBUG) MESSAGE("SMESH_Mesh::IsNotConformAllowed");
1195
1196   SMESH_HypoFilter filter( SMESH_HypoFilter::HasName( "NotConformAllowed" ));
1197   return GetHypothesis( _myMeshDS->ShapeToMesh(), filter, false );
1198 }
1199
1200 //=======================================================================
1201 //function : IsMainShape
1202 //purpose  : 
1203 //=======================================================================
1204
1205 bool SMESH_Mesh::IsMainShape(const TopoDS_Shape& theShape) const
1206 {
1207   return theShape.IsSame(_myMeshDS->ShapeToMesh() );
1208 }
1209
1210 //=============================================================================
1211 /*!
1212  *  
1213  */
1214 //=============================================================================
1215
1216 SMESH_Group* SMESH_Mesh::AddGroup (const SMDSAbs_ElementType theType,
1217                                    const char*               theName,
1218                                    int&                      theId,
1219                                    const TopoDS_Shape&       theShape)
1220 {
1221   if (_mapGroup.find(_groupId) != _mapGroup.end())
1222     return NULL;
1223   theId = _groupId;
1224   SMESH_Group* aGroup = new SMESH_Group (theId, this, theType, theName, theShape);
1225   GetMeshDS()->AddGroup( aGroup->GetGroupDS() );
1226   _mapGroup[_groupId++] = aGroup;
1227   return aGroup;
1228 }
1229
1230 //=============================================================================
1231 /*!
1232  *  
1233  */
1234 //=============================================================================
1235
1236 SMESH_Group* SMESH_Mesh::GetGroup (const int theGroupID)
1237 {
1238   if (_mapGroup.find(theGroupID) == _mapGroup.end())
1239     return NULL;
1240   return _mapGroup[theGroupID];
1241 }
1242
1243
1244 //=============================================================================
1245 /*!
1246  *  
1247  */
1248 //=============================================================================
1249
1250 list<int> SMESH_Mesh::GetGroupIds()
1251 {
1252   list<int> anIds;
1253   for ( map<int, SMESH_Group*>::const_iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ )
1254     anIds.push_back( it->first );
1255   
1256   return anIds;
1257 }
1258
1259
1260 //=============================================================================
1261 /*!
1262  *  
1263  */
1264 //=============================================================================
1265
1266 void SMESH_Mesh::RemoveGroup (const int theGroupID)
1267 {
1268   if (_mapGroup.find(theGroupID) == _mapGroup.end())
1269     return;
1270   GetMeshDS()->RemoveGroup( _mapGroup[theGroupID]->GetGroupDS() );
1271   delete _mapGroup[theGroupID];
1272   _mapGroup.erase (theGroupID);
1273 }
1274
1275 //=============================================================================
1276 /*!
1277  *  IsLocal1DHypothesis
1278  *  Returns a local 1D hypothesis used for theEdge
1279  */
1280 //=============================================================================
1281 const SMESH_Hypothesis* SMESH_Mesh::IsLocal1DHypothesis (const TopoDS_Shape& theEdge)
1282 {
1283   SMESH_HypoFilter hypo ( SMESH_HypoFilter::HasDim( 1 ));
1284   hypo.AndNot( hypo.IsAlgo() ).AndNot( hypo.IsAssignedTo( GetMeshDS()->ShapeToMesh() ));
1285
1286   return GetHypothesis( theEdge, hypo, true );
1287 }
1288
1289 //=============================================================================
1290 /*!
1291  *  IsPropagationHypothesis
1292  */
1293 //=============================================================================
1294 bool SMESH_Mesh::IsPropagationHypothesis (const TopoDS_Shape& theEdge)
1295 {
1296   return _mapPropagationChains.Contains(theEdge);
1297 }
1298
1299 //=============================================================================
1300 /*!
1301  *  IsPropagatedHypothesis
1302  */
1303 //=============================================================================
1304 bool SMESH_Mesh::IsPropagatedHypothesis (const TopoDS_Shape& theEdge,
1305                                          TopoDS_Shape&       theMainEdge)
1306 {
1307   int nbChains = _mapPropagationChains.Extent();
1308   for (int i = 1; i <= nbChains; i++) {
1309     //const TopTools_IndexedMapOfShape& aChain = _mapPropagationChains.FindFromIndex(i);
1310     const SMESH_IndexedMapOfShape& aChain = _mapPropagationChains.FindFromIndex(i);
1311     if (aChain.Contains(theEdge)) {
1312       theMainEdge = _mapPropagationChains.FindKey(i);
1313       return true;
1314     }
1315   }
1316
1317   return false;
1318 }
1319 //=============================================================================
1320 /*!
1321  *  IsReversedInChain
1322  */
1323 //=============================================================================
1324
1325 bool SMESH_Mesh::IsReversedInChain (const TopoDS_Shape& theEdge,
1326                                     const TopoDS_Shape& theMainEdge)
1327 {
1328   if ( !theMainEdge.IsNull() && !theEdge.IsNull() &&
1329       _mapPropagationChains.Contains( theMainEdge ))
1330   {
1331     const SMESH_IndexedMapOfShape& aChain =
1332       _mapPropagationChains.FindFromKey( theMainEdge );
1333     int index = aChain.FindIndex( theEdge );
1334     if ( index )
1335       return aChain(index).Orientation() == TopAbs_REVERSED;
1336   }
1337   return false;
1338 }
1339
1340 //=============================================================================
1341 /*!
1342  *  CleanMeshOnPropagationChain
1343  */
1344 //=============================================================================
1345 void SMESH_Mesh::CleanMeshOnPropagationChain (const TopoDS_Shape& theMainEdge)
1346 {
1347   const SMESH_IndexedMapOfShape& aChain = _mapPropagationChains.FindFromKey(theMainEdge);
1348   int i, nbEdges = aChain.Extent();
1349   for (i = 1; i <= nbEdges; i++) {
1350     TopoDS_Shape anEdge = aChain.FindKey(i);
1351     SMESH_subMesh *subMesh = GetSubMesh(anEdge);
1352     SMESHDS_SubMesh *subMeshDS = subMesh->GetSubMeshDS();
1353     if (subMeshDS && subMeshDS->NbElements() > 0) {
1354       subMesh->ComputeStateEngine(SMESH_subMesh::CLEAN);
1355     }
1356   }
1357 }
1358
1359 //=============================================================================
1360 /*!
1361  *  RebuildPropagationChains
1362  *  Rebuild all existing propagation chains.
1363  *  Have to be used, if 1D hypothesis have been assigned/removed to/from any edge
1364  */
1365 //=============================================================================
1366 bool SMESH_Mesh::RebuildPropagationChains()
1367 {
1368   bool ret = true;
1369
1370   // Clean all chains, because they can be not up-to-date
1371   int i, nbChains = _mapPropagationChains.Extent();
1372   for (i = 1; i <= nbChains; i++) {
1373     TopoDS_Shape aMainEdge = _mapPropagationChains.FindKey(i);
1374     CleanMeshOnPropagationChain(aMainEdge);
1375     _mapPropagationChains.ChangeFromIndex(i).Clear();
1376   }
1377
1378   // Build all chains
1379   for (i = 1; i <= nbChains; i++) {
1380     TopoDS_Shape aMainEdge = _mapPropagationChains.FindKey(i);
1381     if (!BuildPropagationChain(aMainEdge))
1382       ret = false;
1383     CleanMeshOnPropagationChain(aMainEdge);
1384   }
1385
1386   return ret;
1387 }
1388
1389 //=============================================================================
1390 /*!
1391  *  RemovePropagationChain
1392  *  Have to be used, if Propagation hypothesis is removed from <theMainEdge>
1393  */
1394 //=============================================================================
1395 bool SMESH_Mesh::RemovePropagationChain (const TopoDS_Shape& theMainEdge)
1396 {
1397   if (!_mapPropagationChains.Contains(theMainEdge))
1398     return false;
1399
1400   // Clean mesh elements and nodes, built on the chain
1401   CleanMeshOnPropagationChain(theMainEdge);
1402
1403   // Clean the chain
1404   _mapPropagationChains.ChangeFromKey(theMainEdge).Clear();
1405
1406   // Remove the chain from the map
1407   int i = _mapPropagationChains.FindIndex(theMainEdge);
1408   if ( i == _mapPropagationChains.Extent() )
1409     _mapPropagationChains.RemoveLast();
1410   else {
1411     TopoDS_Vertex anEmptyShape;
1412     BRep_Builder BB;
1413     BB.MakeVertex(anEmptyShape, gp_Pnt(0,0,0), 0.1);
1414     SMESH_IndexedMapOfShape anEmptyMap;
1415     _mapPropagationChains.Substitute(i, anEmptyShape, anEmptyMap);
1416   }
1417
1418   return true;
1419 }
1420
1421 //=============================================================================
1422 /*!
1423  *  BuildPropagationChain
1424  */
1425 //=============================================================================
1426 bool SMESH_Mesh::BuildPropagationChain (const TopoDS_Shape& theMainEdge)
1427 {
1428   if (theMainEdge.ShapeType() != TopAbs_EDGE) return true;
1429
1430   // Add new chain, if there is no
1431   if (!_mapPropagationChains.Contains(theMainEdge)) {
1432     SMESH_IndexedMapOfShape aNewChain;
1433     _mapPropagationChains.Add(theMainEdge, aNewChain);
1434   }
1435
1436   // Check presence of 1D hypothesis to be propagated
1437   const SMESH_Hypothesis* aMainHyp = IsLocal1DHypothesis(theMainEdge);
1438   if (!aMainHyp) {
1439     MESSAGE("Warning: There is no 1D hypothesis to propagate. Please, assign.");
1440     return true;
1441   }
1442
1443   // Edges, on which the 1D hypothesis will be propagated from <theMainEdge>
1444   SMESH_IndexedMapOfShape& aChain = _mapPropagationChains.ChangeFromKey(theMainEdge);
1445   if (aChain.Extent() > 0) {
1446     CleanMeshOnPropagationChain(theMainEdge);
1447     aChain.Clear();
1448   }
1449
1450   // At first put <theMainEdge> in the chain
1451   aChain.Add(theMainEdge);
1452
1453   // List of edges, added to chain on the previous cycle pass
1454   TopTools_ListOfShape listPrevEdges;
1455   listPrevEdges.Append(theMainEdge.Oriented( TopAbs_FORWARD ));
1456
1457 //   5____4____3____4____5____6
1458 //   |    |    |    |    |    |
1459 //   |    |    |    |    |    |
1460 //   4____3____2____3____4____5
1461 //   |    |    |    |    |    |      Number in the each knot of
1462 //   |    |    |    |    |    |      grid indicates cycle pass,
1463 //   3____2____1____2____3____4      on which corresponding edge
1464 //   |    |    |    |    |    |      (perpendicular to the plane
1465 //   |    |    |    |    |    |      of view) will be found.
1466 //   2____1____0____1____2____3
1467 //   |    |    |    |    |    |
1468 //   |    |    |    |    |    |
1469 //   3____2____1____2____3____4
1470
1471   // Collect all edges pass by pass
1472   while (listPrevEdges.Extent() > 0) {
1473     // List of edges, added to chain on this cycle pass
1474     TopTools_ListOfShape listCurEdges;
1475
1476     // Find the next portion of edges
1477     TopTools_ListIteratorOfListOfShape itE (listPrevEdges);
1478     for (; itE.More(); itE.Next()) {
1479       TopoDS_Shape anE = itE.Value();
1480
1481       // Iterate on faces, having edge <anE>
1482       TopTools_ListIteratorOfListOfShape itA (GetAncestors(anE));
1483       for (; itA.More(); itA.Next()) {
1484         TopoDS_Shape aW = itA.Value();
1485
1486         // There are objects of different type among the ancestors of edge
1487         if (aW.ShapeType() == TopAbs_WIRE) {
1488           TopoDS_Shape anOppE;
1489
1490           BRepTools_WireExplorer aWE (TopoDS::Wire(aW));
1491           Standard_Integer nb = 1, found = 0;
1492           TopTools_Array1OfShape anEdges (1,4);
1493           for (; aWE.More(); aWE.Next(), nb++) {
1494             if (nb > 4) {
1495               found = 0;
1496               break;
1497             }
1498             anEdges(nb) = aWE.Current();
1499             if (!_mapAncestors.Contains(anEdges(nb))) {
1500               MESSAGE("WIRE EXPLORER HAVE GIVEN AN INVALID EDGE !!!");
1501               break;
1502             }
1503             if (anEdges(nb).IsSame(anE)) found = nb;
1504           }
1505
1506           if (nb == 5 && found > 0) {
1507             // Quadrangle face found, get an opposite edge
1508             Standard_Integer opp = found + 2;
1509             if (opp > 4) opp -= 4;
1510             anOppE = anEdges(opp);
1511
1512             // add anOppE to aChain if ...
1513             if (!aChain.Contains(anOppE)) { // ... anOppE is not in aChain
1514               if (!IsLocal1DHypothesis(anOppE)) { // ... no other 1d hyp on anOppE
1515                 TopoDS_Shape aMainEdgeForOppEdge; // ... no other hyp is propagated to anOppE
1516                 if (!IsPropagatedHypothesis(anOppE, aMainEdgeForOppEdge))
1517                 {
1518                   // Add found edge to the chain oriented so that to
1519                   // have it co-directed with a forward MainEdge
1520                   TopAbs_Orientation ori = anE.Orientation();
1521                   if ( anEdges(opp).Orientation() == anEdges(found).Orientation() )
1522                     ori = TopAbs::Reverse( ori );
1523                   anOppE.Orientation( ori );
1524                   aChain.Add(anOppE);
1525                   listCurEdges.Append(anOppE);
1526                 }
1527                 else {
1528                   // Collision!
1529                   MESSAGE("Error: Collision between propagated hypotheses");
1530                   CleanMeshOnPropagationChain(theMainEdge);
1531                   aChain.Clear();
1532                   return ( aMainHyp == IsLocal1DHypothesis(aMainEdgeForOppEdge) );
1533                 }
1534               }
1535             }
1536           } // if (nb == 5 && found > 0)
1537         } // if (aF.ShapeType() == TopAbs_WIRE)
1538       } // for (; itF.More(); itF.Next())
1539     } // for (; itE.More(); itE.Next())
1540
1541     listPrevEdges = listCurEdges;
1542   } // while (listPrevEdges.Extent() > 0)
1543
1544   CleanMeshOnPropagationChain(theMainEdge);
1545   return true;
1546 }
1547
1548 //=======================================================================
1549 //function : GetAncestors
1550 //purpose  : return list of ancestors of theSubShape in the order
1551 //           that lower dimention shapes come first.
1552 //=======================================================================
1553
1554 const TopTools_ListOfShape& SMESH_Mesh::GetAncestors(const TopoDS_Shape& theS) const
1555 {
1556   if ( _mapAncestors.Contains( theS ) )
1557     return _mapAncestors.FindFromKey( theS );
1558
1559   static TopTools_ListOfShape emptyList;
1560   return emptyList;
1561 }
1562
1563 //=======================================================================
1564 //function : Dump
1565 //purpose  : dumps contents of mesh to stream [ debug purposes ]
1566 //=======================================================================
1567 ostream& SMESH_Mesh::Dump(ostream& save)
1568 {
1569   save << "========================== Dump contents of mesh ==========================" << endl;
1570   save << "1) Total number of nodes:     " << NbNodes() << endl;
1571   save << "2) Total number of edges:     " << NbEdges() << endl;
1572   save << "3) Total number of faces:     " << NbFaces() << endl;
1573   if ( NbFaces() > 0 ) {
1574     int nb3 = NbTriangles();
1575     int nb4 = NbQuadrangles();
1576     save << "3.1.) Number of triangles:    " << nb3 << endl;
1577     save << "3.2.) Number of quadrangles:  " << nb4 << endl;
1578     if ( nb3 + nb4 !=  NbFaces() ) {
1579       map<int,int> myFaceMap;
1580       SMDS_FaceIteratorPtr itFaces=_myMeshDS->facesIterator();
1581       while( itFaces->more( ) ) {
1582         int nbNodes = itFaces->next()->NbNodes();
1583         if ( myFaceMap.find( nbNodes ) == myFaceMap.end() )
1584           myFaceMap[ nbNodes ] = 0;
1585         myFaceMap[ nbNodes ] = myFaceMap[ nbNodes ] + 1;
1586       }
1587       save << "3.3.) Faces in detail: " << endl;
1588       map <int,int>::iterator itF;
1589       for (itF = myFaceMap.begin(); itF != myFaceMap.end(); itF++)
1590         save << "--> nb nodes: " << itF->first << " - nb elemens: " << itF->second << endl;
1591     }
1592   }
1593   save << "4) Total number of volumes:   " << NbVolumes() << endl;
1594   if ( NbVolumes() > 0 ) {
1595     int nb8 = NbHexas();
1596     int nb4 = NbTetras();
1597     int nb5 = NbPyramids();
1598     int nb6 = NbPrisms();
1599     save << "4.1.) Number of hexahedrons:  " << nb8 << endl;
1600     save << "4.2.) Number of tetrahedrons: " << nb4 << endl;
1601     save << "4.3.) Number of prisms:       " << nb6 << endl;
1602     save << "4.4.) Number of pyramides:    " << nb5 << endl;
1603     if ( nb8 + nb4 + nb5 + nb6 != NbVolumes() ) {
1604       map<int,int> myVolumesMap;
1605       SMDS_VolumeIteratorPtr itVolumes=_myMeshDS->volumesIterator();
1606       while( itVolumes->more( ) ) {
1607         int nbNodes = itVolumes->next()->NbNodes();
1608         if ( myVolumesMap.find( nbNodes ) == myVolumesMap.end() )
1609           myVolumesMap[ nbNodes ] = 0;
1610         myVolumesMap[ nbNodes ] = myVolumesMap[ nbNodes ] + 1;
1611       }
1612       save << "4.5.) Volumes in detail: " << endl;
1613       map <int,int>::iterator itV;
1614       for (itV = myVolumesMap.begin(); itV != myVolumesMap.end(); itV++)
1615         save << "--> nb nodes: " << itV->first << " - nb elemens: " << itV->second << endl;
1616     }
1617   }
1618   save << "===========================================================================" << endl;
1619   return save;
1620 }
1621
1622 //=======================================================================
1623 //function : GetElementType
1624 //purpose  : Returns type of mesh element with certain id
1625 //=======================================================================
1626 SMDSAbs_ElementType SMESH_Mesh::GetElementType( const int id, const bool iselem )
1627 {
1628   return _myMeshDS->GetElementType( id, iselem );
1629 }