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