Salome HOME
23611: EDF 11012 - Force Z coords to 0
[modules/smesh.git] / src / DriverMED / DriverMED_W_SMESHDS_Mesh.cxx
1 // Copyright (C) 2007-2016  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 DriverMED : driver to read and write 'med' files
24 //  File   : DriverMED_W_SMESHDS_Mesh.cxx
25 //  Module : SMESH
26 //
27
28 #include "DriverMED_W_SMESHDS_Mesh.h"
29
30 #include "DriverMED_Family.h"
31 #include "MED_Factory.hxx"
32 #include "MED_Utilities.hxx"
33 #include "SMDS_IteratorOnIterators.hxx"
34 #include "SMDS_MeshNode.hxx"
35 #include "SMDS_SetIterator.hxx"
36 #include "SMESHDS_Mesh.hxx"
37
38 #include <med.h>
39
40 #include <BRep_Tool.hxx>
41 #include <TopExp_Explorer.hxx>
42 #include <TopoDS.hxx>
43
44 #include <utilities.h>
45
46
47 #define _EDF_NODE_IDS_
48 //#define _ELEMENTS_BY_DIM_
49
50 using namespace std;
51 using namespace MED;
52
53
54 DriverMED_W_SMESHDS_Mesh::DriverMED_W_SMESHDS_Mesh():
55   myAllSubMeshes (false),
56   myDoGroupOfNodes (false),
57   myDoGroupOfEdges (false),
58   myDoGroupOfFaces (false),
59   myDoGroupOfVolumes (false),
60   myDoGroupOf0DElems(false),
61   myDoGroupOfBalls(false),
62   myAutoDimension(false),
63   myAddODOnVertices(false),
64   myDoAllInGroups(false),
65   myVersion(-1),
66   myZTolerance(-1.)
67 {}
68
69 void DriverMED_W_SMESHDS_Mesh::SetFile(const std::string& theFileName, int theVersion)
70 {
71   myVersion = theVersion;
72   Driver_SMESHDS_Mesh::SetFile(theFileName);
73 }
74
75 /*!
76  * MED version is either the latest available, or with an inferior minor,
77  * to ensure backward compatibility on writing med files.
78  */
79 string DriverMED_W_SMESHDS_Mesh::GetVersionString(int theMinor, int theNbDigits)
80 {
81   TInt majeur, mineur, release;
82   majeur=MED_MAJOR_NUM;
83   mineur=MED_MINOR_NUM;
84   release=MED_RELEASE_NUM;
85   TInt imposedMineur = mineur;
86
87   if (theMinor < 0)
88     imposedMineur = mineur;
89   else if (theMinor > MED_MINOR_NUM)
90     imposedMineur = mineur;
91   else
92     imposedMineur = theMinor;
93
94   ostringstream name;
95   if ( theNbDigits > 0 )
96     name << majeur;
97   if ( theNbDigits > 1 )
98     name << "." << imposedMineur;
99   if ( theNbDigits > 2 )
100     name << "." << release;
101   return name.str();
102 }
103
104 void DriverMED_W_SMESHDS_Mesh::AddGroup(SMESHDS_GroupBase* theGroup)
105 {
106   myGroups.push_back(theGroup);
107 }
108
109 void DriverMED_W_SMESHDS_Mesh::AddAllSubMeshes()
110 {
111   myAllSubMeshes = true;
112 }
113
114 void DriverMED_W_SMESHDS_Mesh::AddSubMesh(SMESHDS_SubMesh* theSubMesh, int theID)
115 {
116   mySubMeshes.push_back( theSubMesh );
117 }
118
119 void DriverMED_W_SMESHDS_Mesh::AddGroupOfNodes()
120 {
121   myDoGroupOfNodes = true;
122 }
123
124 void DriverMED_W_SMESHDS_Mesh::AddGroupOfEdges()
125 {
126   myDoGroupOfEdges = true;
127 }
128
129 void DriverMED_W_SMESHDS_Mesh::AddGroupOfFaces()
130 {
131   myDoGroupOfFaces = true;
132 }
133
134 void DriverMED_W_SMESHDS_Mesh::AddGroupOfVolumes()
135 {
136   myDoGroupOfVolumes = true;
137 }
138
139 void DriverMED_W_SMESHDS_Mesh::AddGroupOf0DElems()
140 {
141   myDoGroupOf0DElems = true;
142 }
143
144 void DriverMED_W_SMESHDS_Mesh::AddGroupOfBalls()
145 {
146   myDoGroupOfBalls = true;
147 }
148
149 //================================================================================
150 /*!
151  * \brief Set up a flag to add all elements not belonging to any group to
152  *        some auxiliary group. This is needed for SMESH -> SAUVE -> SMESH conversion,
153  *        which since PAL0023285 reads only SAUVE elements belonging to any group,
154  *        and hence can lose some elements. That auxiliary group is ignored while
155  *        reading a MED file.
156  */
157 //================================================================================
158
159 void DriverMED_W_SMESHDS_Mesh::AddAllToGroup()
160 {
161   myDoAllInGroups = true;
162 }
163
164
165 namespace
166 {
167   typedef double (SMDS_MeshNode::* TGetCoord)() const;
168   typedef const char* TName;
169   typedef const char* TUnit;
170
171   // name length in a mesh must be equal to 16 :
172   //         1234567890123456
173   TName M = "m               ";
174   TName X = "x               ";
175   TName Y = "y               ";
176   TName Z = "z               ";
177
178   TUnit aUnit[3] = {M,M,M};
179
180   // 3 dim
181   TGetCoord aXYZGetCoord[3] = {
182     &SMDS_MeshNode::X, 
183     &SMDS_MeshNode::Y, 
184     &SMDS_MeshNode::Z
185   };
186   TName aXYZName[3] = {X,Y,Z};
187   
188   // 2 dim
189   TGetCoord aXYGetCoord[2] = {
190     &SMDS_MeshNode::X, 
191     &SMDS_MeshNode::Y
192   };
193   TName aXYName[2] = {X,Y};
194
195   TGetCoord aYZGetCoord[2] = {
196     &SMDS_MeshNode::Y, 
197     &SMDS_MeshNode::Z
198   };
199   TName aYZName[2] = {Y,Z};
200
201   TGetCoord aXZGetCoord[2] = {
202     &SMDS_MeshNode::X, 
203     &SMDS_MeshNode::Z
204   };
205   TName aXZName[2] = {X,Z};
206
207   // 1 dim
208   TGetCoord aXGetCoord[1] = {
209     &SMDS_MeshNode::X
210   };
211   TName aXName[1] = {X};
212
213   TGetCoord aYGetCoord[1] = {
214     &SMDS_MeshNode::Y
215   };
216   TName aYName[1] = {Y};
217
218   TGetCoord aZGetCoord[1] = {
219     &SMDS_MeshNode::Z
220   };
221   TName aZName[1] = {Z};
222
223
224   class TCoordHelper{
225     SMDS_NodeIteratorPtr myNodeIter;
226     const SMDS_MeshNode* myCurrentNode;
227     TGetCoord* myGetCoord;
228     TName* myName;
229     TUnit* myUnit;
230   public:
231     TCoordHelper(const SMDS_NodeIteratorPtr& theNodeIter,
232                  TGetCoord* theGetCoord,
233                  TName* theName,
234                  TUnit* theUnit = aUnit):
235       myNodeIter(theNodeIter),
236       myGetCoord(theGetCoord),
237       myName(theName),
238       myUnit(theUnit)
239     {}
240     virtual ~TCoordHelper(){}
241     bool Next(){ 
242       return myNodeIter->more() && 
243         (myCurrentNode = myNodeIter->next());
244     }
245     const SMDS_MeshNode* GetNode(){
246       return myCurrentNode;
247     }
248     MED::TIntVector::value_type GetID(){
249       return myCurrentNode->GetID();
250     }
251     MED::TFloatVector::value_type GetCoord(TInt theCoodId){
252       return (myCurrentNode->*myGetCoord[theCoodId])();
253     }
254     MED::TStringVector::value_type GetName(TInt theDimId){
255       return myName[theDimId];
256     }
257     MED::TStringVector::value_type GetUnit(TInt theDimId){
258       return myUnit[theDimId];
259     }
260   };
261   typedef boost::shared_ptr<TCoordHelper> TCoordHelperPtr;
262
263   //-------------------------------------------------------
264   /*!
265    * \brief Structure describing element type
266    */
267   //-------------------------------------------------------
268   struct TElemTypeData
269   {
270     EEntiteMaillage     _entity;
271     EGeometrieElement   _geomType;
272     TInt                _nbElems;
273     SMDSAbs_ElementType _smdsType;
274
275     TElemTypeData (EEntiteMaillage entity, EGeometrieElement geom, TInt nb, SMDSAbs_ElementType type)
276       : _entity(entity), _geomType(geom), _nbElems( nb ), _smdsType( type ) {}
277   };
278
279
280   typedef NCollection_DataMap< Standard_Address, int > TElemFamilyMap;
281
282   //================================================================================
283   /*!
284    * \brief Fills element to famaly ID map for element type.
285    * Removes all families of anElemType
286    */
287   //================================================================================
288
289   void fillElemFamilyMap( TElemFamilyMap &            anElemFamMap,
290                           list<DriverMED_FamilyPtr> & aFamilies,
291                           const SMDSAbs_ElementType   anElemType)
292   {
293     anElemFamMap.Clear();
294     list<DriverMED_FamilyPtr>::iterator aFamsIter = aFamilies.begin();
295     while ( aFamsIter != aFamilies.end() )
296     {
297       if ((*aFamsIter)->GetType() != anElemType) {
298         aFamsIter++;
299       }
300       else {
301         int aFamId = (*aFamsIter)->GetId();
302         const ElementsSet&              anElems = (*aFamsIter)->GetElements();
303         ElementsSet::const_iterator anElemsIter = anElems.begin();
304         for (; anElemsIter != anElems.end(); anElemsIter++)
305         {
306           anElemFamMap.Bind( (Standard_Address)*anElemsIter, aFamId );
307         }
308         // remove a family from the list
309         aFamilies.erase( aFamsIter++ );
310       }
311     }
312   }
313
314   //================================================================================
315   /*!
316    * \brief For an element, return family ID found in the map or a default one
317    */
318   //================================================================================
319
320   int getFamilyId( const TElemFamilyMap &  anElemFamMap,
321                    const SMDS_MeshElement* anElement,
322                    const int               aDefaultFamilyId)
323   {
324     if ( anElemFamMap.IsBound( (Standard_Address) anElement ))
325       return anElemFamMap( (Standard_Address) anElement );
326
327     return aDefaultFamilyId;
328   }
329
330   //================================================================================
331   /*!
332    * \brief Returns iterator on sub-meshes
333    */
334   //================================================================================
335
336   SMESHDS_SubMeshIteratorPtr getIterator( std::vector<SMESHDS_SubMesh*>& mySubMeshes )
337   {
338     return SMESHDS_SubMeshIteratorPtr
339       ( new SMDS_SetIterator
340         < const SMESHDS_SubMesh*, std::vector< SMESHDS_SubMesh* >::iterator >( mySubMeshes.begin(),
341                                                                                mySubMeshes.end() ));
342   }
343 }
344
345 Driver_Mesh::Status DriverMED_W_SMESHDS_Mesh::Perform()
346 {
347   Status aResult = DRS_OK;
348   try {
349     //MESSAGE("Perform - myFile : "<<myFile);
350
351     // Creating the MED mesh for corresponding SMDS structure
352     //-------------------------------------------------------
353     string aMeshName;
354     if (myMeshId != -1) {
355       ostringstream aMeshNameStr;
356       aMeshNameStr<<myMeshId;
357       aMeshName = aMeshNameStr.str();
358     } else {
359       aMeshName = myMeshName;
360     }
361
362     // Mesh dimension definition
363
364     TInt aMeshDimension = 0;
365     if ( myMesh->NbEdges() > 0 )
366       aMeshDimension = 1;
367     if ( myMesh->NbFaces() > 0 )
368       aMeshDimension = 2;
369     if ( myMesh->NbVolumes() > 0 )
370       aMeshDimension = 3;
371
372     TInt aSpaceDimension = 3;
373     TCoordHelperPtr aCoordHelperPtr;
374     {
375       bool anIsXDimension = false;
376       bool anIsYDimension = false;
377       bool anIsZDimension = false;
378       if ( myAutoDimension && aMeshDimension < 3 )
379       {
380         SMDS_NodeIteratorPtr aNodesIter = myMesh->nodesIterator();
381         double aBounds[6];
382         if(aNodesIter->more()){
383           const SMDS_MeshNode* aNode = aNodesIter->next();
384           aBounds[0] = aBounds[1] = aNode->X();
385           aBounds[2] = aBounds[3] = aNode->Y();
386           aBounds[4] = aBounds[5] = aNode->Z();
387         }
388         while(aNodesIter->more()){
389           const SMDS_MeshNode* aNode = aNodesIter->next();
390           aBounds[0] = min(aBounds[0],aNode->X());
391           aBounds[1] = max(aBounds[1],aNode->X());
392
393           aBounds[2] = min(aBounds[2],aNode->Y());
394           aBounds[3] = max(aBounds[3],aNode->Y());
395
396           aBounds[4] = min(aBounds[4],aNode->Z());
397           aBounds[5] = max(aBounds[5],aNode->Z());
398         }
399
400         double EPS = 1.0E-7;
401         TopoDS_Shape mainShape = myMesh->ShapeToMesh();
402         bool    hasShapeToMesh = ( myMesh->SubMeshIndices().size() > 1 );
403         if ( !mainShape.IsNull() && hasShapeToMesh )
404         {
405           // define EPS by max tolerance of the mainShape (IPAL53097)
406           TopExp_Explorer subShape;
407           for ( subShape.Init( mainShape, TopAbs_FACE ); subShape.More(); subShape.Next() ) {
408             EPS = Max( EPS, BRep_Tool::Tolerance( TopoDS::Face( subShape.Current() )));
409           }
410           for ( subShape.Init( mainShape, TopAbs_EDGE ); subShape.More(); subShape.Next() ) {
411             EPS = Max( EPS, BRep_Tool::Tolerance( TopoDS::Edge( subShape.Current() )));
412           }
413           for ( subShape.Init( mainShape, TopAbs_VERTEX ); subShape.More(); subShape.Next() ) {
414             EPS = Max( EPS, BRep_Tool::Tolerance( TopoDS::Vertex( subShape.Current() )));
415           }
416           EPS *= 2.;
417         }
418         anIsXDimension = (aBounds[1] - aBounds[0]) + abs(aBounds[1]) + abs(aBounds[0]) > EPS;
419         anIsYDimension = (aBounds[3] - aBounds[2]) + abs(aBounds[3]) + abs(aBounds[2]) > EPS;
420         anIsZDimension = (aBounds[5] - aBounds[4]) + abs(aBounds[5]) + abs(aBounds[4]) > EPS;
421         if ( myZTolerance > 0 && anIsZDimension )
422           anIsZDimension = (aBounds[5] > myZTolerance || aBounds[4] < -myZTolerance );
423         aSpaceDimension = Max( aMeshDimension, anIsXDimension + anIsYDimension + anIsZDimension );
424         if ( !aSpaceDimension )
425           aSpaceDimension = 3;
426         // PAL16857(SMESH not conform to the MED convention):
427         if ( aSpaceDimension == 2 && anIsZDimension ) // 2D only if mesh is in XOY plane
428           aSpaceDimension = 3;
429         // PAL18941(a saved study with a mesh belong Z is opened and the mesh is belong X)
430         if ( aSpaceDimension == 1 && !anIsXDimension ) {// 1D only if mesh is along OX
431           if ( anIsYDimension ) {
432             aSpaceDimension = 2;
433             anIsXDimension = true;
434           } else {
435             aSpaceDimension = 3;
436           }
437         }
438       }
439
440       SMDS_NodeIteratorPtr aNodesIter = myMesh->nodesIterator();
441       switch ( aSpaceDimension ) {
442       case 3:
443         aCoordHelperPtr.reset(new TCoordHelper(aNodesIter,aXYZGetCoord,aXYZName));
444         break;
445       case 2:
446         if(anIsXDimension && anIsYDimension)
447           aCoordHelperPtr.reset(new TCoordHelper(aNodesIter,aXYGetCoord,aXYName));
448         if(anIsYDimension && anIsZDimension)
449           aCoordHelperPtr.reset(new TCoordHelper(aNodesIter,aYZGetCoord,aYZName));
450         if(anIsXDimension && anIsZDimension)
451           aCoordHelperPtr.reset(new TCoordHelper(aNodesIter,aXZGetCoord,aXZName));
452         break;
453       case 1:
454         if(anIsXDimension)
455           aCoordHelperPtr.reset(new TCoordHelper(aNodesIter,aXGetCoord,aXName));
456         if(anIsYDimension)
457           aCoordHelperPtr.reset(new TCoordHelper(aNodesIter,aYGetCoord,aYName));
458         if(anIsZDimension)
459           aCoordHelperPtr.reset(new TCoordHelper(aNodesIter,aZGetCoord,aZName));
460         break;
461       }
462     }
463
464     MED::PWrapper myMed = CrWrapperW(myFile, myVersion);
465     PMeshInfo aMeshInfo = myMed->CrMeshInfo(aMeshDimension,aSpaceDimension,aMeshName);
466     //MESSAGE("Add - aMeshName : "<<aMeshName<<"; "<<aMeshInfo->GetName());
467     myMed->SetMeshInfo(aMeshInfo);
468
469     // Storing SMDS groups and sub-meshes as med families
470     //----------------------------------------------------
471     int myNodesDefaultFamilyId      = 0;
472     int my0DElementsDefaultFamilyId = 0;
473     int myBallsDefaultFamilyId      = 0;
474     int myEdgesDefaultFamilyId      = 0;
475     int myFacesDefaultFamilyId      = 0;
476     int myVolumesDefaultFamilyId    = 0;
477     int nbNodes      = myMesh->NbNodes();
478     int nb0DElements = myMesh->Nb0DElements();
479     int nbBalls      = myMesh->NbBalls();
480     int nbEdges      = myMesh->NbEdges();
481     int nbFaces      = myMesh->NbFaces();
482     int nbVolumes    = myMesh->NbVolumes();
483     if (myDoGroupOfNodes)   myNodesDefaultFamilyId      = REST_NODES_FAMILY;
484     if (myDoGroupOfEdges)   myEdgesDefaultFamilyId      = REST_EDGES_FAMILY;
485     if (myDoGroupOfFaces)   myFacesDefaultFamilyId      = REST_FACES_FAMILY;
486     if (myDoGroupOfVolumes) myVolumesDefaultFamilyId    = REST_VOLUMES_FAMILY;
487     if (myDoGroupOf0DElems) my0DElementsDefaultFamilyId = REST_0DELEM_FAMILY;
488     if (myDoGroupOfBalls)   myBallsDefaultFamilyId      = REST_BALL_FAMILY;
489     if (myDoAllInGroups )
490     {
491       if (!myDoGroupOfEdges)   myEdgesDefaultFamilyId      = NIG_EDGES_FAMILY   ;
492       if (!myDoGroupOfFaces)   myFacesDefaultFamilyId      = NIG_FACES_FAMILY   ;
493       if (!myDoGroupOfVolumes) myVolumesDefaultFamilyId    = NIG_VOLS_FAMILY    ;
494       if (!myDoGroupOf0DElems) my0DElementsDefaultFamilyId = NIG_0DELEM_FAMILY  ;
495       if (!myDoGroupOfBalls)   myBallsDefaultFamilyId      = NIG_BALL_FAMILY    ;
496     }
497
498     //MESSAGE("Perform - aFamilyInfo");
499     list<DriverMED_FamilyPtr> aFamilies;
500     if (myAllSubMeshes) {
501       aFamilies = DriverMED_Family::MakeFamilies
502         (myMesh->SubMeshes(), myGroups,
503          myDoGroupOfNodes   && nbNodes,
504          myDoGroupOfEdges   && nbEdges,
505          myDoGroupOfFaces   && nbFaces,
506          myDoGroupOfVolumes && nbVolumes,
507          myDoGroupOf0DElems && nb0DElements,
508          myDoGroupOfBalls   && nbBalls,
509          myDoAllInGroups);
510     }
511     else {
512       aFamilies = DriverMED_Family::MakeFamilies
513         (getIterator( mySubMeshes ), myGroups,
514          myDoGroupOfNodes   && nbNodes,
515          myDoGroupOfEdges   && nbEdges,
516          myDoGroupOfFaces   && nbFaces,
517          myDoGroupOfVolumes && nbVolumes,
518          myDoGroupOf0DElems && nb0DElements,
519          myDoGroupOfBalls   && nbBalls,
520          myDoAllInGroups);
521     }
522     list<DriverMED_FamilyPtr>::iterator aFamsIter;
523     for (aFamsIter = aFamilies.begin(); aFamsIter != aFamilies.end(); aFamsIter++)
524     {
525       PFamilyInfo aFamilyInfo = (*aFamsIter)->GetFamilyInfo(myMed,aMeshInfo);
526       myMed->SetFamilyInfo(aFamilyInfo);
527     }
528
529     // Storing SMDS nodes to the MED file for the MED mesh
530     //----------------------------------------------------
531 #ifdef _EDF_NODE_IDS_
532     typedef map<TInt,TInt> TNodeIdMap;
533     TNodeIdMap aNodeIdMap;
534 #endif
535     const EModeSwitch   theMode        = eFULL_INTERLACE;
536     const ERepere       theSystem      = eCART;
537     const EBooleen      theIsElemNum   = eVRAI;
538     const EBooleen      theIsElemNames = eFAUX;
539     const EConnectivite theConnMode    = eNOD;
540
541     TInt aNbNodes = myMesh->NbNodes();
542     PNodeInfo aNodeInfo = myMed->CrNodeInfo(aMeshInfo, aNbNodes,
543                                             theMode, theSystem, theIsElemNum, theIsElemNames);
544
545     // find family numbers for nodes
546     TElemFamilyMap anElemFamMap;
547     fillElemFamilyMap( anElemFamMap, aFamilies, SMDSAbs_Node );
548
549     for (TInt iNode = 0; aCoordHelperPtr->Next(); iNode++)
550     {
551       // coordinates
552       TCoordSlice aTCoordSlice = aNodeInfo->GetCoordSlice( iNode );
553       for(TInt iCoord = 0; iCoord < aSpaceDimension; iCoord++){
554         aTCoordSlice[iCoord] = aCoordHelperPtr->GetCoord(iCoord);
555       }
556       if ( aSpaceDimension == 3 &&
557            -myZTolerance < aTCoordSlice[2] && aTCoordSlice[2] < myZTolerance )
558         aTCoordSlice[2] = 0.;
559
560       // node number
561       int aNodeID = aCoordHelperPtr->GetID();
562       aNodeInfo->SetElemNum( iNode, aNodeID );
563 #ifdef _EDF_NODE_IDS_
564       aNodeIdMap.insert( aNodeIdMap.end(), make_pair( aNodeID, iNode+1 ));
565 #endif
566       // family number
567       const SMDS_MeshNode* aNode = aCoordHelperPtr->GetNode();
568       int famNum = getFamilyId( anElemFamMap, aNode, myNodesDefaultFamilyId );
569       aNodeInfo->SetFamNum( iNode, famNum );
570     }
571     anElemFamMap.Clear();
572
573     // coordinate names and units
574     for (TInt iCoord = 0; iCoord < aSpaceDimension; iCoord++) {
575       aNodeInfo->SetCoordName( iCoord, aCoordHelperPtr->GetName(iCoord));
576       aNodeInfo->SetCoordUnit( iCoord, aCoordHelperPtr->GetUnit(iCoord));
577     }
578
579     //MESSAGE("Perform - aNodeInfo->GetNbElem() = "<<aNbNodes);
580     myMed->SetNodeInfo(aNodeInfo);
581     aNodeInfo.reset(); // free memory used for arrays
582
583
584     // Storing SMDS elements to the MED file for the MED mesh
585     //-------------------------------------------------------
586     // Write one element type at once in order to minimize memory usage (PAL19276)
587
588     const SMDS_MeshInfo& nbElemInfo = myMesh->GetMeshInfo();
589
590     // poly elements are not supported by med-2.1
591     bool polyTypesSupported = ( myMed->CrPolygoneInfo(aMeshInfo,eMAILLE,ePOLYGONE,0,0).get() != 0 );
592     TInt nbPolygonNodes = 0, nbPolyhedronNodes = 0, nbPolyhedronFaces = 0;
593
594     // nodes on VERTEXes where 0D elements are absent
595     std::vector<const SMDS_MeshElement*> nodesOf0D;
596     std::vector< SMDS_ElemIteratorPtr > iterVec;
597     SMDS_ElemIteratorPtr iterVecIter;
598     if ( myAddODOnVertices && getNodesOfMissing0DOnVert( myMesh, nodesOf0D ))
599     {
600       iterVec.resize(2);
601       iterVec[0] = myMesh->elementsIterator( SMDSAbs_0DElement );
602       iterVec[1] = SMDS_ElemIteratorPtr
603         ( new SMDS_ElementVectorIterator( nodesOf0D.begin(), nodesOf0D.end() ));
604
605       typedef SMDS_IteratorOnIterators
606         < const SMDS_MeshElement *, std::vector< SMDS_ElemIteratorPtr > > TItIterator;
607       iterVecIter = SMDS_ElemIteratorPtr( new TItIterator( iterVec ));
608     }
609
610     // collect info on all geom types
611
612     list< TElemTypeData > aTElemTypeDatas;
613
614     EEntiteMaillage anEntity = eMAILLE;
615 #ifdef _ELEMENTS_BY_DIM_
616     anEntity = eNOEUD_ELEMENT;
617 #endif
618     aTElemTypeDatas.push_back(TElemTypeData(anEntity,
619                                             ePOINT1,
620                                             nbElemInfo.Nb0DElements() + nodesOf0D.size(),
621                                             SMDSAbs_0DElement));
622 #ifdef _ELEMENTS_BY_DIM_
623     anEntity = eSTRUCT_ELEMENT;
624 #endif
625     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
626                                              eBALL,
627                                              nbElemInfo.NbBalls(),
628                                              SMDSAbs_Ball));
629 #ifdef _ELEMENTS_BY_DIM_
630     anEntity = eARETE;
631 #endif
632     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
633                                              eSEG2,
634                                              nbElemInfo.NbEdges( ORDER_LINEAR ),
635                                              SMDSAbs_Edge));
636     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
637                                              eSEG3,
638                                              nbElemInfo.NbEdges( ORDER_QUADRATIC ),
639                                              SMDSAbs_Edge));
640 #ifdef _ELEMENTS_BY_DIM_
641     anEntity = eFACE;
642 #endif
643     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
644                                              eTRIA3,
645                                              nbElemInfo.NbTriangles( ORDER_LINEAR ),
646                                              SMDSAbs_Face));
647     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
648                                              eTRIA6,
649                                              nbElemInfo.NbTriangles( ORDER_QUADRATIC ) -
650                                              nbElemInfo.NbBiQuadTriangles(),
651                                              SMDSAbs_Face));
652     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
653                                              eTRIA7,
654                                              nbElemInfo.NbBiQuadTriangles(),
655                                              SMDSAbs_Face));
656     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
657                                              eQUAD4,
658                                              nbElemInfo.NbQuadrangles( ORDER_LINEAR ),
659                                              SMDSAbs_Face));
660     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
661                                              eQUAD8,
662                                              nbElemInfo.NbQuadrangles( ORDER_QUADRATIC ) -
663                                              nbElemInfo.NbBiQuadQuadrangles(),
664                                              SMDSAbs_Face));
665     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
666                                              eQUAD9,
667                                              nbElemInfo.NbBiQuadQuadrangles(),
668                                              SMDSAbs_Face));
669     if ( polyTypesSupported ) {
670       aTElemTypeDatas.push_back( TElemTypeData(anEntity,
671                                                ePOLYGONE,
672                                                nbElemInfo.NbPolygons( ORDER_LINEAR ),
673                                                SMDSAbs_Face));
674       // we need one more loop on poly elements to count nb of their nodes
675       aTElemTypeDatas.push_back( TElemTypeData(anEntity,
676                                                ePOLYGONE,
677                                                nbElemInfo.NbPolygons( ORDER_LINEAR ),
678                                                SMDSAbs_Face));
679       aTElemTypeDatas.push_back( TElemTypeData(anEntity,
680                                                ePOLYGON2,
681                                                nbElemInfo.NbPolygons( ORDER_QUADRATIC ),
682                                                SMDSAbs_Face));
683       // we need one more loop on QUAD poly elements to count nb of their nodes
684       aTElemTypeDatas.push_back( TElemTypeData(anEntity,
685                                                ePOLYGON2,
686                                                nbElemInfo.NbPolygons( ORDER_QUADRATIC ),
687                                                SMDSAbs_Face));
688     }
689 #ifdef _ELEMENTS_BY_DIM_
690     anEntity = eMAILLE;
691 #endif
692     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
693                                              eTETRA4,
694                                              nbElemInfo.NbTetras( ORDER_LINEAR ),
695                                              SMDSAbs_Volume));
696     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
697                                              eTETRA10,
698                                              nbElemInfo.NbTetras( ORDER_QUADRATIC ),
699                                              SMDSAbs_Volume));
700     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
701                                              ePYRA5,
702                                              nbElemInfo.NbPyramids( ORDER_LINEAR ),
703                                              SMDSAbs_Volume));
704     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
705                                              ePYRA13,
706                                              nbElemInfo.NbPyramids( ORDER_QUADRATIC ),
707                                              SMDSAbs_Volume));
708     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
709                                              ePENTA6,
710                                              nbElemInfo.NbPrisms( ORDER_LINEAR ),
711                                              SMDSAbs_Volume));
712     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
713                                              ePENTA15,
714                                              nbElemInfo.NbQuadPrisms(),
715                                              SMDSAbs_Volume));
716     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
717                                              ePENTA18,
718                                              nbElemInfo.NbBiQuadPrisms(),
719                                              SMDSAbs_Volume));
720     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
721                                              eHEXA8,
722                                              nbElemInfo.NbHexas( ORDER_LINEAR ),
723                                              SMDSAbs_Volume));
724     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
725                                              eHEXA20,
726                                              nbElemInfo.NbHexas( ORDER_QUADRATIC )-
727                                              nbElemInfo.NbTriQuadHexas(),
728                                              SMDSAbs_Volume));
729     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
730                                              eHEXA27,
731                                              nbElemInfo.NbTriQuadHexas(),
732                                              SMDSAbs_Volume));
733     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
734                                              eOCTA12,
735                                              nbElemInfo.NbHexPrisms(),
736                                              SMDSAbs_Volume));
737     if ( polyTypesSupported ) {
738       aTElemTypeDatas.push_back( TElemTypeData(anEntity,
739                                                ePOLYEDRE,
740                                                nbElemInfo.NbPolyhedrons(),
741                                                SMDSAbs_Volume));
742       // we need one more loop on poly elements to count nb of their nodes
743       aTElemTypeDatas.push_back( TElemTypeData(anEntity,
744                                                ePOLYEDRE,
745                                                nbElemInfo.NbPolyhedrons(),
746                                                SMDSAbs_Volume));
747     }
748
749     vector< bool > isElemFamMapBuilt( SMDSAbs_NbElementTypes, false );
750
751     // loop on all geom types of elements
752
753     list< TElemTypeData >::iterator aElemTypeData = aTElemTypeDatas.begin();
754     for ( ; aElemTypeData != aTElemTypeDatas.end(); ++aElemTypeData )
755     {
756       if ( aElemTypeData->_nbElems == 0 )
757         continue;
758
759       int defaultFamilyId = 0;
760       switch ( aElemTypeData->_smdsType ) {
761       case SMDSAbs_0DElement: defaultFamilyId = my0DElementsDefaultFamilyId; break;
762       case SMDSAbs_Ball:      defaultFamilyId = myBallsDefaultFamilyId;      break;
763       case SMDSAbs_Edge:      defaultFamilyId = myEdgesDefaultFamilyId;      break;
764       case SMDSAbs_Face:      defaultFamilyId = myFacesDefaultFamilyId;      break;
765       case SMDSAbs_Volume:    defaultFamilyId = myVolumesDefaultFamilyId;    break;
766       default:
767         continue;
768       }
769
770       // build map of family numbers for this type
771       if ( !isElemFamMapBuilt[ aElemTypeData->_smdsType ])
772       {
773         fillElemFamilyMap( anElemFamMap, aFamilies, aElemTypeData->_smdsType );
774         isElemFamMapBuilt[ aElemTypeData->_smdsType ] = true;
775       }
776
777       // iterator on elements of a current type
778       SMDS_ElemIteratorPtr elemIterator;
779       int iElem = 0;
780
781       // Treat POLYGONs
782       // ---------------
783       if ( aElemTypeData->_geomType == ePOLYGONE ||
784            aElemTypeData->_geomType == ePOLYGON2 )
785       {
786         if ( aElemTypeData->_geomType == ePOLYGONE )
787           elemIterator = myMesh->elementEntityIterator( SMDSEntity_Polygon );
788         else
789           elemIterator = myMesh->elementEntityIterator( SMDSEntity_Quad_Polygon );
790
791         if ( nbPolygonNodes == 0 ) {
792           // Count nb of nodes
793           while ( elemIterator->more() ) {
794             const SMDS_MeshElement* anElem = elemIterator->next();
795             nbPolygonNodes += anElem->NbNodes();
796             if ( ++iElem == aElemTypeData->_nbElems )
797               break;
798           }
799         }
800         else {
801           // Store in med file
802           PPolygoneInfo aPolygoneInfo = myMed->CrPolygoneInfo(aMeshInfo,
803                                                               aElemTypeData->_entity,
804                                                               aElemTypeData->_geomType,
805                                                               aElemTypeData->_nbElems,
806                                                               nbPolygonNodes,
807                                                               theConnMode, theIsElemNum,
808                                                               theIsElemNames);
809           TElemNum & index = *(aPolygoneInfo->myIndex.get());
810           index[0] = 1;
811
812           while ( elemIterator->more() )
813           {
814             const SMDS_MeshElement* anElem = elemIterator->next();
815             // index
816             TInt aNbNodes = anElem->NbNodes();
817             index[ iElem+1 ] = index[ iElem ] + aNbNodes;
818
819             // connectivity
820             TConnSlice aTConnSlice = aPolygoneInfo->GetConnSlice( iElem );
821             for(TInt iNode = 0; iNode < aNbNodes; iNode++) {
822               const SMDS_MeshElement* aNode = anElem->GetNode( iNode );
823 #ifdef _EDF_NODE_IDS_
824               aTConnSlice[ iNode ] = aNodeIdMap[aNode->GetID()];
825 #else
826               aTConnSlice[ iNode ] = aNode->GetID();
827 #endif
828             }
829             // element number
830             aPolygoneInfo->SetElemNum( iElem, anElem->GetID() );
831
832             // family number
833             int famNum = getFamilyId( anElemFamMap, anElem, defaultFamilyId );
834             aPolygoneInfo->SetFamNum( iElem, famNum );
835
836             if ( ++iElem == aPolygoneInfo->GetNbElem() )
837               break;
838           }
839           myMed->SetPolygoneInfo(aPolygoneInfo);
840
841           nbPolygonNodes = 0; // to treat next polygon type
842         }
843       }
844
845       // Treat POLYEDREs
846       // ----------------
847       else if ( aElemTypeData->_geomType == ePOLYEDRE )
848       {
849         elemIterator = myMesh->elementGeomIterator( SMDSGeom_POLYHEDRA );
850
851         if ( nbPolyhedronNodes == 0 ) {
852           // Count nb of nodes
853           while ( elemIterator->more() ) {
854             const SMDS_MeshElement*  anElem = elemIterator->next();
855             nbPolyhedronNodes += anElem->NbNodes();
856             nbPolyhedronFaces += anElem->NbFaces();
857             if ( ++iElem == aElemTypeData->_nbElems )
858               break;
859           }
860         }
861         else {
862           // Store in med file
863           PPolyedreInfo aPolyhInfo = myMed->CrPolyedreInfo(aMeshInfo,
864                                                            aElemTypeData->_entity,
865                                                            aElemTypeData->_geomType,
866                                                            aElemTypeData->_nbElems,
867                                                            nbPolyhedronFaces+1,
868                                                            nbPolyhedronNodes,
869                                                            theConnMode,
870                                                            theIsElemNum,
871                                                            theIsElemNames);
872           TElemNum & index = *(aPolyhInfo->myIndex.get());
873           TElemNum & faces = *(aPolyhInfo->myFaces.get());
874           TElemNum & conn  = *(aPolyhInfo->myConn.get());
875           index[0] = 1;
876           faces[0] = 1;
877
878           TInt iFace = 0, iNode = 0;
879           while ( elemIterator->more() )
880           {
881             const SMDS_MeshElement* anElem = elemIterator->next();
882             const SMDS_MeshVolume *aPolyedre = myMesh->DownCast< SMDS_MeshVolume >( anElem );
883             if ( !aPolyedre ) continue;
884             // index
885             TInt aNbFaces = aPolyedre->NbFaces();
886             index[ iElem+1 ] = index[ iElem ] + aNbFaces;
887
888             // face index
889             for (TInt f = 1; f <= aNbFaces; ++f, ++iFace ) {
890               int aNbFaceNodes = aPolyedre->NbFaceNodes( f );
891               faces[ iFace+1 ] = faces[ iFace ] + aNbFaceNodes;
892             }
893             // connectivity
894             SMDS_ElemIteratorPtr nodeIt = anElem->nodesIterator();
895             while ( nodeIt->more() ) {
896               const SMDS_MeshElement* aNode = nodeIt->next();
897 #ifdef _EDF_NODE_IDS_
898               conn[ iNode ] = aNodeIdMap[aNode->GetID()];
899 #else
900               conn[ iNode ] = aNode->GetID();
901 #endif
902               ++iNode;
903             }
904             // element number
905             aPolyhInfo->SetElemNum( iElem, anElem->GetID() );
906
907             // family number
908             int famNum = getFamilyId( anElemFamMap, anElem, defaultFamilyId );
909             aPolyhInfo->SetFamNum( iElem, famNum );
910
911             if ( ++iElem == aPolyhInfo->GetNbElem() )
912               break;
913           }
914           myMed->SetPolyedreInfo(aPolyhInfo);
915         }
916       } // if (aElemTypeData->_geomType == ePOLYEDRE )
917
918       // Treat BALLs
919       // ----------------
920       else if (aElemTypeData->_geomType == eBALL )
921       {
922         // allocate data arrays
923         PBallInfo aBallInfo = myMed->CrBallInfo( aMeshInfo, aElemTypeData->_nbElems );
924
925         elemIterator = myMesh->elementsIterator( SMDSAbs_Ball );
926         while ( elemIterator->more() )
927         {
928           const SMDS_MeshElement* anElem = elemIterator->next();
929           // connectivity
930           const SMDS_MeshElement* aNode = anElem->GetNode( 0 );
931 #ifdef _EDF_NODE_IDS_
932           (*aBallInfo->myConn)[ iElem ] = aNodeIdMap[aNode->GetID()];
933 #else
934           (*aBallInfo->myConn)[ iElem ] = aNode->GetID();
935 #endif
936           // element number
937           aBallInfo->SetElemNum( iElem, anElem->GetID() );
938
939           // diameter
940           aBallInfo->myDiameters[ iElem ] =
941             static_cast<const SMDS_BallElement*>( anElem )->GetDiameter();
942
943           // family number
944           int famNum = getFamilyId( anElemFamMap, anElem, defaultFamilyId );
945           aBallInfo->SetFamNum( iElem, famNum );
946           ++iElem;
947         }
948         // store data in a file
949         myMed->SetBallInfo(aBallInfo);
950       }
951
952       else
953       {
954         // Treat standard types
955         // ---------------------
956         // allocate data arrays
957         PCellInfo aCellInfo = myMed->CrCellInfo( aMeshInfo,
958                                                  aElemTypeData->_entity,
959                                                  aElemTypeData->_geomType,
960                                                  aElemTypeData->_nbElems,
961                                                  theConnMode,
962                                                  theIsElemNum,
963                                                  theIsElemNames);
964
965         TInt aNbNodes = MED::GetNbNodes(aElemTypeData->_geomType);
966         elemIterator = myMesh->elementsIterator( aElemTypeData->_smdsType );
967         if ( aElemTypeData->_smdsType == SMDSAbs_0DElement && ! nodesOf0D.empty() )
968           elemIterator = iterVecIter;
969         while ( elemIterator->more() )
970         {
971           const SMDS_MeshElement* anElem = elemIterator->next();
972           if ( anElem->NbNodes() != aNbNodes || anElem->IsPoly() )
973             continue; // other geometry
974
975           // connectivity
976           TConnSlice aTConnSlice = aCellInfo->GetConnSlice( iElem );
977           for (TInt iNode = 0; iNode < aNbNodes; iNode++) {
978             const SMDS_MeshElement* aNode = anElem->GetNode( iNode );
979 #ifdef _EDF_NODE_IDS_
980             aTConnSlice[ iNode ] = aNodeIdMap[aNode->GetID()];
981 #else
982             aTConnSlice[ iNode ] = aNode->GetID();
983 #endif
984           }
985           // element number
986           aCellInfo->SetElemNum( iElem, anElem->GetID() );
987
988           // family number
989           int famNum = getFamilyId( anElemFamMap, anElem, defaultFamilyId );
990           aCellInfo->SetFamNum( iElem, famNum );
991
992           if ( ++iElem == aCellInfo->GetNbElem() )
993             break;
994         }
995         // store data in a file
996         myMed->SetCellInfo(aCellInfo);
997       }
998     } // loop on geom types
999   }
1000   catch(const std::exception& exc) {
1001     INFOS("The following exception was caught:\n\t"<<exc.what());
1002     throw;
1003   }
1004   catch(...) {
1005     INFOS("Unknown exception was caught !!!");
1006     throw;
1007   }
1008
1009   myMeshId = -1;
1010   myGroups.clear();
1011   mySubMeshes.clear();
1012   return aResult;
1013 }
1014
1015 //================================================================================
1016 /*!
1017  * \brief Returns nodes on VERTEXes where 0D elements are absent
1018  */
1019 //================================================================================
1020
1021 bool DriverMED_W_SMESHDS_Mesh::
1022 getNodesOfMissing0DOnVert(SMESHDS_Mesh*                         meshDS,
1023                           std::vector<const SMDS_MeshElement*>& nodes)
1024 {
1025   nodes.clear();
1026   for ( int i = 1; i <= meshDS->MaxShapeIndex(); ++i )
1027   {
1028     if ( meshDS->IndexToShape( i ).ShapeType() != TopAbs_VERTEX )
1029       continue;
1030     if ( SMESHDS_SubMesh* sm = meshDS->MeshElements(i) ) {
1031       SMDS_NodeIteratorPtr nIt= sm->GetNodes();
1032       while (nIt->more())
1033       {
1034         const SMDS_MeshNode* n = nIt->next();
1035         if ( n->NbInverseElements( SMDSAbs_0DElement ) == 0 )
1036           nodes.push_back( n );
1037       }
1038     }
1039   }
1040   return !nodes.empty();
1041 }