Salome HOME
23308: [EDF] Re-implement DISTENE meshing plugins to use libraries instead of executables
authoreap <eap@opencascade.com>
Tue, 23 Aug 2016 10:36:25 +0000 (13:36 +0300)
committereap <eap@opencascade.com>
Tue, 23 Aug 2016 10:36:25 +0000 (13:36 +0300)
CMakeLists.txt
src/GHS3DPlugin/CMakeLists.txt
src/GHS3DPlugin/GHS3DPlugin_GHS3D.cxx
src/GHS3DPlugin/GHS3DPlugin_GHS3D.hxx
src/GHS3DPlugin/GHS3DPlugin_Hypothesis.cxx
src/GHS3DPlugin/GHS3DPlugin_Hypothesis.hxx
src/GHS3DPlugin/MG_Tetra_API.cxx [new file with mode: 0644]
src/GHS3DPlugin/MG_Tetra_API.hxx [new file with mode: 0644]

index 1fff0e4b19eeac052d8952ab1fa03d19d6bedaf6..6e59bb629464374aca2516707e211db178ea875e 100755 (executable)
@@ -69,6 +69,7 @@ SET(BUILD_SHARED_LIBS TRUE)
 # ============
 OPTION(SALOME_BUILD_TESTS "Build SALOME tests" ON)
 OPTION(SALOME_BUILD_DOC "Generate SALOME GHS3DPLUGIN documentation" ON)
+OPTION(SALOME_USE_MG_LIBS "Use MeshGems libraries" ON)
 
 IF(SALOME_BUILD_TESTS)
   ENABLE_TESTING()
@@ -77,6 +78,8 @@ ENDIF()
 # Advanced options:
 OPTION(SALOME_BUILD_GUI "Enable GUI" ON)
 
+MARK_AS_ADVANCED(SALOME_USE_MG_LIBS)
+
 ##
 ## From KERNEL:
 ##
@@ -165,6 +168,15 @@ ELSE(EXISTS ${SMESH_ROOT_DIR})
   MESSAGE(FATAL_ERROR "We absolutely need a Salome SMESH, please define SMESH_ROOT_DIR")
 ENDIF(EXISTS ${SMESH_ROOT_DIR})
 
+##
+## Find MESHGEMS
+## =============
+IF(SALOME_USE_MG_LIBS)
+  FIND_PACKAGE(SalomeMESHGEMS)
+  SALOME_LOG_OPTIONAL_PACKAGE(MESHGEMS SALOME_USE_MG_LIBS)
+  ADD_DEFINITIONS(-DUSE_MG_LIBS)
+ENDIF(SALOME_USE_MG_LIBS)
+
 # Detection summary:
 SALOME_PACKAGE_REPORT_AND_CHECK()
 
@@ -253,17 +265,18 @@ EXPORT(TARGETS ${_${PROJECT_NAME}_exposed_targets}
 
 # Ensure the variables are always defined for the configure:
 SET(SMESH_ROOT_DIR "${SMESH_ROOT_DIR}")
+SET(MESHGEMS_ROOT_DIR "${MESHGEMS_ROOT_DIR}")
  
 SET(CONF_INCLUDE_DIRS "${PROJECT_SOURCE_DIR}/include" "${PROJECT_BINARY_DIR}/include")
 
 # Build variables that will be expanded when configuring Salome<MODULE>Config.cmake:
-# SALOME_CONFIGURE_PREPARE() #For use in the future
+SALOME_CONFIGURE_PREPARE(MESHGEMS)
 
 CONFIGURE_PACKAGE_CONFIG_FILE(${PROJECT_NAME}Config.cmake.in 
     ${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake
     INSTALL_DESTINATION "${SALOME_INSTALL_CMAKE_LOCAL}"
     PATH_VARS CONF_INCLUDE_DIRS SALOME_INSTALL_CMAKE_LOCAL CMAKE_INSTALL_PREFIX
-    SMESH_ROOT_DIR)
+    SMESH_ROOT_DIR MESHGEMS_ROOT_DIR)
 
 WRITE_BASIC_PACKAGE_VERSION_FILE(${PROJECT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake
     VERSION ${${PROJECT_NAME_UC}_VERSION}
index 1ca4bdd256ab943dcd4e0b7a88a565f807cd65e5..1f49d548e1deec2f0858935f52dd976ce17309f5 100644 (file)
@@ -25,6 +25,7 @@ INCLUDE_DIRECTORIES(
   ${GEOM_INCLUDE_DIRS}
   ${SMESH_INCLUDE_DIRS}
   ${VTK_INCLUDE_DIRS}
+  ${MESHGEMS_INCLUDE_DIRS}
   ${Boost_INCLUDE_DIRS}
   ${OMNIORB_INCLUDE_DIR}
   ${PROJECT_BINARY_DIR}/idl
@@ -46,6 +47,7 @@ SET(_link_LIBRARIES
   ${CAS_TKGeomBase}
   ${CAS_TKGeomAlgo}
   ${CAS_TKCDF}
+  ${MESHGEMS_TETRA_LIBRARY}
   ${SMESH_SMESHimpl}
   ${SMESH_SMESHEngine}
   ${SMESH_SMESHDS}
@@ -69,6 +71,7 @@ SET(GHS3DEngine_HEADERS
   GHS3DPlugin_GHS3D_i.hxx
   GHS3DPlugin_Hypothesis.hxx
   GHS3DPlugin_Hypothesis_i.hxx
+  MG_Tetra_API.hxx
 )
 
 # --- sources ---
@@ -80,6 +83,7 @@ SET(GHS3DEngine_SOURCES
   GHS3DPlugin_i.cxx
   GHS3DPlugin_Hypothesis.cxx
   GHS3DPlugin_Hypothesis_i.cxx
+  MG_Tetra_API.cxx
 )
 
 # --- scripts ---
index 3c546076cf44022e5a1584ea6935589f0540e3da..f6dff504912b4430cec12e70a7947d3bc631a639 100644 (file)
@@ -26,6 +26,7 @@
 //
 #include "GHS3DPlugin_GHS3D.hxx"
 #include "GHS3DPlugin_Hypothesis.hxx"
+#include "MG_Tetra_API.hxx"
 
 #include <SMDS_FaceOfNodes.hxx>
 #include <SMDS_LinearEdge.hxx>
@@ -35,6 +36,7 @@
 #include <SMESHDS_Group.hxx>
 #include <SMESHDS_Mesh.hxx>
 #include <SMESH_Comment.hxx>
+#include <SMESH_File.hxx>
 #include <SMESH_Group.hxx>
 #include <SMESH_HypoFilter.hxx>
 #include <SMESH_Mesh.hxx>
@@ -58,7 +60,6 @@
 #include <Bnd_Box.hxx>
 #include <GProp_GProps.hxx>
 #include <GeomAPI_ProjectPointOnSurf.hxx>
-#include <OSD_File.hxx>
 #include <Precision.hxx>
 #include <Standard_ErrorHandler.hxx>
 #include <Standard_Failure.hxx>
 #include <Basics_Utils.hxx>
 #include <utilities.h>
 
-#ifdef WIN32
-#include <io.h>
-#else
-#include <sys/sysinfo.h>
-#endif
 #include <algorithm>
 #include <errno.h>
 
-#define castToNode(n) static_cast<const SMDS_MeshNode *>( n );
-
-extern "C"
-{
-#ifndef WIN32
-#include <unistd.h>
-#include <sys/mman.h>
+#ifdef _DEBUG_
+//#define _MY_DEBUG_
 #endif
-#include <sys/stat.h>
-#include <fcntl.h>
-}
+
+#define castToNode(n) static_cast<const SMDS_MeshNode *>( n );
 
 using namespace std;
 
@@ -129,9 +119,9 @@ static const char theDomainGroupNamePrefix[] = "Domain_";
 static void removeFile( const TCollection_AsciiString& fileName )
 {
   try {
-    OSD_File( fileName ).Remove();
+    SMESH_File( fileName.ToCString() ).remove();
   }
-  catch ( Standard_ProgramError ) {
+  catch ( ... ) {
     MESSAGE("Can't remove file: " << fileName.ToCString() << " ; file does not exist or permission denied");
   }
 }
@@ -143,7 +133,7 @@ static void removeFile( const TCollection_AsciiString& fileName )
 //=============================================================================
 
 GHS3DPlugin_GHS3D::GHS3DPlugin_GHS3D(int hypId, int studyId, SMESH_Gen* gen)
-  : SMESH_3D_Algo(hypId, studyId, gen)
+  : SMESH_3D_Algo(hypId, studyId, gen), _isLibUsed( false )
 {
   MESSAGE("GHS3DPlugin_GHS3D::GHS3DPlugin_GHS3D");
   _name = Name();
@@ -155,16 +145,16 @@ GHS3DPlugin_GHS3D::GHS3DPlugin_GHS3D(int hypId, int studyId, SMESH_Gen* gen)
   _compatibleHypothesis.push_back( StdMeshers_ViscousLayers::GetHypType() );
   _requireShape = false; // can work without shape_studyId
 
-  smeshGen_i = SMESH_Gen_i::GetSMESHGen();
-  CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
+  _smeshGen_i = SMESH_Gen_i::GetSMESHGen();
+  CORBA::Object_var anObject = _smeshGen_i->GetNS()->Resolve("/myStudyManager");
   SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
 
   MESSAGE("studyid = " << _studyId);
 
-  myStudy = NULL;
-  myStudy = aStudyMgr->GetStudyByID(_studyId);
-  if (myStudy)
-    MESSAGE("myStudy->StudyId() = " << myStudy->StudyId());
+  _study = NULL;
+  _study = aStudyMgr->GetStudyByID(_studyId);
+  if (!_study->_is_nil())
+    MESSAGE("_study->StudyId() = " << _study->StudyId());
   
   _compute_canceled = false;
 }
@@ -230,61 +220,21 @@ bool GHS3DPlugin_GHS3D::CheckHypothesis ( SMESH_Mesh&         aMesh,
 TopoDS_Shape GHS3DPlugin_GHS3D::entryToShape(std::string entry)
 {
   MESSAGE("GHS3DPlugin_GHS3D::entryToShape "<<entry );
+  if ( _study->_is_nil() )
+    throw SALOME_Exception("MG-Tetra plugin can't work w/o publishing in the study");
   GEOM::GEOM_Object_var aGeomObj;
   TopoDS_Shape S = TopoDS_Shape();
-  SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
+  SALOMEDS::SObject_var aSObj = _study->FindObjectID( entry.c_str() );
   if (!aSObj->_is_nil() ) {
     CORBA::Object_var obj = aSObj->GetObject();
     aGeomObj = GEOM::GEOM_Object::_narrow(obj);
     aSObj->UnRegister();
   }
   if ( !aGeomObj->_is_nil() )
-    S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
+    S = _smeshGen_i->GeomObjectToShape( aGeomObj.in() );
   return S;
 }
 
-//=======================================================================
-//function : findShape
-//purpose  : 
-//=======================================================================
-
-// static TopoDS_Shape findShape(const SMDS_MeshNode *aNode[],
-//                               TopoDS_Shape        aShape,
-//                               const TopoDS_Shape  shape[],
-//                               double**            box,
-//                               const int           nShape,
-//                               TopAbs_State *      state = 0)
-// {
-//   gp_XYZ aPnt(0,0,0);
-//   int j, iShape, nbNode = 4;
-
-//   for ( j=0; j<nbNode; j++ ) {
-//     gp_XYZ p ( aNode[j]->X(), aNode[j]->Y(), aNode[j]->Z() );
-//     if ( aNode[j]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE ) {
-//       aPnt = p;
-//       break;
-//     }
-//     aPnt += p / nbNode;
-//   }
-
-//   BRepClass3d_SolidClassifier SC (aShape, aPnt, Precision::Confusion());
-//   if (state) *state = SC.State();
-//   if ( SC.State() != TopAbs_IN || aShape.IsNull() || aShape.ShapeType() != TopAbs_SOLID) {
-//     for (iShape = 0; iShape < nShape; iShape++) {
-//       aShape = shape[iShape];
-//       if ( !( aPnt.X() < box[iShape][0] || box[iShape][1] < aPnt.X() ||
-//               aPnt.Y() < box[iShape][2] || box[iShape][3] < aPnt.Y() ||
-//               aPnt.Z() < box[iShape][4] || box[iShape][5] < aPnt.Z()) ) {
-//         BRepClass3d_SolidClassifier SC (aShape, aPnt, Precision::Confusion());
-//         if (state) *state = SC.State();
-//         if (SC.State() == TopAbs_IN)
-//           break;
-//       }
-//     }
-//   }
-//   return aShape;
-// }
-
 //================================================================================
 /*!
  * \brief returns id of a solid if a triangle defined by the nodes is a temporary face on a
@@ -630,7 +580,8 @@ static void makeDomainGroups( std::vector< std::vector< const SMDS_MeshElement*
 //purpose  : read GMF file w/o geometry associated to mesh
 //=======================================================================
 
-static bool readGMFFile(const char*                     theFile,
+static bool readGMFFile(MG_Tetra_API*                   MGOutput,
+                        const char*                     theFile,
                         GHS3DPlugin_GHS3D*              theAlgo,
                         SMESH_MesherHelper*             theHelper,
                         std::vector <const SMDS_MeshNode*> &    theNodeByGhs3dId,
@@ -667,7 +618,7 @@ static bool readGMFFile(const char*                     theFile,
 
   int nbElem = 0, nbRef = 0;
   int aGMFNodeID = 0;
-  const SMDS_MeshNode** GMFNode;
+  std::vector< const SMDS_MeshNode*> GMFNode;
 #ifdef _DEBUG_
   std::map<int, std::set<int> > subdomainId2tetraId;
 #endif
@@ -686,7 +637,7 @@ static bool readGMFFile(const char*                     theFile,
 
   int ver, dim;
   MESSAGE("Read " << theFile << " file");
-  int InpMsh = GmfOpenMesh(theFile, GmfRead, &ver, &dim);
+  int InpMsh = MGOutput->GmfOpenMesh( theFile, GmfRead, &ver, &dim);
   if (!InpMsh)
     return false;
   MESSAGE("Done ");
@@ -702,17 +653,17 @@ static bool readGMFFile(const char*                     theFile,
       solid1 = theMeshDS->ShapeToIndex
         ( TopExp_Explorer( theHelper->GetSubShape(), TopAbs_SOLID ).Current() );
 
-    int nbDomains = GmfStatKwd( InpMsh, GmfSubDomainFromGeom );
+    int nbDomains = MGOutput->GmfStatKwd( InpMsh, GmfSubDomainFromGeom );
     if ( nbDomains > 1 )
     {
       solidIDByDomain.resize( nbDomains+1, theHelper->GetSubShapeID() );
       int faceNbNodes, faceIndex, orientation, domainNb;
-      GmfGotoKwd( InpMsh, GmfSubDomainFromGeom );
+      MGOutput->GmfGotoKwd( InpMsh, GmfSubDomainFromGeom );
       for ( int i = 0; i < nbDomains; ++i )
       {
         faceIndex = 0;
-        GmfGetLin( InpMsh, GmfSubDomainFromGeom,
-                   &faceNbNodes, &faceIndex, &orientation, &domainNb);
+        MGOutput->GmfGetLin( InpMsh, GmfSubDomainFromGeom,
+                   &faceNbNodes, &faceIndex, &orientation, &domainNb, i);
         solidIDByDomain[ domainNb ] = 1;
         if ( 0 < faceIndex && faceIndex-1 < (int)theFaceByGhs3dId.size() )
         {
@@ -751,24 +702,24 @@ static bool readGMFFile(const char*                     theFile,
   // IMP 0022172: [CEA 790] create the groups corresponding to domains
   std::vector< std::vector< const SMDS_MeshElement* > > elemsOfDomain;
 
-  int nbVertices = GmfStatKwd(InpMsh, GmfVertices) - nbInitialNodes;
-  GMFNode = new const SMDS_MeshNode*[ nbVertices + 1 ];
+  int nbVertices = MGOutput->GmfStatKwd( InpMsh, GmfVertices ) - nbInitialNodes;
+  if ( nbVertices < 0 )
+    return false;
+  GMFNode.resize( nbVertices + 1 );
 
   std::map <GmfKwdCod,int>::const_iterator it = tabRef.begin();
   for ( ; it != tabRef.end() ; ++it)
   {
     if(theAlgo->computeCanceled()) {
-      GmfCloseMesh(InpMsh);
-      delete [] GMFNode;
       return false;
     }
     int dummy, solidID;
     GmfKwdCod token = it->first;
     nbRef           = it->second;
 
-    nbElem = GmfStatKwd(InpMsh, token);
+    nbElem = MGOutput->GmfStatKwd( InpMsh, token);
     if (nbElem > 0) {
-      GmfGotoKwd(InpMsh, token);
+      MGOutput->GmfGotoKwd( InpMsh, token);
       std::cout << "Read " << nbElem;
     }
     else
@@ -802,18 +753,16 @@ static bool readGMFFile(const char*                     theFile,
 
       for ( int iElem = 0; iElem < nbElem; iElem++ ) {
         if(theAlgo->computeCanceled()) {
-          GmfCloseMesh(InpMsh);
-          delete [] GMFNode;
           return false;
         }
         if (ver == GmfFloat) {
-          GmfGetLin(InpMsh, token, &VerTab_f[0], &VerTab_f[1], &VerTab_f[2], &dummy);
+          MGOutput->GmfGetLin( InpMsh, token, &VerTab_f[0], &VerTab_f[1], &VerTab_f[2], &dummy);
           x = VerTab_f[0];
           y = VerTab_f[1];
           z = VerTab_f[2];
         }
         else {
-          GmfGetLin(InpMsh, token, &x, &y, &z, &dummy);
+          MGOutput->GmfGetLin( InpMsh, token, &x, &y, &z, &dummy);
         }
         if (iElem >= nbInitialNodes) {
           if ( elemSearcher &&
@@ -832,42 +781,41 @@ static bool readGMFFile(const char*                     theFile,
     else if (token == GmfCorners && nbElem > 0) {
       (nbElem <= 1) ? tmpStr = " corner" : tmpStr = " corners";
       for ( int iElem = 0; iElem < nbElem; iElem++ )
-        GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]]);
+        MGOutput->GmfGetLin( InpMsh, token, &id[iElem*tabRef[token]]);
     }
     else if (token == GmfRidges && nbElem > 0) {
       (nbElem <= 1) ? tmpStr = " ridge" : tmpStr = " ridges";
       for ( int iElem = 0; iElem < nbElem; iElem++ )
-        GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]]);
+        MGOutput->GmfGetLin( InpMsh, token, &id[iElem*tabRef[token]]);
     }
     else if (token == GmfEdges && nbElem > 0) {
       (nbElem <= 1) ? tmpStr = " edge" : tmpStr = " edges";
       for ( int iElem = 0; iElem < nbElem; iElem++ )
-        GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &domainID[iElem]);
+        MGOutput->GmfGetLin( InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &domainID[iElem]);
     }
     else if (token == GmfTriangles && nbElem > 0) {
       (nbElem <= 1) ? tmpStr = " triangle" : tmpStr = " triangles";
       for ( int iElem = 0; iElem < nbElem; iElem++ )
-        GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &domainID[iElem]);
+        MGOutput->GmfGetLin( InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &domainID[iElem]);
     }
     else if (token == GmfQuadrilaterals && nbElem > 0) {
       (nbElem <= 1) ? tmpStr = " Quadrilateral" : tmpStr = " Quadrilaterals";
       for ( int iElem = 0; iElem < nbElem; iElem++ )
-        GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3], &domainID[iElem]);
+        MGOutput->GmfGetLin( InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3], &domainID[iElem]);
     }
     else if (token == GmfTetrahedra && nbElem > 0) {
       (nbElem <= 1) ? tmpStr = " Tetrahedron" : tmpStr = " Tetrahedra";
       for ( int iElem = 0; iElem < nbElem; iElem++ ) {
-        GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3], &domainID[iElem]);
+        MGOutput->GmfGetLin( InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3], &domainID[iElem]);
 #ifdef _DEBUG_
         subdomainId2tetraId[dummy].insert(iElem+1);
-//         MESSAGE("subdomainId2tetraId["<<dummy<<"].insert("<<iElem+1<<")");
 #endif
       }
     }
     else if (token == GmfHexahedra && nbElem > 0) {
       (nbElem <= 1) ? tmpStr = " Hexahedron" : tmpStr = " Hexahedra";
       for ( int iElem = 0; iElem < nbElem; iElem++ )
-        GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3],
+        MGOutput->GmfGetLin( InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3],
                   &id[iElem*tabRef[token]+4], &id[iElem*tabRef[token]+5], &id[iElem*tabRef[token]+6], &id[iElem*tabRef[token]+7], &domainID[iElem]);
     }
     std::cout << tmpStr << std::endl;
@@ -890,8 +838,6 @@ static bool readGMFFile(const char*                     theFile,
       for ( int iElem = 0; iElem < nbElem; iElem++ )
       {
         if(theAlgo->computeCanceled()) {
-          GmfCloseMesh(InpMsh);
-          delete [] GMFNode;
           return false;
         }
         // Check if elem is already in input mesh. If yes => skip
@@ -1028,8 +974,7 @@ static bool readGMFFile(const char*                     theFile,
         theMeshDS->RemoveFreeNode( GMFNode[i], /*sm=*/0, /*fromGroups=*/false );
   }
 
-  GmfCloseMesh(InpMsh);
-  delete [] GMFNode;
+  MGOutput->GmfCloseMesh( InpMsh);
 
   // 0022172: [CEA 790] create the groups corresponding to domains
   if ( toMakeGroupsOfDomains )
@@ -1061,7 +1006,8 @@ static bool readGMFFile(const char*                     theFile,
 }
 
 
-static bool writeGMFFile(const char*                                     theMeshFileName,
+static bool writeGMFFile(MG_Tetra_API*                                   MGInput,
+                         const char*                                     theMeshFileName,
                          const char*                                     theRequiredFileName,
                          const char*                                     theSolFileName,
                          const SMESH_ProxyMesh&                          theProxyMesh,
@@ -1116,7 +1062,7 @@ static bool writeGMFFile(const char*                                     theMesh
   if ( nbFaces == 0 )
     return false;
   
-  idx = GmfOpenMesh(theMeshFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
+  idx = MGInput->GmfOpenMesh( theMeshFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
   if (!idx)
     return false;
   
@@ -1169,7 +1115,7 @@ static bool writeGMFFile(const char*                                     theMesh
         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
         gp_Pnt myPoint(node->X(),node->Y(),node->Z());
         nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
-#ifdef _DEBUG_
+#ifdef _MY_DEBUG_
         std::cout << "Node at "<<node->X()<<", "<<node->Y()<<", "<<node->Z()<<std::endl;
         std::cout << "Nb nodes found : "<<nbFoundElems<<std::endl;
 #endif
@@ -1186,7 +1132,7 @@ static bool writeGMFFile(const char*                                     theMesh
         }
         else
           isOK = false;
-#ifdef _DEBUG_
+#ifdef _MY_DEBUG_
         std::cout << "MG-Tetra node ID: "<<newId<<std::endl;
 #endif
       }
@@ -1227,7 +1173,7 @@ static bool writeGMFFile(const char*                                     theMesh
         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
         gp_Pnt myPoint(node->X(),node->Y(),node->Z());
         nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
-#ifdef _DEBUG_
+#ifdef _MY_DEBUG_
         std::cout << "Nb nodes found : "<<nbFoundElems<<std::endl;
 #endif
         if (nbFoundElems ==0) {
@@ -1243,7 +1189,7 @@ static bool writeGMFFile(const char*                                     theMesh
         }
         else
           isOK = false;
-#ifdef _DEBUG_
+#ifdef _MY_DEBUG_
         std::cout << "MG-Tetra node ID: "<<newId<<std::endl;
 #endif
       }
@@ -1255,7 +1201,7 @@ static bool writeGMFFile(const char*                                     theMesh
   }
   
   // put nodes to theNodeByGhs3dId vector
-#ifdef _DEBUG_
+#ifdef _MY_DEBUG_
   std::cout << "aNodeToGhs3dIdMap.size(): "<<aNodeToGhs3dIdMap.size()<<std::endl;
 #endif
   theNodeByGhs3dId.resize( aNodeToGhs3dIdMap.size() );
@@ -1267,7 +1213,7 @@ static bool writeGMFFile(const char*                                     theMesh
   }
 
   // put nodes to anEnforcedNodeToGhs3dIdMap vector
-#ifdef _DEBUG_
+#ifdef _MY_DEBUG_
   std::cout << "anEnforcedNodeToGhs3dIdMap.size(): "<<anEnforcedNodeToGhs3dIdMap.size()<<std::endl;
 #endif
   theEnforcedNodeByGhs3dId.resize( anEnforcedNodeToGhs3dIdMap.size());
@@ -1311,13 +1257,13 @@ static bool writeGMFFile(const char*                                     theMesh
     coords.push_back(node->X());
     coords.push_back(node->Y());
     coords.push_back(node->Z());
-#ifdef _DEBUG_
+#ifdef _MY_DEBUG_
     std::cout << "Node at " << node->X()<<", " <<node->Y()<<", " <<node->Z();
 #endif
     
     if (nodesCoords.find(coords) != nodesCoords.end()) {
       // node already exists in original mesh
-#ifdef _DEBUG_
+#ifdef _MY_DEBUG_
       std::cout << " found" << std::endl;
 #endif
       continue;
@@ -1325,7 +1271,7 @@ static bool writeGMFFile(const char*                                     theMesh
     
     if (theEnforcedVertices.find(coords) != theEnforcedVertices.end()) {
       // node already exists in enforced vertices
-#ifdef _DEBUG_
+#ifdef _MY_DEBUG_
       std::cout << " found" << std::endl;
 #endif
       continue;
@@ -1347,7 +1293,7 @@ static bool writeGMFFile(const char*                                     theMesh
 //       theOrderedNodes.push_back(existingNode);
 //     }
     
-#ifdef _DEBUG_
+#ifdef _MY_DEBUG_
     std::cout << " not found" << std::endl;
 #endif
     
@@ -1368,7 +1314,7 @@ static bool writeGMFFile(const char*                                     theMesh
     coords.push_back(node->X());
     coords.push_back(node->Y());
     coords.push_back(node->Z());
-#ifdef _DEBUG_
+#ifdef _MY_DEBUG_
     std::cout << "Node at " << node->X()<<", " <<node->Y()<<", " <<node->Z();
 #endif
     
@@ -1376,7 +1322,7 @@ static bool writeGMFFile(const char*                                     theMesh
     gp_Pnt myPoint(node->X(),node->Y(),node->Z());
     TopAbs_State result = pntCls->GetPointState( myPoint );
     if ( result == TopAbs_OUT ) {
-#ifdef _DEBUG_
+#ifdef _MY_DEBUG_
       std::cout << " out of volume" << std::endl;
 #endif
       theInvalidEnforcedFlags |= FLAG_BAD_ENF_NODE;
@@ -1384,7 +1330,7 @@ static bool writeGMFFile(const char*                                     theMesh
     }
     
     if (nodesCoords.find(coords) != nodesCoords.end()) {
-#ifdef _DEBUG_
+#ifdef _MY_DEBUG_
       std::cout << " found in nodesCoords" << std::endl;
 #endif
 //       theRequiredNodes.push_back(node);
@@ -1392,7 +1338,7 @@ static bool writeGMFFile(const char*                                     theMesh
     }
 
     if (theEnforcedVertices.find(coords) != theEnforcedVertices.end()) {
-#ifdef _DEBUG_
+#ifdef _MY_DEBUG_
       std::cout << " found in theEnforcedVertices" << std::endl;
 #endif
       continue;
@@ -1421,7 +1367,7 @@ static bool writeGMFFile(const char*                                     theMesh
 //     if ( result != TopAbs_IN )
 //       continue;
     
-#ifdef _DEBUG_
+#ifdef _MY_DEBUG_
     std::cout << " not found" << std::endl;
 #endif
     nodesCoords.insert(coords);
@@ -1464,9 +1410,9 @@ static bool writeGMFFile(const char*                                     theMesh
   // GmfVertices
   std::cout << "Begin writting required nodes in GmfVertices" << std::endl;
   std::cout << "Nb vertices: " << theOrderedNodes.size() << std::endl;
-  GmfSetKwd(idx, GmfVertices, theOrderedNodes.size()/*+solSize*/);
+  MGInput->GmfSetKwd( idx, GmfVertices, theOrderedNodes.size()/*+solSize*/);
   for (ghs3dNodeIt = theOrderedNodes.begin();ghs3dNodeIt != theOrderedNodes.end();++ghs3dNodeIt) {
-    GmfSetLin(idx, GmfVertices, (*ghs3dNodeIt)->X(), (*ghs3dNodeIt)->Y(), (*ghs3dNodeIt)->Z(), dummyint);
+    MGInput->GmfSetLin( idx, GmfVertices, (*ghs3dNodeIt)->X(), (*ghs3dNodeIt)->Y(), (*ghs3dNodeIt)->Z(), dummyint);
   }
 
   std::cout << "End writting required nodes in GmfVertices" << std::endl;
@@ -1474,27 +1420,23 @@ static bool writeGMFFile(const char*                                     theMesh
   if (requiredNodes + solSize) {
     std::cout << "Begin writting in req and sol file" << std::endl;
     aNodeGroupByGhs3dId.resize( requiredNodes + solSize );
-    idxRequired = GmfOpenMesh(theRequiredFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
+    idxRequired = MGInput->GmfOpenMesh( theRequiredFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
     if (!idxRequired) {
-      GmfCloseMesh(idx);
       return false;
     }
-    idxSol = GmfOpenMesh(theSolFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
+    idxSol = MGInput->GmfOpenMesh( theSolFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
     if (!idxSol) {
-      GmfCloseMesh(idx);
-      if (idxRequired)
-        GmfCloseMesh(idxRequired);
       return false;
     }
     int TypTab[] = {GmfSca};
     double ValTab[] = {0.0};
-    GmfSetKwd(idxRequired, GmfVertices, requiredNodes + solSize);
-    GmfSetKwd(idxSol, GmfSolAtVertices, requiredNodes + solSize, 1, TypTab);
+    MGInput->GmfSetKwd( idxRequired, GmfVertices, requiredNodes + solSize);
+    MGInput->GmfSetKwd( idxSol, GmfSolAtVertices, requiredNodes + solSize, 1, TypTab);
 //     int usedEnforcedNodes = 0;
 //     std::string gn = "";
     for (ghs3dNodeIt = theRequiredNodes.begin();ghs3dNodeIt != theRequiredNodes.end();++ghs3dNodeIt) {
-      GmfSetLin(idxRequired, GmfVertices, (*ghs3dNodeIt)->X(), (*ghs3dNodeIt)->Y(), (*ghs3dNodeIt)->Z(), dummyint);
-      GmfSetLin(idxSol, GmfSolAtVertices, ValTab);
+      MGInput->GmfSetLin( idxRequired, GmfVertices, (*ghs3dNodeIt)->X(), (*ghs3dNodeIt)->Y(), (*ghs3dNodeIt)->Z(), dummyint);
+      MGInput->GmfSetLin( idxSol, GmfSolAtVertices, ValTab);
       if (theEnforcedNodes.find((*ghs3dNodeIt)) != theEnforcedNodes.end())
         gn = theEnforcedNodes.find((*ghs3dNodeIt))->second;
       aNodeGroupByGhs3dId[usedEnforcedNodes] = gn;
@@ -1503,14 +1445,14 @@ static bool writeGMFFile(const char*                                     theMesh
 
     for (int i=0;i<solSize;i++) {
       std::cout << ReqVerTab[i][0] <<" "<< ReqVerTab[i][1] << " "<< ReqVerTab[i][2] << std::endl;
-#ifdef _DEBUG_
+#ifdef _MY_DEBUG_
       std::cout << "enfVertexSizes.at("<<i<<"): " << enfVertexSizes.at(i) << std::endl;
 #endif
       double solTab[] = {enfVertexSizes.at(i)};
-      GmfSetLin(idxRequired, GmfVertices, ReqVerTab[i][0], ReqVerTab[i][1], ReqVerTab[i][2], dummyint);
-      GmfSetLin(idxSol, GmfSolAtVertices, solTab);
+      MGInput->GmfSetLin( idxRequired, GmfVertices, ReqVerTab[i][0], ReqVerTab[i][1], ReqVerTab[i][2], dummyint);
+      MGInput->GmfSetLin( idxSol, GmfSolAtVertices, solTab);
       aNodeGroupByGhs3dId[usedEnforcedNodes] = enfVerticesWithGroup.find(ReqVerTab[i])->second;
-#ifdef _DEBUG_
+#ifdef _MY_DEBUG_
       std::cout << "aNodeGroupByGhs3dId["<<usedEnforcedNodes<<"] = \""<<aNodeGroupByGhs3dId[usedEnforcedNodes]<<"\""<<std::endl;
 #endif
       usedEnforcedNodes++;
@@ -1524,11 +1466,11 @@ static bool writeGMFFile(const char*                                     theMesh
   int usedEnforcedEdges = 0;
   if (theKeptEnforcedEdges.size()) {
     anEdgeGroupByGhs3dId.resize( theKeptEnforcedEdges.size() );
-//    idxRequired = GmfOpenMesh(theRequiredFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
+//    idxRequired = MGInput->GmfOpenMesh( theRequiredFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
 //    if (!idxRequired)
 //      return false;
-    GmfSetKwd(idx, GmfEdges, theKeptEnforcedEdges.size());
-//    GmfSetKwd(idxRequired, GmfEdges, theKeptEnforcedEdges.size());
+    MGInput->GmfSetKwd( idx, GmfEdges, theKeptEnforcedEdges.size());
+//    MGInput->GmfSetKwd( idxRequired, GmfEdges, theKeptEnforcedEdges.size());
     for(elemSetIt = theKeptEnforcedEdges.begin() ; elemSetIt != theKeptEnforcedEdges.end() ; ++elemSetIt) {
       elem = (*elemSetIt);
       nodeIt = elem->nodesIterator();
@@ -1545,19 +1487,18 @@ static bool writeGMFFile(const char*                                     theMesh
         nedge[index] = it->second;
         index++;
       }
-      GmfSetLin(idx, GmfEdges, nedge[0], nedge[1], dummyint);
+      MGInput->GmfSetLin( idx, GmfEdges, nedge[0], nedge[1], dummyint);
       anEdgeGroupByGhs3dId[usedEnforcedEdges] = theEnforcedEdges.find(elem)->second;
-//      GmfSetLin(idxRequired, GmfEdges, nedge[0], nedge[1], dummyint);
+//      MGInput->GmfSetLin( idxRequired, GmfEdges, nedge[0], nedge[1], dummyint);
       usedEnforcedEdges++;
     }
-//    GmfCloseMesh(idxRequired);
   }
 
 
   if (usedEnforcedEdges) {
-    GmfSetKwd(idx, GmfRequiredEdges, usedEnforcedEdges);
+    MGInput->GmfSetKwd( idx, GmfRequiredEdges, usedEnforcedEdges);
     for (int enfID=1;enfID<=usedEnforcedEdges;enfID++) {
-      GmfSetLin(idx, GmfRequiredEdges, enfID);
+      MGInput->GmfSetLin( idx, GmfRequiredEdges, enfID);
     }
   }
 
@@ -1565,7 +1506,7 @@ static bool writeGMFFile(const char*                                     theMesh
   int usedEnforcedTriangles = 0;
   if (anElemSet.size()+theKeptEnforcedTriangles.size()) {
     aFaceGroupByGhs3dId.resize( anElemSet.size()+theKeptEnforcedTriangles.size() );
-    GmfSetKwd(idx, GmfTriangles, anElemSet.size()+theKeptEnforcedTriangles.size());
+    MGInput->GmfSetKwd( idx, GmfTriangles, anElemSet.size()+theKeptEnforcedTriangles.size());
     int k=0;
     for(elemSetIt = anElemSet.begin() ; elemSetIt != anElemSet.end() ; ++elemSetIt,++k) {
       elem = (*elemSetIt);
@@ -1581,7 +1522,7 @@ static bool writeGMFFile(const char*                                     theMesh
         ntri[index] = it->second;
         index++;
       }
-      GmfSetLin(idx, GmfTriangles, ntri[0], ntri[1], ntri[2], dummyint);
+      MGInput->GmfSetLin( idx, GmfTriangles, ntri[0], ntri[1], ntri[2], dummyint);
       aFaceGroupByGhs3dId[k] = "";
     }
     if ( !theHelper.GetMesh()->HasShapeToMesh() )
@@ -1603,7 +1544,7 @@ static bool writeGMFFile(const char*                                     theMesh
           ntri[index] = it->second;
           index++;
         }
-        GmfSetLin(idx, GmfTriangles, ntri[0], ntri[1], ntri[2], dummyint);
+        MGInput->GmfSetLin( idx, GmfTriangles, ntri[0], ntri[1], ntri[2], dummyint);
         aFaceGroupByGhs3dId[k] = theEnforcedTriangles.find(elem)->second;
         usedEnforcedTriangles++;
       }
@@ -1612,19 +1553,18 @@ static bool writeGMFFile(const char*                                     theMesh
 
   
   if (usedEnforcedTriangles) {
-    GmfSetKwd(idx, GmfRequiredTriangles, usedEnforcedTriangles);
+    MGInput->GmfSetKwd( idx, GmfRequiredTriangles, usedEnforcedTriangles);
     for (int enfID=1;enfID<=usedEnforcedTriangles;enfID++)
-      GmfSetLin(idx, GmfRequiredTriangles, anElemSet.size()+enfID);
+      MGInput->GmfSetLin( idx, GmfRequiredTriangles, anElemSet.size()+enfID);
   }
 
-  GmfCloseMesh(idx);
+  MGInput->GmfCloseMesh(idx);
   if (idxRequired)
-    GmfCloseMesh(idxRequired);
+    MGInput->GmfCloseMesh(idxRequired);
   if (idxSol)
-    GmfCloseMesh(idxSol);
-  
+    MGInput->GmfCloseMesh(idxSol);
+
   return true;
-  
 }
 
 //=============================================================================
@@ -1637,36 +1577,7 @@ bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
                                 const TopoDS_Shape& theShape)
 {
   bool Ok(false);
-  //SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
-
-  // we count the number of shapes
-  // _nbShape = countShape( meshDS, TopAbs_SOLID ); -- 0020330: Pb with MG-Tetra as a submesh
-  // _nbShape = 0;
   TopExp_Explorer expBox ( theShape, TopAbs_SOLID );
-  // for ( ; expBox.More(); expBox.Next() )
-  //   _nbShape++;
-
-  // create bounding box for every shape inside the compound
-
-  // int iShape = 0;
-  // TopoDS_Shape* tabShape;
-  // double**      tabBox;
-  // tabShape = new TopoDS_Shape[_nbShape];
-  // tabBox   = new double*[_nbShape];
-  // for (int i=0; i<_nbShape; i++)
-  //   tabBox[i] = new double[6];
-  // Standard_Real Xmin, Ymin, Zmin, Xmax, Ymax, Zmax;
-
-  // for (expBox.ReInit(); expBox.More(); expBox.Next()) {
-  //   tabShape[iShape] = expBox.Current();
-  //   Bnd_Box BoundingBox;
-  //   BRepBndLib::Add(expBox.Current(), BoundingBox);
-  //   BoundingBox.Get(Xmin, Ymin, Zmin, Xmax, Ymax, Zmax);
-  //   tabBox[iShape][0] = Xmin; tabBox[iShape][1] = Xmax;
-  //   tabBox[iShape][2] = Ymin; tabBox[iShape][3] = Ymax;
-  //   tabBox[iShape][4] = Zmin; tabBox[iShape][5] = Zmax;
-  //   iShape++;
-  // }
 
   // a unique working file name
   // to avoid access to the same files by eg different users
@@ -1678,28 +1589,19 @@ bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
   TCollection_AsciiString aResultFileName;
 
   TCollection_AsciiString aGMFFileName, aRequiredVerticesFileName, aSolFileName, aResSolFileName;
-//#ifdef _DEBUG_
   aGMFFileName              = aGenericName + ".mesh"; // GMF mesh file
   aResultFileName           = aGenericName + "Vol.mesh"; // GMF mesh file
   aResSolFileName           = aGenericName + "Vol.sol"; // GMF mesh file
   aRequiredVerticesFileName = aGenericNameRequired + ".mesh"; // GMF required vertices mesh file
   aSolFileName              = aGenericNameRequired + ".sol"; // GMF solution file
-//#else
-//  aGMFFileName    = aGenericName + ".meshb"; // GMF mesh file
-//  aResultFileName = aGenericName + "Vol.meshb"; // GMF mesh file
-//  aRequiredVerticesFileName    = aGenericNameRequired + ".meshb"; // GMF required vertices mesh file
-//  aSolFileName    = aGenericNameRequired + ".solb"; // GMF solution file
-//#endif
   
   std::map <int,int> aNodeId2NodeIndexMap, aSmdsToGhs3dIdMap, anEnforcedNodeIdToGhs3dIdMap;
-  //std::map <int,const SMDS_MeshNode*> aGhs3dIdToNodeMap;
   std::map <int, int> nodeID2nodeIndexMap;
   std::map<std::vector<double>, std::string> enfVerticesWithGroup;
   GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexCoordsValues coordsSizeMap = GHS3DPlugin_Hypothesis::GetEnforcedVerticesCoordsSize(_hyp);
   GHS3DPlugin_Hypothesis::TIDSortedNodeGroupMap enforcedNodes = GHS3DPlugin_Hypothesis::GetEnforcedNodes(_hyp);
   GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap enforcedEdges = GHS3DPlugin_Hypothesis::GetEnforcedEdges(_hyp);
   GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap enforcedTriangles = GHS3DPlugin_Hypothesis::GetEnforcedTriangles(_hyp);
-//   TIDSortedElemSet enforcedQuadrangles = GHS3DPlugin_Hypothesis::GetEnforcedQuadrangles(_hyp);
   GHS3DPlugin_Hypothesis::TID2SizeMap nodeIDToSizeMap = GHS3DPlugin_Hypothesis::GetNodeIDToSizeMap(_hyp);
 
   GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexList enfVertices = GHS3DPlugin_Hypothesis::GetEnforcedVertices(_hyp);
@@ -1709,59 +1611,36 @@ bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
   for ( ; enfVerIt != enfVertices.end() ; ++enfVerIt)
   {
     GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertex* enfVertex = (*enfVerIt);
-//     if (enfVertex->geomEntry.empty() && enfVertex->coords.size()) {
     if (enfVertex->coords.size()) {
       coordsSizeMap.insert(make_pair(enfVertex->coords,enfVertex->size));
       enfVerticesWithGroup.insert(make_pair(enfVertex->coords,enfVertex->groupName));
-//       MESSAGE("enfVerticesWithGroup.insert(make_pair(("<<enfVertex->coords[0]<<","<<enfVertex->coords[1]<<","<<enfVertex->coords[2]<<"),\""<<enfVertex->groupName<<"\"))");
     }
     else {
-//     if (!enfVertex->geomEntry.empty()) {
       TopoDS_Shape GeomShape = entryToShape(enfVertex->geomEntry);
-//       GeomType = GeomShape.ShapeType();
-
-//       if (!enfVertex->isCompound) {
-// //       if (GeomType == TopAbs_VERTEX) {
-//         coords.clear();
-//         aPnt = BRep_Tool::Pnt(TopoDS::Vertex(GeomShape));
-//         coords.push_back(aPnt.X());
-//         coords.push_back(aPnt.Y());
-//         coords.push_back(aPnt.Z());
-//         if (coordsSizeMap.find(coords) == coordsSizeMap.end()) {
-//           coordsSizeMap.insert(make_pair(coords,enfVertex->size));
-//           enfVerticesWithGroup.insert(make_pair(coords,enfVertex->groupName));
-//         }
-//       }
-//
-//       // Group Management
-//       else {
-//       if (GeomType == TopAbs_COMPOUND){
-        for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
-          coords.clear();
-          if (it.Value().ShapeType() == TopAbs_VERTEX){
-            gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
-            coords.push_back(aPnt.X());
-            coords.push_back(aPnt.Y());
-            coords.push_back(aPnt.Z());
-            if (coordsSizeMap.find(coords) == coordsSizeMap.end()) {
-              coordsSizeMap.insert(make_pair(coords,enfVertex->size));
-              enfVerticesWithGroup.insert(make_pair(coords,enfVertex->groupName));
-//               MESSAGE("enfVerticesWithGroup.insert(make_pair(("<<coords[0]<<","<<coords[1]<<","<<coords[2]<<"),\""<<enfVertex->groupName<<"\"))");
-            }
+      for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
+        coords.clear();
+        if (it.Value().ShapeType() == TopAbs_VERTEX){
+          gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
+          coords.push_back(aPnt.X());
+          coords.push_back(aPnt.Y());
+          coords.push_back(aPnt.Z());
+          if (coordsSizeMap.find(coords) == coordsSizeMap.end()) {
+            coordsSizeMap.insert(make_pair(coords,enfVertex->size));
+            enfVerticesWithGroup.insert(make_pair(coords,enfVertex->groupName));
           }
         }
-//       }
+      }
     }
   }
   int nbEnforcedVertices = coordsSizeMap.size();
   int nbEnforcedNodes = enforcedNodes.size();
-  
+
   std::string tmpStr;
   (nbEnforcedNodes <= 1) ? tmpStr = "node" : "nodes";
   std::cout << nbEnforcedNodes << " enforced " << tmpStr << " from hypo" << std::endl;
   (nbEnforcedVertices <= 1) ? tmpStr = "vertex" : "vertices";
   std::cout << nbEnforcedVertices << " enforced " << tmpStr << " from hypo" << std::endl;
-  
+
   SMESH_MesherHelper helper( theMesh );
   helper.SetSubShape( theShape );
 
@@ -1772,51 +1651,48 @@ bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
 
   // proxyMesh must live till readGMFFile() as a proxy face can be used by
   // MG-Tetra for domain indication
-  //{
-    SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( theMesh ));
+  SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( theMesh ));
 
-    // make prisms on quadrangles
-    if ( theMesh.NbQuadrangles() > 0 )
+  // make prisms on quadrangles
+  if ( theMesh.NbQuadrangles() > 0 )
+  {
+    vector<SMESH_ProxyMesh::Ptr> components;
+    for (expBox.ReInit(); expBox.More(); expBox.Next())
     {
-      vector<SMESH_ProxyMesh::Ptr> components;
-      for (expBox.ReInit(); expBox.More(); expBox.Next())
+      if ( _viscousLayersHyp )
       {
-        if ( _viscousLayersHyp )
-        {
-          proxyMesh = _viscousLayersHyp->Compute( theMesh, expBox.Current() );
-          if ( !proxyMesh )
-            return false;
-        }
-        StdMeshers_QuadToTriaAdaptor* q2t = new StdMeshers_QuadToTriaAdaptor;
-        q2t->Compute( theMesh, expBox.Current(), proxyMesh.get() );
-        components.push_back( SMESH_ProxyMesh::Ptr( q2t ));
+        proxyMesh = _viscousLayersHyp->Compute( theMesh, expBox.Current() );
+        if ( !proxyMesh )
+          return false;
       }
-      proxyMesh.reset( new SMESH_ProxyMesh( components ));
-    }
-    // build viscous layers
-    else if ( _viscousLayersHyp )
-    {
-      proxyMesh = _viscousLayersHyp->Compute( theMesh, theShape );
-      if ( !proxyMesh )
-        return false;
+      StdMeshers_QuadToTriaAdaptor* q2t = new StdMeshers_QuadToTriaAdaptor;
+      q2t->Compute( theMesh, expBox.Current(), proxyMesh.get() );
+      components.push_back( SMESH_ProxyMesh::Ptr( q2t ));
     }
+    proxyMesh.reset( new SMESH_ProxyMesh( components ));
+  }
+  // build viscous layers
+  else if ( _viscousLayersHyp )
+  {
+    proxyMesh = _viscousLayersHyp->Compute( theMesh, theShape );
+    if ( !proxyMesh )
+      return false;
+  }
+
+  MG_Tetra_API mgTetra( _compute_canceled, _progress );
 
-    // Ok = (writePoints( aPointsFile, helper, 
-    //                    aSmdsToGhs3dIdMap, anEnforcedNodeIdToGhs3dIdMap, aGhs3dIdToNodeMap, 
-    //                    nodeIDToSizeMap,
-    //                    coordsSizeMap, enforcedNodes, enforcedEdges, enforcedTriangles)
-    //       &&
-    //       writeFaces ( aFacesFile, *proxyMesh, theShape, 
-    //                    aSmdsToGhs3dIdMap, anEnforcedNodeIdToGhs3dIdMap,
-    //                    enforcedEdges, enforcedTriangles ));
-    int anInvalidEnforcedFlags = 0;
-    Ok = writeGMFFile(aGMFFileName.ToCString(), aRequiredVerticesFileName.ToCString(), aSolFileName.ToCString(),
-                      *proxyMesh, helper,
-                      aNodeByGhs3dId, aFaceByGhs3dId, aNodeToGhs3dIdMap,
-                      aNodeGroupByGhs3dId, anEdgeGroupByGhs3dId, aFaceGroupByGhs3dId,
-                      enforcedNodes, enforcedEdges, enforcedTriangles, /*enforcedQuadrangles,*/
-                      enfVerticesWithGroup, coordsSizeMap, anInvalidEnforcedFlags);
-    //}
+  _isLibUsed = mgTetra.IsLibrary();
+
+  int anInvalidEnforcedFlags = 0;
+  Ok = writeGMFFile(&mgTetra,
+                    aGMFFileName.ToCString(),
+                    aRequiredVerticesFileName.ToCString(),
+                    aSolFileName.ToCString(),
+                    *proxyMesh, helper,
+                    aNodeByGhs3dId, aFaceByGhs3dId, aNodeToGhs3dIdMap,
+                    aNodeGroupByGhs3dId, anEdgeGroupByGhs3dId, aFaceGroupByGhs3dId,
+                    enforcedNodes, enforcedEdges, enforcedTriangles,
+                    enfVerticesWithGroup, coordsSizeMap, anInvalidEnforcedFlags);
 
   // Write aSmdsToGhs3dIdMap to temp file
   TCollection_AsciiString aSmdsToGhs3dIdMapFileName;
@@ -1835,7 +1711,7 @@ bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
   }
 
   aIdsFile.close();
-  
+
   if ( ! Ok ) {
     if ( !_keepFiles ) {
       removeFile( aGMFFileName );
@@ -1851,74 +1727,54 @@ bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
   // run MG-Tetra mesher
   // -----------------
 
-  TCollection_AsciiString cmd( (char*)GHS3DPlugin_Hypothesis::CommandToRun( _hyp ).c_str() );
-  
-  cmd += TCollection_AsciiString(" --in ") + aGMFFileName;
-  if ( nbEnforcedVertices + nbEnforcedNodes)
-    cmd += TCollection_AsciiString(" --required_vertices ") + aGenericNameRequired;
-  cmd += TCollection_AsciiString(" --out ") + aResultFileName;
+  TCollection_AsciiString cmd = GHS3DPlugin_Hypothesis::CommandToRun( _hyp, true, mgTetra.IsExecutable() ).c_str();
+
+  if ( mgTetra.IsExecutable() )
+  {
+    cmd += TCollection_AsciiString(" --in ") + aGMFFileName;
+    if ( nbEnforcedVertices + nbEnforcedNodes)
+      cmd += TCollection_AsciiString(" --required_vertices ") + aGenericNameRequired;
+    cmd += TCollection_AsciiString(" --out ") + aResultFileName;
+  }
   if ( !_logInStandardOutput )
+  {
+    mgTetra.SetLogFile( aLogFileName.ToCString() );
     cmd += TCollection_AsciiString(" 1>" ) + aLogFileName;  // dump into file
-
+  }
   std::cout << std::endl;
   std::cout << "MG-Tetra execution..." << std::endl;
   std::cout << cmd << std::endl;
 
   _compute_canceled = false;
 
-  int err = system( cmd.ToCString() ); // run
-
   std::string errStr;
-  if ( err )
-    errStr = SMESH_Comment("system(mg-tetra.exe ...) command failed with error: ")
-      << strerror( errno );
-  else
+  Ok = mgTetra.Compute( cmd.ToCString(), errStr ); // run
+
+  if ( _logInStandardOutput && mgTetra.IsLibrary() )
+    std::cout << std::endl << mgTetra.GetLog() << std::endl;
+  if ( Ok )
     std::cout << std::endl << "End of MG-Tetra execution !" << std::endl;
 
   // --------------
   // read a result
   // --------------
 
-  // Mapping the result file
-
-  // int fileOpen;
-  // fileOpen = open( aResultFileName.ToCString(), O_RDONLY);
-  // if ( fileOpen < 0 ) {
-  //   std::cout << std::endl;
-  //   std::cout << "Can't open the " << aResultFileName.ToCString() << " MG-Tetra output file" << std::endl;
-  //   std::cout << "Log: " << aLogFileName << std::endl;
-  //   Ok = false;
-  // }
-  // else {
-    GHS3DPlugin_Hypothesis::TSetStrings groupsToRemove = GHS3DPlugin_Hypothesis::GetGroupsToRemove(_hyp);
-    bool toMeshHoles =
-      _hyp ? _hyp->GetToMeshHoles(true) : GHS3DPlugin_Hypothesis::DefaultMeshHoles();
-    const bool toMakeGroupsOfDomains = GHS3DPlugin_Hypothesis::GetToMakeGroupsOfDomains( _hyp );
-
-    helper.IsQuadraticSubMesh( theShape );
-    helper.SetElementsOnShape( false );
-
-//     Ok = readResultFile( fileOpen,
-// #ifdef WIN32
-//                          aResultFileName.ToCString(),
-// #endif
-//                          this,
-//                          /*theMesh, */helper, tabShape, tabBox, _nbShape, 
-//                          aGhs3dIdToNodeMap, aNodeId2NodeIndexMap,
-//                          toMeshHoles, 
-//                          nbEnforcedVertices, nbEnforcedNodes, 
-//                          enforcedEdges, enforcedTriangles,
-//                          toMakeGroupsOfDomains );
-                         
-    Ok = readGMFFile(aResultFileName.ToCString(),
-                     this,
-                     &helper, aNodeByGhs3dId, aFaceByGhs3dId, aNodeToGhs3dIdMap,
-                     aNodeGroupByGhs3dId, anEdgeGroupByGhs3dId, aFaceGroupByGhs3dId,
-                     groupsToRemove, toMakeGroupsOfDomains, toMeshHoles);
-
-    removeEmptyGroupsOfDomains( helper.GetMesh(), /*notEmptyAsWell =*/ !toMakeGroupsOfDomains );
-    //}
+  GHS3DPlugin_Hypothesis::TSetStrings groupsToRemove = GHS3DPlugin_Hypothesis::GetGroupsToRemove(_hyp);
+  bool toMeshHoles =
+    _hyp ? _hyp->GetToMeshHoles(true) : GHS3DPlugin_Hypothesis::DefaultMeshHoles();
+  const bool toMakeGroupsOfDomains = GHS3DPlugin_Hypothesis::GetToMakeGroupsOfDomains( _hyp );
+
+  helper.IsQuadraticSubMesh( theShape );
+  helper.SetElementsOnShape( false );
+
+  Ok = readGMFFile(&mgTetra,
+                   aResultFileName.ToCString(),
+                   this,
+                   &helper, aNodeByGhs3dId, aFaceByGhs3dId, aNodeToGhs3dIdMap,
+                   aNodeGroupByGhs3dId, anEdgeGroupByGhs3dId, aFaceGroupByGhs3dId,
+                   groupsToRemove, toMakeGroupsOfDomains, toMeshHoles);
 
+  removeEmptyGroupsOfDomains( helper.GetMesh(), /*notEmptyAsWell =*/ !toMakeGroupsOfDomains );
 
 
 
@@ -1935,13 +1791,14 @@ bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
     // if ( _hyp && _hyp->GetToMakeGroupsOfDomains() )
     //   error( COMPERR_WARNING, "'toMakeGroupsOfDomains' is ignored since the mesh is on shape" );
   }
-  else if ( OSD_File( aLogFileName ).Size() > 0 )
+  else if ( mgTetra.HasLog() )
   {
     // get problem description from the log file
     _Ghs2smdsConvertor conv( aNodeByGhs3dId, proxyMesh );
-    storeErrorDescription( aLogFileName, conv );
+    storeErrorDescription( _logInStandardOutput ? 0 : aLogFileName.ToCString(),
+                           mgTetra.GetLog(), conv );
   }
-  else
+  else if ( !errStr.empty() )
   {
     // the log file is empty
     removeFile( aLogFileName );
@@ -1950,7 +1807,7 @@ bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
   }
 
   if ( !_keepFiles ) {
-    if (! Ok && _compute_canceled)
+    if (! Ok && _compute_canceled )
       removeFile( aLogFileName );
     removeFile( aGMFFileName );
     removeFile( aRequiredVerticesFileName );
@@ -1959,16 +1816,18 @@ bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
     removeFile( aResultFileName );
     removeFile( aSmdsToGhs3dIdMapFileName );
   }
-  std::cout << "<" << aResultFileName.ToCString() << "> MG-Tetra output file ";
-  if ( !Ok )
-    std::cout << "not ";
-  std::cout << "treated !" << std::endl;
-  std::cout << std::endl;
-
-  // _nbShape = 0;    // re-initializing _nbShape for the next Compute() method call
-  // delete [] tabShape;
-  // delete [] tabBox;
-
+  if ( mgTetra.IsExecutable() )
+  {
+    std::cout << "<" << aResultFileName.ToCString() << "> MG-Tetra output file ";
+    if ( !Ok )
+      std::cout << "not ";
+    std::cout << "treated !" << std::endl;
+    std::cout << std::endl;
+  }
+  else
+  {
+    std::cout << "MG-Tetra " << ( Ok ? "succeeded" : "failed") << std::endl;
+  }
   return Ok;
 }
 
@@ -1995,24 +1854,16 @@ bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
   bool Ok;
 
   TCollection_AsciiString aGMFFileName, aRequiredVerticesFileName, aSolFileName, aResSolFileName;
-//#ifdef _DEBUG_
   aGMFFileName              = aGenericName + ".mesh"; // GMF mesh file
   aResultFileName           = aGenericName + "Vol.mesh"; // GMF mesh file
   aResSolFileName           = aGenericName + "Vol.sol"; // GMF mesh file
   aRequiredVerticesFileName = aGenericNameRequired + ".mesh"; // GMF required vertices mesh file
   aSolFileName              = aGenericNameRequired + ".sol"; // GMF solution file
-//#else
-//  aGMFFileName    = aGenericName + ".meshb"; // GMF mesh file
-//  aResultFileName = aGenericName + "Vol.meshb"; // GMF mesh file
-//  aRequiredVerticesFileName    = aGenericNameRequired + ".meshb"; // GMF required vertices mesh file
-//  aSolFileName    = aGenericNameRequired + ".solb"; // GMF solution file
-//#endif
 
   std::map <int, int> nodeID2nodeIndexMap;
   std::map<std::vector<double>, std::string> enfVerticesWithGroup;
   GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexCoordsValues coordsSizeMap;
   TopoDS_Shape GeomShape;
-//   TopAbs_ShapeEnum GeomType;
   std::vector<double> coords;
   gp_Pnt aPnt;
   GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertex* enfVertex;
@@ -2023,70 +1874,32 @@ bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
   for ( ; enfVerIt != enfVertices.end() ; ++enfVerIt)
   {
     enfVertex = (*enfVerIt);
-//     if (enfVertex->geomEntry.empty() && enfVertex->coords.size()) {
     if (enfVertex->coords.size()) {
       coordsSizeMap.insert(make_pair(enfVertex->coords,enfVertex->size));
       enfVerticesWithGroup.insert(make_pair(enfVertex->coords,enfVertex->groupName));
-//       MESSAGE("enfVerticesWithGroup.insert(make_pair(("<<enfVertex->coords[0]<<","<<enfVertex->coords[1]<<","<<enfVertex->coords[2]<<"),\""<<enfVertex->groupName<<"\"))");
     }
     else {
-//     if (!enfVertex->geomEntry.empty()) {
       GeomShape = entryToShape(enfVertex->geomEntry);
-//       GeomType = GeomShape.ShapeType();
-
-//       if (!enfVertex->isCompound) {
-// //       if (GeomType == TopAbs_VERTEX) {
-//         coords.clear();
-//         aPnt = BRep_Tool::Pnt(TopoDS::Vertex(GeomShape));
-//         coords.push_back(aPnt.X());
-//         coords.push_back(aPnt.Y());
-//         coords.push_back(aPnt.Z());
-//         if (coordsSizeMap.find(coords) == coordsSizeMap.end()) {
-//           coordsSizeMap.insert(make_pair(coords,enfVertex->size));
-//           enfVerticesWithGroup.insert(make_pair(coords,enfVertex->groupName));
-//         }
-//       }
-//
-//       // Group Management
-//       else {
-//       if (GeomType == TopAbs_COMPOUND){
-        for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
-          coords.clear();
-          if (it.Value().ShapeType() == TopAbs_VERTEX){
-            aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
-            coords.push_back(aPnt.X());
-            coords.push_back(aPnt.Y());
-            coords.push_back(aPnt.Z());
-            if (coordsSizeMap.find(coords) == coordsSizeMap.end()) {
-              coordsSizeMap.insert(make_pair(coords,enfVertex->size));
-              enfVerticesWithGroup.insert(make_pair(coords,enfVertex->groupName));
-//               MESSAGE("enfVerticesWithGroup.insert(make_pair(("<<coords[0]<<","<<coords[1]<<","<<coords[2]<<"),\""<<enfVertex->groupName<<"\"))");
-            }
+      for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
+        coords.clear();
+        if (it.Value().ShapeType() == TopAbs_VERTEX){
+          aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
+          coords.push_back(aPnt.X());
+          coords.push_back(aPnt.Y());
+          coords.push_back(aPnt.Z());
+          if (coordsSizeMap.find(coords) == coordsSizeMap.end()) {
+            coordsSizeMap.insert(make_pair(coords,enfVertex->size));
+            enfVerticesWithGroup.insert(make_pair(coords,enfVertex->groupName));
           }
         }
-//       }
+      }
     }
   }
 
-//   const SMDS_MeshNode* enfNode;
-  GHS3DPlugin_Hypothesis::TIDSortedNodeGroupMap enforcedNodes = GHS3DPlugin_Hypothesis::GetEnforcedNodes(_hyp);
-//   GHS3DPlugin_Hypothesis::TIDSortedNodeGroupMap::const_iterator enfNodeIt = enforcedNodes.begin();
-//   for ( ; enfNodeIt != enforcedNodes.end() ; ++enfNodeIt)
-//   {
-//     enfNode = enfNodeIt->first;
-//     coords.clear();
-//     coords.push_back(enfNode->X());
-//     coords.push_back(enfNode->Y());
-//     coords.push_back(enfNode->Z());
-//     if (enfVerticesWithGro
-//       enfVerticesWithGroup.insert(make_pair(coords,enfNodeIt->second));
-//   }
-
-
-  GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap enforcedEdges = GHS3DPlugin_Hypothesis::GetEnforcedEdges(_hyp);
+  GHS3DPlugin_Hypothesis::TIDSortedNodeGroupMap     enforcedNodes = GHS3DPlugin_Hypothesis::GetEnforcedNodes(_hyp);
+  GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap     enforcedEdges = GHS3DPlugin_Hypothesis::GetEnforcedEdges(_hyp);
   GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap enforcedTriangles = GHS3DPlugin_Hypothesis::GetEnforcedTriangles(_hyp);
-//   TIDSortedElemSet enforcedQuadrangles = GHS3DPlugin_Hypothesis::GetEnforcedQuadrangles(_hyp);
-  GHS3DPlugin_Hypothesis::TID2SizeMap nodeIDToSizeMap = GHS3DPlugin_Hypothesis::GetNodeIDToSizeMap(_hyp);
+  GHS3DPlugin_Hypothesis::TID2SizeMap             nodeIDToSizeMap = GHS3DPlugin_Hypothesis::GetNodeIDToSizeMap(_hyp);
 
   std::string tmpStr;
 
@@ -2104,50 +1917,57 @@ bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
 
   // proxyMesh must live till readGMFFile() as a proxy face can be used by
   // MG-Tetra for domain indication
-  //{
-    SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( theMesh ));
-    if ( theMesh.NbQuadrangles() > 0 )
-    {
-      StdMeshers_QuadToTriaAdaptor* aQuad2Trias = new StdMeshers_QuadToTriaAdaptor;
-      aQuad2Trias->Compute( theMesh );
-      proxyMesh.reset( aQuad2Trias );
-    }
+  SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( theMesh ));
+  if ( theMesh.NbQuadrangles() > 0 )
+  {
+    StdMeshers_QuadToTriaAdaptor* aQuad2Trias = new StdMeshers_QuadToTriaAdaptor;
+    aQuad2Trias->Compute( theMesh );
+    proxyMesh.reset( aQuad2Trias );
+  }
+
+  MG_Tetra_API mgTetra( _compute_canceled, _progress );
 
-    int anInvalidEnforcedFlags = 0;
-    Ok = writeGMFFile(aGMFFileName.ToCString(), aRequiredVerticesFileName.ToCString(), aSolFileName.ToCString(),
-                      *proxyMesh, *theHelper,
-                      aNodeByGhs3dId, aFaceByGhs3dId, aNodeToGhs3dIdMap,
-                      aNodeGroupByGhs3dId, anEdgeGroupByGhs3dId, aFaceGroupByGhs3dId,
-                      enforcedNodes, enforcedEdges, enforcedTriangles,
-                      enfVerticesWithGroup, coordsSizeMap, anInvalidEnforcedFlags);
-    //}
+  _isLibUsed = mgTetra.IsLibrary();
+
+  int anInvalidEnforcedFlags = 0;
+  Ok = writeGMFFile(&mgTetra,
+                    aGMFFileName.ToCString(), aRequiredVerticesFileName.ToCString(), aSolFileName.ToCString(),
+                    *proxyMesh, *theHelper,
+                    aNodeByGhs3dId, aFaceByGhs3dId, aNodeToGhs3dIdMap,
+                    aNodeGroupByGhs3dId, anEdgeGroupByGhs3dId, aFaceGroupByGhs3dId,
+                    enforcedNodes, enforcedEdges, enforcedTriangles,
+                    enfVerticesWithGroup, coordsSizeMap, anInvalidEnforcedFlags);
 
   // -----------------
   // run MG-Tetra mesher
   // -----------------
 
-  TCollection_AsciiString cmd = TCollection_AsciiString((char*)GHS3DPlugin_Hypothesis::CommandToRun( _hyp, false ).c_str());
+  TCollection_AsciiString cmd = GHS3DPlugin_Hypothesis::CommandToRun( _hyp, false, mgTetra.IsExecutable() ).c_str();
 
-  cmd += TCollection_AsciiString(" --in ") + aGMFFileName;
-  if ( nbEnforcedVertices + nbEnforcedNodes)
-    cmd += TCollection_AsciiString(" --required_vertices ") + aGenericNameRequired;
-  cmd += TCollection_AsciiString(" --out ") + aResultFileName;
+  if ( mgTetra.IsExecutable() )
+  {
+    cmd += TCollection_AsciiString(" --in ") + aGMFFileName;
+    if ( nbEnforcedVertices + nbEnforcedNodes)
+      cmd += TCollection_AsciiString(" --required_vertices ") + aGenericNameRequired;
+    cmd += TCollection_AsciiString(" --out ") + aResultFileName;
+  }
   if ( !_logInStandardOutput )
+  {
+    mgTetra.SetLogFile( aLogFileName.ToCString() );
     cmd += TCollection_AsciiString(" 1>" ) + aLogFileName;  // dump into file
-
+  }
   std::cout << std::endl;
   std::cout << "MG-Tetra execution..." << std::endl;
   std::cout << cmd << std::endl;
 
   _compute_canceled = false;
 
-  int err = system( cmd.ToCString() ); // run
-
   std::string errStr;
-  if ( err )
-    errStr = SMESH_Comment("system(mg-tetra.exe ...) command failed with error: ")
-      << strerror( errno );
-  else
+  Ok = mgTetra.Compute( cmd.ToCString(), errStr ); // run
+
+  if ( _logInStandardOutput && mgTetra.IsLibrary() )
+    std::cout << std::endl << mgTetra.GetLog() << std::endl;
+  if ( Ok )
     std::cout << std::endl << "End of MG-Tetra execution !" << std::endl;
 
   // --------------
@@ -2156,7 +1976,8 @@ bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
   GHS3DPlugin_Hypothesis::TSetStrings groupsToRemove = GHS3DPlugin_Hypothesis::GetGroupsToRemove(_hyp);
   const bool toMakeGroupsOfDomains = GHS3DPlugin_Hypothesis::GetToMakeGroupsOfDomains( _hyp );
 
-  Ok = readGMFFile(aResultFileName.ToCString(),
+  Ok = readGMFFile(&mgTetra,
+                   aResultFileName.ToCString(),
                    this,
                    theHelper, aNodeByGhs3dId, aFaceByGhs3dId, aNodeToGhs3dIdMap,
                    aNodeGroupByGhs3dId, anEdgeGroupByGhs3dId, aFaceGroupByGhs3dId,
@@ -2184,11 +2005,12 @@ bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
     //if ( !toMakeGroupsOfDomains && _hyp && _hyp->GetToMakeGroupsOfDomains() )
     //error( COMPERR_WARNING, "'toMakeGroupsOfDomains' is ignored since 'toMeshHoles' is OFF." );
   }
-  else if ( OSD_File( aLogFileName ).Size() > 0 )
+  else if ( mgTetra.HasLog() )
   {
     // get problem description from the log file
     _Ghs2smdsConvertor conv( aNodeByGhs3dId, proxyMesh );
-    storeErrorDescription( aLogFileName, conv );
+    storeErrorDescription( _logInStandardOutput ? 0 : aLogFileName.ToCString(),
+                           mgTetra.GetLog(), conv );
   }
   else {
     // the log file is empty
@@ -2544,30 +2366,21 @@ static char* getIds( char* ptr, int nbIds, vector<int>& ids )
  */
 //================================================================================
 
-bool GHS3DPlugin_GHS3D::storeErrorDescription(const TCollection_AsciiString& logFile,
-                                              const _Ghs2smdsConvertor &     toSmdsConvertor )
+bool GHS3DPlugin_GHS3D::storeErrorDescription(const char*                logFile,
+                                              const std::string&         log,
+                                              const _Ghs2smdsConvertor & toSmdsConvertor )
 {
   if(_compute_canceled)
     return error(SMESH_Comment("interruption initiated by user"));
-  // open file
-#ifdef WIN32
-  int file = ::_open (logFile.ToCString(), _O_RDONLY|_O_BINARY);
-#else
-  int file = ::open (logFile.ToCString(), O_RDONLY);
-#endif
-  if ( file < 0 )
-    return error( SMESH_Comment("See ") << logFile << " for problem description");
-
-  // get file size
-  off_t length = lseek( file, 0, SEEK_END);
-  lseek( file, 0, SEEK_SET);
 
   // read file
-  vector< char > buf( length );
-  int nBytesRead = ::read (file, & buf[0], length);
-  ::close (file);
-  char* ptr = & buf[0];
-  char* bufEnd = ptr + nBytesRead;
+  // SMESH_File file( logFile.ToCString() );
+  // if ( file.size() == 0 )
+  //   return error( SMESH_Comment("See ") << logFile << " for problem description");
+
+  char* ptr = const_cast<char*>( log.c_str() );
+  char* buf = ptr, * bufEnd = ptr + log.size();
+
 
   SMESH_Comment errDescription;
 
@@ -2806,11 +2619,13 @@ bool GHS3DPlugin_GHS3D::storeErrorDescription(const TCollection_AsciiString& log
     }
   }
 
-  if ( errDescription.empty() )
-    errDescription << "See " << logFile << " for problem description";
-  else
-    errDescription << "\nSee " << logFile << " for more information";
-
+  if ( logFile && logFile[0] )
+  {
+    if ( errDescription.empty() )
+      errDescription << "See " << logFile << " for problem description";
+    else
+      errDescription << "\nSee " << logFile << " for more information";
+  }
   return error( errDescription );
 }
 
@@ -2966,19 +2781,11 @@ bool GHS3DPlugin_GHS3D::Evaluate(SMESH_Mesh& aMesh,
 
 bool GHS3DPlugin_GHS3D::importGMFMesh(const char* theGMFFileName, SMESH_Mesh& theMesh)
 {
-  SMESH_MesherHelper* helper  = new SMESH_MesherHelper(theMesh );
-  std::vector <const SMDS_MeshNode*> dummyNodeVector;
-  std::vector <const SMDS_MeshElement*> aFaceByGhs3dId;
-  std::map<const SMDS_MeshNode*,int> dummyNodeMap;
-  std::map<std::vector<double>, std::string> dummyEnfVertGroup;
-  std::vector<std::string> dummyElemGroup;
-  std::set<std::string> dummyGroupsToRemove;
-
-  bool ok = readGMFFile(theGMFFileName,
-                        this,
-                        helper, dummyNodeVector, aFaceByGhs3dId, dummyNodeMap, dummyElemGroup, dummyElemGroup, dummyElemGroup, dummyGroupsToRemove);
+  SMESH_ComputeErrorPtr err = theMesh.GMFToMesh( theGMFFileName, /*makeRequiredGroups =*/ true );
+
   theMesh.GetMeshDS()->Modified();
-  return ok;
+
+  return ( !err || err->IsOK());
 }
 
 namespace
@@ -3105,3 +2912,26 @@ void GHS3DPlugin_GHS3D::SetEventListener(SMESH_subMesh* subMesh)
 {
   subMesh->SetEventListener( new _GroupsOfDomainsRemover(), 0, subMesh );
 }
+
+//================================================================================
+/*!
+ * \brief If possible, returns progress of computation [0.,1.]
+ */
+//================================================================================
+
+double GHS3DPlugin_GHS3D::GetProgress() const
+{
+  if ( _isLibUsed )
+  {
+    // this->_progress is advanced by MG_Tetra_API according to messages from MG library
+    // but sharply. Advanced it a bit to get smoother advancement.
+    GHS3DPlugin_GHS3D* me = const_cast<GHS3DPlugin_GHS3D*>( this );
+    if ( _progress < 0.1 ) // the first message is at 10%
+      me->_progress = GetProgressByTic();
+    else if ( _progress < 0.98 )
+      me->_progress += 1e-4;
+    return _progress;
+  }
+
+  return -1;
+}
index 3dd25e37c5d4eaee4dd667269cce5bc3b26f33d8..0c5326bc905bf90b93986d48b5b6f0546c0f17b7 100644 (file)
 #include <map>
 #include <vector>
 
-extern "C"
-{
-  #include "libmesh5.h"
-}
-
 #ifndef GMFVERSION
 #define GMFVERSION GmfDouble
 #endif
@@ -82,6 +77,8 @@ public:
 
   static const char* Name() { return "MG-Tetra"; }
 
+  virtual double GetProgress() const;
+
 protected:
   const GHS3DPlugin_Hypothesis*   _hyp;
   const StdMeshers_ViscousLayers* _viscousLayersHyp;
@@ -89,19 +86,21 @@ protected:
    
 private:
 
-  bool         storeErrorDescription(const TCollection_AsciiString& logFile,
-                                     const _Ghs2smdsConvertor &     toSmdsConvertor );
+  bool         storeErrorDescription(const char*                logFile,
+                                     const std::string&         log,
+                                     const _Ghs2smdsConvertor & toSmdsConvertor );
   TopoDS_Shape entryToShape(std::string entry);
-  
-  int  _iShape;
-  int  _nbShape;
-  bool _keepFiles;
-  bool _removeLogOnSuccess;
-  bool _logInStandardOutput;
-  SALOMEDS::Study_var myStudy;
-  SMESH_Gen_i* smeshGen_i;
-
-  volatile bool _compute_canceled;
+
+  int                 _iShape;
+  int                 _nbShape;
+  bool                _keepFiles;
+  bool                _removeLogOnSuccess;
+  bool                _logInStandardOutput;
+  SALOMEDS::Study_var _study;
+  SMESH_Gen_i*        _smeshGen_i;
+
+  volatile bool       _compute_canceled;
+  bool                _isLibUsed;
 };
 
 /*!
index 5f3e70d8bfff8e79e7f8482285b9ac4ca295bc30..4cbcd0bb94cef304cec0d6b5f60af866722caaba 100644 (file)
@@ -432,8 +432,12 @@ bool GHS3DPlugin_Hypothesis::GetRemoveLogOnSuccess() const
 //function : SetEnforcedVertex
 //=======================================================================
 
-bool GHS3DPlugin_Hypothesis::SetEnforcedVertex(std::string theName, std::string theEntry, std::string theGroupName,
-                                               double size, double x, double y, double z, bool isCompound)
+bool GHS3DPlugin_Hypothesis::SetEnforcedVertex(std::string theName,
+                                               std::string theEntry,
+                                               std::string theGroupName,
+                                               double      size,
+                                               double x, double y, double z,
+                                               bool        isCompound)
 {
   MESSAGE("GHS3DPlugin_Hypothesis::SetEnforcedVertex(\""<< theName << "\", \""<< theEntry << "\", \"" << theGroupName << "\", "
                                                       << size << ", " << x << ", " << y << ", " << z  << ", "<< isCompound << ")");
@@ -1459,9 +1463,10 @@ bool GHS3DPlugin_Hypothesis::SetParametersByDefaults(const TDefaults&  dflts,
 //================================================================================
 
 std::string GHS3DPlugin_Hypothesis::CommandToRun(const GHS3DPlugin_Hypothesis* hyp,
-                                                 const bool         hasShapeToMesh)
+                                                 const bool                    hasShapeToMesh,
+                                                 const bool                    forExucutable)
 {
-  TCollection_AsciiString cmd = GetExeName().c_str();
+  std::string cmd = GetExeName();
   // check if any option is overridden by hyp->myTextOption
   bool max_memory   = hyp ? ( hyp->myTextOption.find("--max_memory")  == std::string::npos ) : true;
   bool auto_memory   = hyp ? ( hyp->myTextOption.find("--automatic_memory")  == std::string::npos ) : true;
@@ -1484,21 +1489,15 @@ std::string GHS3DPlugin_Hypothesis::CommandToRun(const GHS3DPlugin_Hypothesis* h
   // so allow to use about all available memory
   if ( max_memory ) {
     long aMaximumMemory = hyp ? hyp->myMaximumMemory : -1;
-    ostringstream tmpMaximumMemory;
     cmd += " --max_memory ";
-    if ( aMaximumMemory < 0 )
-      tmpMaximumMemory << DefaultMaximumMemory();
-    else
-      tmpMaximumMemory << aMaximumMemory;
-    cmd += tmpMaximumMemory.str().c_str();
+    if ( aMaximumMemory < 0 ) cmd += SMESH_Comment( DefaultMaximumMemory() );
+    else                      cmd += SMESH_Comment( aMaximumMemory );
   }
   if ( auto_memory && !useBndRecovery ) {
     long aInitialMemory = hyp ? hyp->myInitialMemory : -1;
     cmd += " --automatic_memory ";
-    if ( aInitialMemory > 0 )
-      cmd += (int)aInitialMemory;
-    else
-      cmd += "100";
+    if ( aInitialMemory > 0 ) cmd += SMESH_Comment( aInitialMemory );
+    else                      cmd += "100";
   }
   // component to mesh
   if ( comp && !useBndRecovery ) {
@@ -1507,36 +1506,35 @@ std::string GHS3DPlugin_Hypothesis::CommandToRun(const GHS3DPlugin_Hypothesis* h
       cmd += " --components all";
     else {
       bool aToMeshHoles = hyp ? hyp->myToMeshHoles : DefaultMeshHoles();
-      if ( aToMeshHoles )
-        cmd += " --components all";
-      else
-        cmd += " --components outside_components";
+      if ( aToMeshHoles ) cmd += " --components all";
+      else                cmd += " --components outside_components";
     }
   }
   const bool toCreateNewNodes = ( no_int_points && ( !hyp || hyp->myToCreateNewNodes ));
 
   // optimization level
-  // This option need to be improved concerning new mg-tetra version
-  if ( optim_level && hyp && !useBndRecovery && toCreateNewNodes ) {
+  if ( !toCreateNewNodes ) {
+    cmd += " --optimisation_level none"; // issue 22608
+  }
+  else if ( optim_level && hyp && !useBndRecovery ) {
     if ( hyp->myOptimizationLevel >= 0 && hyp->myOptimizationLevel < 5 ) {
       const char* level[] = { "none" , "light" , "standard" , "standard+" , "strong" };
       cmd += " --optimisation_level ";
       cmd += level[ hyp->myOptimizationLevel ];
     }
   }
-  if ( !toCreateNewNodes ) {
-    cmd += " --optimisation_level none"; // issue 22608
-  }
 
   // to create internal nodes
   if ( no_int_points && !toCreateNewNodes ) {
-    cmd += " --no_internal_points";
+    if ( forExucutable )
+      cmd += " --no_internal_points";
+    else
+      cmd += " --internalpoints no";
   }
 
   // verbose mode
   if ( verbose && hyp ) {
-    cmd += " --verbose ";
-    cmd += hyp->myVerboseLevel;
+    cmd += " --verbose " + SMESH_Comment( hyp->myVerboseLevel );
   }
 
   // boundary recovery version
@@ -1551,26 +1549,30 @@ std::string GHS3DPlugin_Hypothesis::CommandToRun(const GHS3DPlugin_Hypothesis* h
 
   // to remove initial central point.
   if ( rem && hyp && hyp->myToRemoveCentralPoint) {
-    cmd += " --no_initial_central_point";
+    if ( forExucutable )
+      cmd += " --no_initial_central_point";
+    else
+      cmd += " --centralpoint no";
   }
 
   // options as text
   if ( hyp && !hyp->myTextOption.empty() ) {
-    cmd += " ";
-    cmd += (char*) hyp->myTextOption.c_str();
+    cmd += " " + hyp->myTextOption;
   }
 
   // to define volumic gradation.
-  if ( gra && hyp) {
-    cmd += " -Dcpropa=";
-    cmd += hyp->myGradation;
+  if ( gra && hyp ) {
+    if ( forExucutable )
+      cmd += " -Dcpropa=" + SMESH_Comment( hyp->myGradation );
+    else
+      cmd += " --gradation " + SMESH_Comment( hyp->myGradation );
   }
 
 #ifdef WIN32
   cmd += " < NUL";
 #endif
 
-  return cmd.ToCString();
+  return cmd;
 }
 
 //================================================================================
index 06c26ffd03225e5c3bf902e9c3b6513605a09f50..c6990a33f8a686ceed82f212d406c0f1890e670b 100644 (file)
@@ -228,7 +228,8 @@ public:
    * \brief Return command to run MG-Tetra mesher excluding file prefix (-f)
    */
   static std::string CommandToRun(const GHS3DPlugin_Hypothesis* hyp,
-                                  const bool                    hasShapeToMesh=true);
+                                  const bool                    hasShapeToMesh,
+                                  const bool                    forExucutable);
   /*!
    * \brief Return a unique file name
    */
@@ -337,39 +338,39 @@ public:
 
 private:
 
-  bool   myToMeshHoles;
-  bool   myToMakeGroupsOfDomains;
-  long   myMaximumMemory;
-  long   myInitialMemory;
-  short  myOptimizationLevel;
-  bool   myKeepFiles;
+  bool        myToMeshHoles;
+  bool        myToMakeGroupsOfDomains;
+  long        myMaximumMemory;
+  long        myInitialMemory;
+  short       myOptimizationLevel;
+  bool        myKeepFiles;
   std::string myWorkingDirectory;
-  short  myVerboseLevel;
-  bool   myToCreateNewNodes;
-  bool   myToUseBoundaryRecoveryVersion;
-  bool   myToUseFemCorrection;
-  bool   myToRemoveCentralPoint;
-  bool   myLogInStandardOutput;
-  bool   myRemoveLogOnSuccess;
+  short       myVerboseLevel;
+  bool        myToCreateNewNodes;
+  bool        myToUseBoundaryRecoveryVersion;
+  bool        myToUseFemCorrection;
+  bool        myToRemoveCentralPoint;
+  bool        myLogInStandardOutput;
+  bool        myRemoveLogOnSuccess;
   std::string myTextOption;
-  double myGradation;
+  double      myGradation;
   
-  TGHS3DEnforcedVertexList _enfVertexList;
+  TGHS3DEnforcedVertexList         _enfVertexList;
   TGHS3DEnforcedVertexCoordsValues _enfVertexCoordsSizeList;
-  TGHS3DEnforcedVertexEntryValues _enfVertexEntrySizeList;
+  TGHS3DEnforcedVertexEntryValues  _enfVertexEntrySizeList;
   // map to get "manual" enf vertex (through the coordinates)
-  TCoordsGHS3DEnforcedVertexMap _coordsEnfVertexMap;
+  TCoordsGHS3DEnforcedVertexMap    _coordsEnfVertexMap;
   // map to get "geom" enf vertex (through the geom entries)
   TGeomEntryGHS3DEnforcedVertexMap _geomEntryEnfVertexMap;
   
   
-  TGHS3DEnforcedMeshList _enfMeshList;
+  TGHS3DEnforcedMeshList                   _enfMeshList;
   // map to get enf meshes through the entries
-  TEntryGHS3DEnforcedMeshListMap _entryEnfMeshMap;
-  TIDSortedNodeGroupMap _enfNodes;
-  TIDSortedElemGroupMap _enfEdges;
-  TIDSortedElemGroupMap _enfTriangles;
-  TID2SizeMap _nodeIDToSizeMap;
+  TEntryGHS3DEnforcedMeshListMap           _entryEnfMeshMap;
+  TIDSortedNodeGroupMap                    _enfNodes;
+  TIDSortedElemGroupMap                    _enfEdges;
+  TIDSortedElemGroupMap                    _enfTriangles;
+  TID2SizeMap                              _nodeIDToSizeMap;
   std::map<std::string, TIDSortedElemSet > _entryToElemsMap;
   
   TSetStrings _groupsToRemove;
diff --git a/src/GHS3DPlugin/MG_Tetra_API.cxx b/src/GHS3DPlugin/MG_Tetra_API.cxx
new file mode 100644 (file)
index 0000000..e5adee0
--- /dev/null
@@ -0,0 +1,1186 @@
+// Copyright (C) 2004-2016  CEA/DEN, EDF R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+
+#include "MG_Tetra_API.hxx"
+
+#include <SMESH_Comment.hxx>
+#include <SMESH_File.hxx>
+#include <Utils_SALOME_Exception.hxx>
+
+#include <vector>
+#include <iterator>
+#include <cstring>
+
+#ifdef USE_MG_LIBS
+
+extern "C"{
+#include <meshgems/meshgems.h>
+#include <meshgems/tetra.h>
+}
+
+struct MG_Tetra_API::LibData
+{
+  // MG objects
+  context_t *       _context;
+  tetra_session_t * _session;
+  mesh_t *          _tria_mesh;
+  sizemap_t *       _sizemap;
+  mesh_t *          _tetra_mesh;
+
+  // data to pass to MG
+  std::vector<double> _xyz;
+  std::vector<double> _nodeSize; // required nodes
+  std::vector<int>    _edgeNodes;
+  int                 _nbRequiredEdges;
+  std::vector<int>    _triaNodes;
+  int                 _nbRequiredTria;
+
+  int                 _count;
+  volatile bool&      _cancelled_flag;
+  std::string         _errorStr;
+  double&             _progress;
+
+  LibData( volatile bool & cancelled_flag, double& progress )
+    : _context(0), _session(0), _tria_mesh(0), _sizemap(0), _tetra_mesh(0),
+      _nbRequiredEdges(0), _nbRequiredTria(0),
+      _cancelled_flag( cancelled_flag ), _progress( progress )
+  {
+  }
+  // methods setting callbacks implemented after callback definitions
+  void Init();
+  bool Compute();
+
+  ~LibData()
+  {
+    if ( _tetra_mesh )
+      tetra_regain_mesh( _session, _tetra_mesh );
+    if ( _session )
+      tetra_session_delete( _session );
+    if ( _tria_mesh )
+      mesh_delete( _tria_mesh );
+    if ( _sizemap )
+      sizemap_delete( _sizemap );
+    if ( _context )
+      context_delete( _context );
+
+    _tetra_mesh = 0;
+    _session = 0;
+    _tria_mesh = 0;
+    _sizemap = 0;
+    _context = 0;
+  }
+
+  void AddError( const char *txt )
+  {
+    if ( txt )
+      _errorStr += txt;
+  }
+
+  const std::string& GetErrors()
+  {
+    return _errorStr;
+  }
+
+  void MG_Error(const char* txt="")
+  {
+    SMESH_Comment msg("\nMeshGems error. ");
+    msg << txt << "\n";
+    AddError( msg.c_str() );
+  }
+
+  bool SetParam( const std::string& param, const std::string& value )
+  {
+    status_t ret = tetra_set_param( _session, param.c_str(), value.c_str() );
+#ifdef _DEBUG_
+    //std::cout << param << " = " << value << std::endl;
+#endif
+    return ( ret == STATUS_OK );
+  }
+
+  bool Cancelled()
+  {
+    return _cancelled_flag;
+  }
+
+  int ReadNbSubDomains()
+  {
+    integer nb = 0;
+    status_t ret = mesh_get_subdomain_count( _tetra_mesh, & nb );
+
+    if ( ret != STATUS_OK ) MG_Error("mesh_get_subdomain_count problem");
+    return nb;
+  }
+
+  int ReadNbNodes()
+  {
+    integer nb = 0;
+    status_t ret = mesh_get_vertex_count( _tetra_mesh, & nb );
+
+    if ( ret != STATUS_OK ) MG_Error("mesh_get_vertex_count problem");
+    return nb;
+  }
+
+  int ReadNbEdges()
+  {
+    integer nb = 0;
+    status_t ret = mesh_get_edge_count( _tetra_mesh, & nb );
+
+    if ( ret != STATUS_OK ) MG_Error("mesh_get_edge_count problem");
+    return nb;
+  }
+
+  int ReadNbTria()
+  {
+    integer nb = 0;
+    status_t ret = mesh_get_triangle_count( _tetra_mesh, & nb );
+
+    if ( ret != STATUS_OK ) MG_Error("mesh_get_triangle_count problem");
+    return nb;
+  }
+
+  int ReadNbQuads()
+  {
+    integer nb = 0;
+    status_t ret = mesh_get_quadrangle_count( _tetra_mesh, & nb );
+
+    if ( ret != STATUS_OK ) MG_Error("mesh_get_quadrangle_count problem");
+    return nb;
+  }
+
+  int ReadNbTetra()
+  {
+    integer nb = 0;
+    status_t ret = mesh_get_tetrahedron_count( _tetra_mesh, & nb );
+
+    if ( ret != STATUS_OK ) MG_Error("mesh_get_tetrahedron_count problem");
+    return nb;
+  }
+
+  int ReadNbHexa()
+  {
+    integer nb = 0;
+    status_t ret = mesh_get_hexahedron_count( _tetra_mesh, & nb );
+
+    if ( ret != STATUS_OK ) MG_Error("mesh_get_hexahedron_count problem");
+    return nb;
+  }
+
+  void ResetCounter()
+  {
+    _count = 1;
+  }
+
+  void ReadSubDomain( int* nbNodes, int* faceInd, int* ori, int* domain )
+  {
+    integer tag, seed_type, seed_idx, seed_orientation;
+    status_t ret = mesh_get_subdomain_description( _tetra_mesh, _count,
+                                                   &tag, &seed_type, &seed_idx, &seed_orientation);
+
+    if ( ret != STATUS_OK ) MG_Error( "unable to get a sub-domain description");
+
+    *nbNodes = 3;
+    *faceInd = seed_idx;
+    *domain  = tag;
+    *ori     = seed_orientation;
+
+    ++_count;
+  }
+  void ReadNodeXYZ( double* x, double* y, double *z, int* /*domain*/  )
+  {
+    real coo[3];
+    status_t ret = mesh_get_vertex_coordinates( _tetra_mesh, _count, coo );
+    if ( ret != STATUS_OK ) MG_Error( "unable to get resulting vertices" );
+
+    *x = coo[0];
+    *y = coo[1];
+    *z = coo[2];
+
+    ++_count;
+  }
+
+  void ReadEdgeNodes( int* node1, int* node2, int* domain )
+  {
+    integer vtx[2], tag;
+    status_t ret = mesh_get_edge_vertices( _tetra_mesh, _count, vtx);
+    if (ret != STATUS_OK) MG_Error( "unable to get resulting edge" );
+
+    *node1 = vtx[0];
+    *node2 = vtx[1];
+
+    ret = mesh_get_edge_tag( _tetra_mesh, _count, &tag );
+    if (ret != STATUS_OK) MG_Error( "unable to get resulting edge tag" );
+
+    *domain = tag;
+
+    ++_count;
+  }
+
+  void ReadTriaNodes( int* node1, int* node2, int* node3, int* domain )
+  {
+    integer vtx[3], tag;
+    status_t ret = mesh_get_triangle_vertices( _tetra_mesh, _count, vtx);
+    if (ret != STATUS_OK) MG_Error( "unable to get resulting triangle" );
+
+    *node1 = vtx[0];
+    *node2 = vtx[1];
+    *node3 = vtx[2];
+
+    ret = mesh_get_triangle_tag( _tetra_mesh, _count, &tag );
+    if (ret != STATUS_OK) MG_Error( "unable to get resulting triangle tag" );
+
+    *domain = tag;
+
+    ++_count;
+  }
+
+  void ReadQuadNodes( int* node1, int* node2, int* node3, int* node4, int* domain )
+  {
+    integer vtx[4], tag;
+    status_t ret = mesh_get_quadrangle_vertices( _tetra_mesh, _count, vtx);
+    if (ret != STATUS_OK) MG_Error( "unable to get resulting quadrangle" );
+
+    *node1 = vtx[0];
+    *node2 = vtx[1];
+    *node3 = vtx[2];
+    *node4 = vtx[3];
+
+    ret = mesh_get_quadrangle_tag( _tetra_mesh, _count, &tag );
+    if (ret != STATUS_OK) MG_Error( "unable to get resulting quadrangle tag" );
+
+    *domain = tag;
+
+    ++_count;
+  }
+
+  void ReadTetraNodes( int* node1, int* node2, int* node3, int* node4, int* domain )
+  {
+    integer vtx[4], tag;
+    status_t ret = mesh_get_tetrahedron_vertices( _tetra_mesh, _count, vtx);
+    if (ret != STATUS_OK) MG_Error( "unable to get resulting tetrahedron" );
+
+    *node1 = vtx[0];
+    *node2 = vtx[1];
+    *node3 = vtx[2];
+    *node4 = vtx[3];
+
+    ret = mesh_get_tetrahedron_tag( _tetra_mesh, _count, &tag );
+    if (ret != STATUS_OK) MG_Error( "unable to get resulting tetrahedron tag" );
+
+    *domain = tag;
+
+    ++_count;
+  }
+
+  void ReadHexaNodes( int* node1, int* node2, int* node3, int* node4,
+                     int* node5, int* node6, int* node7, int* node8, int* domain )
+  {
+    integer vtx[8], tag;
+    status_t ret = mesh_get_hexahedron_vertices( _tetra_mesh, _count, vtx);
+    if (ret != STATUS_OK) MG_Error( "unable to get resulting hexahedron" );
+
+    *node1 = vtx[0];
+    *node2 = vtx[1];
+    *node3 = vtx[2];
+    *node4 = vtx[3];
+    *node5 = vtx[4];
+    *node6 = vtx[5];
+    *node7 = vtx[6];
+    *node8 = vtx[7];
+
+    ret = mesh_get_hexahedron_tag( _tetra_mesh, _count, &tag );
+    if (ret != STATUS_OK) MG_Error( "unable to get resulting hexahedron tag" );
+
+    *domain = tag;
+
+    ++_count;
+  }
+
+  void SetNbVertices( int nb )
+  {
+    _xyz.reserve( _xyz.capacity() + nb );
+  }
+
+  void SetNbEdges( int nb )
+  {
+    _edgeNodes.reserve( nb * 2 );
+  }
+
+  void SetNbTria( int nb )
+  {
+    _triaNodes.reserve( nb * 3 );
+  }
+
+  void SetNbReqVertices( int nb )
+  {
+    _nodeSize.reserve( nb );
+  }
+
+  void SetNbReqEdges( int nb )
+  {
+    _nbRequiredEdges = nb;
+  }
+
+  void SetNbReqTria( int nb )
+  {
+    _nbRequiredTria = nb;
+  }
+
+  void AddNode( double x, double y, double z, int domain )
+  {
+    _xyz.push_back( x );
+    _xyz.push_back( y );
+    _xyz.push_back( z );
+  }
+
+  void AddSizeAtNode( double size )
+  {
+    _nodeSize.push_back( size );
+  }
+  
+  void AddEdgeNodes( int node1, int node2, int domain )
+  {
+    _edgeNodes.push_back( node1 );
+    _edgeNodes.push_back( node2 );
+  }
+  
+  void AddTriaNodes( int node1, int node2, int node3, int domain )
+  {
+    _triaNodes.push_back( node1 );
+    _triaNodes.push_back( node2 );
+    _triaNodes.push_back( node3 );
+  }
+
+  int NbNodes()
+  {
+    return _xyz.size() / 3;
+  }
+
+  double* NodeCoord( int iNode )
+  {
+    return & _xyz[ iNode * 3 ];
+  }
+
+  int NbEdges()
+  {
+    return _edgeNodes.size() / 2;
+  }
+
+  int* GetEdgeNodes( int iEdge )
+  {
+    return & _edgeNodes[ iEdge * 2 ];
+  }
+
+  int NbTriangles()
+  {
+    return _triaNodes.size() / 3;
+  }
+
+  int * GetTriaNodes( int iTria )
+  {
+    return & _triaNodes[ iTria * 3 ];
+  }
+
+  int IsVertexRequired( int iNode )
+  {
+    return ! ( iNode < int( _xyz.size() - _nodeSize.size() ));
+  }
+
+  double GetSizeAtVertex( int iNode )
+  {
+    return IsVertexRequired( iNode ) ? _nodeSize[ iNode - _xyz.size() + _nodeSize.size() ] : 0.;
+  }
+};
+
+namespace // functions called by MG library to exchange with the application
+{
+  status_t get_vertex_count(integer * nbvtx, void *user_data)
+  {
+    MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
+    *nbvtx = data->NbNodes();
+
+    return STATUS_OK;
+  }
+
+  status_t get_vertex_coordinates(integer ivtx, real * xyz, void *user_data)
+  {
+    MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
+    double* coord = data->NodeCoord( ivtx-1 );
+    for (int j = 0; j < 3; j++)
+      xyz[j] = coord[j];
+
+    return STATUS_OK;
+  }
+  status_t get_edge_count(integer * nbedge, void *user_data)
+  {
+    MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
+    *nbedge = data->NbEdges();
+
+    return STATUS_OK;
+  }
+
+  status_t get_edge_vertices(integer iedge, integer * vedge, void *user_data)
+  {
+    MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
+    int* nodes = data->GetEdgeNodes( iedge-1 );
+    vedge[0] = nodes[0];
+    vedge[1] = nodes[1];
+
+    return STATUS_OK;
+  }
+
+  status_t get_triangle_count(integer * nbtri, void *user_data)
+  {
+    MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
+    *nbtri = data->NbTriangles();
+
+    return STATUS_OK;
+  }
+
+  status_t get_triangle_vertices(integer itri, integer * vtri, void *user_data)
+  {
+    MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
+    int* nodes = data->GetTriaNodes( itri-1 );
+    vtri[0] = nodes[0];
+    vtri[1] = nodes[1];
+    vtri[2] = nodes[2];
+
+    return STATUS_OK;
+  }
+
+  // status_t get_triangle_extra_vertices(integer itri, integer * typetri,
+  //                                      integer * evtri, void *user_data)
+  // {
+  //   int j;
+  //   MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
+
+  //   if (1) {
+  //     /* We want to describe a linear "3 nodes" triangle */
+  //     *typetri = MESHGEMS_MESH_ELEMENT_TYPE_TRIA3;
+  //   } else {
+  //     /* We want to describe a quadratic "6 nodes" triangle */
+  //     *typetri = MESHGEMS_MESH_ELEMENT_TYPE_TRIA6;
+  //     for (j = 0; j < 3; j++)
+  //       evtri[j] = 0;             /* the j'th quadratic vertex index of the itri'th triangle */
+  //   }
+
+  //   return STATUS_OK;
+  // }
+
+  // status_t get_tetrahedron_count(integer * nbtetra, void *user_data)
+  // {
+  //   MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
+
+  //   *nbtetra = 0;                 /* the number of tetra in your input mesh (0 if you describe a surface mesh) */
+
+  //   return STATUS_OK;
+  // }
+
+  // status_t get_tetrahedron_vertices(integer itetra, integer * vtetra,
+  //                                   void *user_data)
+  // {
+  //   int j;
+  //   MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
+
+  //   for (j = 0; j < 4; j++)
+  //     vtetra[j] = 0;              /* the j'th vertex index of the itetra'th tetrahedron */
+
+  //   return STATUS_OK;
+  // }
+
+  status_t get_vertex_required_property(integer ivtx, integer * rvtx, void *user_data)
+  {
+    MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
+    *rvtx = data->IsVertexRequired( ivtx - 1 );
+
+    return STATUS_OK;
+  }
+
+  status_t get_vertex_weight(integer ivtx, real * wvtx, void *user_data)
+  {
+    MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
+    *wvtx = data->GetSizeAtVertex( ivtx - 1 );
+
+    return STATUS_OK;
+  }
+
+  status_t my_message_cb(message_t * msg, void *user_data)
+  {
+    char *desc;
+    message_get_description(msg, &desc);
+
+    MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
+    data->AddError( desc );
+
+#ifdef _DEBUG_
+    //std::cout << desc << std::endl;
+#endif
+
+    // Compute progress
+    // corresponding messages are:
+    // "  -- PHASE 1 COMPLETED"               => 10 %
+    // "  -- PHASE 2 COMPLETED"               => 25 %
+    // "     ** ITERATION   1"                => 25.* %
+    // "     ** ITERATION   2"                => 25.* %
+    // "  -- PHASE 3 COMPLETED"               => 70 %
+    // "  -- PHASE 4 COMPLETED"               => 98 %
+
+    if ( strncmp( "-- PHASE ", desc + 2, 9 ) == 0 && desc[ 13 ] == 'C' )
+    {
+      const double progress[] = { 10., 25., 70., 98., 100., 100., 100. };
+      int       phase = atoi( desc + 11 );
+      data->_progress = std::max( data->_progress, progress[ phase - 1 ] / 100. );
+    }
+    else if ( strncmp( "** ITERATION ", desc + 5, 13 ) == 0 )
+    {
+      int         iter = atoi( desc + 20 );
+      double   percent = 25. + iter * ( 70 - 25 ) / 20.;
+      data->_progress = std::max( data->_progress, ( percent / 100. ));
+    }
+
+    return STATUS_OK;
+  }
+
+  status_t my_interrupt_callback(integer *interrupt_status, void *user_data)
+  {
+    MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
+    *interrupt_status = ( data->Cancelled() ? INTERRUPT_STOP : INTERRUPT_CONTINUE );
+
+
+    return STATUS_OK;
+  }
+
+} // end namespace
+
+
+void MG_Tetra_API::LibData::Init()
+{
+  status_t ret;
+
+  // Create the meshgems working context
+  _context = context_new();
+  if ( !_context ) MG_Error( "unable to create a new context" );
+
+  // Set the message callback for the _context.
+  ret = context_set_message_callback( _context, my_message_cb, this );
+  if ( ret != STATUS_OK ) MG_Error("in context_set_message_callback");
+
+  // Create the structure holding the callbacks giving access to triangle mesh
+  _tria_mesh = mesh_new( _context );
+  if ( !_tria_mesh ) MG_Error("unable to create a new mesh");
+
+  // Set callbacks to provide triangle mesh data
+  mesh_set_get_vertex_count( _tria_mesh, get_vertex_count, this );
+  mesh_set_get_vertex_coordinates( _tria_mesh, get_vertex_coordinates, this );
+  mesh_set_get_vertex_required_property( _tria_mesh, get_vertex_required_property, this );
+  mesh_set_get_edge_count( _tria_mesh, get_edge_count, this);
+  mesh_set_get_edge_vertices( _tria_mesh, get_edge_vertices, this );
+  mesh_set_get_triangle_count( _tria_mesh, get_triangle_count, this );
+  mesh_set_get_triangle_vertices( _tria_mesh, get_triangle_vertices, this );
+
+  // Create a tetra session
+  _session = tetra_session_new( _context );
+  if ( !_session ) MG_Error( "unable to create a new tetra session");
+
+  ret = tetra_set_interrupt_callback( _session, my_interrupt_callback, this );
+  if ( ret != STATUS_OK ) MG_Error("in tetra_set_interrupt_callback");
+
+}
+
+bool MG_Tetra_API::LibData::Compute()
+{
+  // Set surface mesh
+  status_t ret = tetra_set_surface_mesh( _session, _tria_mesh );
+  if ( ret != STATUS_OK ) MG_Error( "unable to set surface mesh");
+
+  // Set a sizemap
+  if ( !_nodeSize.empty() )
+  {
+    _sizemap = meshgems_sizemap_new( _tria_mesh, meshgems_sizemap_type_iso_mesh_vertex,
+                                     (void*) &get_vertex_weight, this );
+    if ( !_sizemap ) MG_Error("unable to create a new sizemap");
+
+    ret = tetra_set_sizemap( _session, _sizemap );
+    if ( ret != STATUS_OK ) MG_Error( "unable to set sizemap");
+  }
+
+  //////////////////////////////////////////////////////////////////////////////////////////
+  // const char* file  =  "/tmp/ghs3d_IN.mesh";
+  // mesh_write_mesh( _tria_mesh,file);
+  // std::cout << std::endl << std::endl << "Write " << file << std::endl << std::endl << std::endl;
+
+  ret = tetra_compute_mesh( _session );
+  if ( ret != STATUS_OK ) return false;
+
+  ret = tetra_get_mesh( _session, &_tetra_mesh);
+  if (ret != STATUS_OK) MG_Error( "unable to get resulting mesh");
+
+  //////////////////////////////////////////////////////////////////////////////////////////
+  // file  =  "/tmp/ghs3d_OUT.mesh";
+  // mesh_write_mesh( _tetra_mesh,file);
+  // std::cout << std::endl << std::endl << "Write " << file << std::endl << std::endl << std::endl;
+
+  return true;
+}
+
+
+#endif // ifdef USE_MG_LIBS
+
+
+//================================================================================
+/*!
+ * \brief Constructor
+ */
+//================================================================================
+
+MG_Tetra_API::MG_Tetra_API(volatile bool& cancelled_flag, double& progress)
+{
+#ifdef USE_MG_LIBS
+  _useLib = true;
+  _libData = new LibData( cancelled_flag, progress );
+  _libData->Init();
+#endif
+  if ( getenv("MG_TETRA_USE_EXE"))
+    _useLib = false;
+}
+
+//================================================================================
+/*!
+ * \brief Destructor
+ */
+//================================================================================
+
+MG_Tetra_API::~MG_Tetra_API()
+{
+#ifdef USE_MG_LIBS
+  delete _libData;
+  _libData = 0;
+#endif
+  std::set<int>::iterator id = _openFiles.begin();
+  for ( ; id != _openFiles.end(); ++id )
+    ::GmfCloseMesh( *id );
+  _openFiles.clear();
+}
+
+//================================================================================
+/*!
+ * \brief Return the way of MG usage
+ */
+//================================================================================
+
+bool MG_Tetra_API::IsLibrary()
+{
+  return _useLib;
+}
+
+//================================================================================
+/*!
+ * \brief Switch to usage of MG-Tetra executable
+ */
+//================================================================================
+
+void MG_Tetra_API::SetUseExecutable()
+{
+  _useLib = false;
+}
+
+//================================================================================
+/*!
+ * \brief Compute the tetra mesh
+ *  \param [in] cmdLine - a command to run mg_tetra.exe
+ *  \return bool - Ok or not
+ */
+//================================================================================
+
+bool MG_Tetra_API::Compute( const std::string& cmdLine, std::string& errStr )
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+
+    // split cmdLine
+    std::istringstream strm( cmdLine );
+    std::istream_iterator<std::string> sIt( strm ), sEnd;
+    std::vector< std::string > args( sIt, sEnd );
+
+    // set parameters
+    std::string param, value;
+    for ( size_t i = 1; i < args.size(); ++i )
+    {
+      // look for a param name; it starts from "-"
+      param = args[i];
+      if ( param.size() < 2 || param[0] != '-')
+        continue;
+      while ( param[0] == '-')
+        param = param.substr( 1 );
+
+      value = "";
+      while ( i+1 < args.size() && args[i+1][0] != '-' )
+      {
+        if ( !value.empty() ) value += " ";
+        value += args[++i];
+      }
+      if ( !_libData->SetParam( param, value ))
+        std::cout << "Warning: wrong param: '" << param <<"' = '" << value << "'" << std::endl;
+    }
+
+    // compute
+    return _libData->Compute();
+#endif
+  }
+
+  int err = system( cmdLine.c_str() ); // run
+
+  if ( err )
+    errStr = SMESH_Comment("system(mg-tetra.exe ...) command failed with error: ")
+      << strerror( errno );
+
+  GetLog(); // write a log file
+  _logFile = ""; // not to write it again
+
+  return !err;
+
+}
+
+//================================================================================
+/*!
+ * \brief Prepare for reading a mesh data
+ */
+//================================================================================
+
+int  MG_Tetra_API::GmfOpenMesh(const char* theFile, int rdOrWr, int * ver, int * dim)
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+    return 1;
+#endif
+  }
+  int id = ::GmfOpenMesh(theFile, rdOrWr, ver, dim );
+  _openFiles.insert( id );
+  return id;
+}
+
+//================================================================================
+/*!
+ * \brief Return nb of entities
+ */
+//================================================================================
+
+int MG_Tetra_API::GmfStatKwd( int iMesh, GmfKwdCod what )
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+    switch ( what )
+    {
+    case GmfSubDomainFromGeom: return _libData->ReadNbSubDomains();
+    case GmfVertices:          return _libData->ReadNbNodes();
+    case GmfEdges:             return _libData->ReadNbEdges();
+    case GmfTriangles:         return _libData->ReadNbTria();
+    case GmfQuadrilaterals:    return _libData->ReadNbQuads();
+    case GmfTetrahedra:        return _libData->ReadNbTetra();
+    case GmfHexahedra:         return _libData->ReadNbHexa();
+    default:                   return 0;
+    }
+    return 0;
+#endif
+  }
+  return ::GmfStatKwd( iMesh, what );
+}
+
+//================================================================================
+/*!
+ * \brief Prepare for reading some data
+ */
+//================================================================================
+
+void MG_Tetra_API::GmfGotoKwd( int iMesh, GmfKwdCod what )
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+    _libData->ResetCounter();
+    return;
+#endif
+  }
+  ::GmfGotoKwd( iMesh, what );
+}
+
+//================================================================================
+/*!
+ * \brief Return index of a domain identified by a triangle normal
+ *  \param [in] iMesh - mesh file index
+ *  \param [in] what - must be GmfSubDomainFromGeom
+ *  \param [out] nbNodes - nb nodes in a face
+ *  \param [out] faceInd - face index
+ *  \param [out] ori - face orientation
+ *  \param [out] domain - domain index
+ *  \param [in] dummy - an artificial param used to discriminate from GmfGetLin() reading
+ *              a triangle
+ */
+//================================================================================
+
+void MG_Tetra_API::GmfGetLin( int iMesh, GmfKwdCod what, int* nbNodes, int* faceInd, int* ori, int* domain, int dummy )
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+    _libData->ReadSubDomain( nbNodes, faceInd, ori, domain );
+    return;
+#endif
+  }
+  ::GmfGetLin( iMesh, what, nbNodes, faceInd, ori, domain );
+}
+
+//================================================================================
+/*!
+ * \brief Return coordinates of a next node
+ */
+//================================================================================
+
+void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what,
+                             double* x, double* y, double *z, int* domain )
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+    _libData->ReadNodeXYZ( x, y, z, domain );
+    return;
+#endif
+  }
+  ::GmfGetLin(iMesh, what, x, y, z, domain );
+}
+
+//================================================================================
+/*!
+ * \brief Return coordinates of a next node
+ */
+//================================================================================
+
+void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what,
+                             float* x, float* y, float *z, int* domain )
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+    double X,Y,Z;
+    _libData->ReadNodeXYZ( &X, &Y, &Z, domain );
+    *x = X;
+    *y = Y;
+    *z = Z;
+    return;
+#endif
+  }
+  ::GmfGetLin(iMesh, what, x, y, z, domain );
+}
+
+//================================================================================
+/*!
+ * \brief Return node index of a next corner
+ */
+//================================================================================
+
+void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what, int* node )
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+    node = 0;
+    return;
+#endif
+  }
+  ::GmfGetLin(iMesh, what, node );
+}
+
+//================================================================================
+/*!
+ * \brief Return node indices of a next edge
+ */
+//================================================================================
+
+void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what, int* node1, int* node2, int* domain )
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+    _libData->ReadEdgeNodes( node1, node2, domain );
+    return;
+#endif
+  }
+  ::GmfGetLin( iMesh, what, node1, node2, domain );
+}
+
+//================================================================================
+/*!
+ * \brief Return node indices of a next triangle
+ */
+//================================================================================
+
+void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what,
+                             int* node1, int* node2, int* node3, int* domain )
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+    _libData->ReadTriaNodes( node1, node2, node3, domain );
+    return;
+#endif
+  }
+  ::GmfGetLin(iMesh, what, node1, node2, node3, domain );
+}
+
+//================================================================================
+/*!
+ * \brief Return node indices of a next tetrahedron or quadrangle
+ */
+//================================================================================
+
+void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what,
+                             int* node1, int* node2, int* node3, int* node4, int* domain )
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+    if ( what == GmfQuadrilaterals )
+      _libData->ReadQuadNodes( node1, node2, node3, node4, domain );
+    else
+      _libData->ReadTetraNodes( node1, node2, node3, node4, domain );
+    return;
+#endif
+  }
+  ::GmfGetLin(iMesh, what, node1, node2, node3, node4, domain );
+}
+
+//================================================================================
+/*!
+ * \brief Return node indices of a next hexahedron
+ */
+//================================================================================
+
+void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what,
+                             int* node1, int* node2, int* node3, int* node4,
+                             int* node5, int* node6, int* node7, int* node8,
+                             int* domain )
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+    _libData->ReadHexaNodes( node1, node2, node3, node4,
+                             node5, node6, node7, node8, domain );
+    return;
+#endif
+  }
+  ::GmfGetLin(iMesh, what, node1, node2, node3, node4, node5, node6, node7, node8, domain );
+}
+
+//================================================================================
+/*!
+ * \brief Prepare for passing data to MeshGems
+ */
+//================================================================================
+
+int  MG_Tetra_API::GmfOpenMesh(const char* theFile, int rdOrWr, int ver, int dim)
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+    return 1;
+#endif
+  }
+  int id = ::GmfOpenMesh(theFile, rdOrWr, ver, dim);
+  _openFiles.insert( id );
+  return id;
+}
+
+//================================================================================
+/*!
+ * \brief Set number of entities
+ */
+//================================================================================
+
+void MG_Tetra_API::GmfSetKwd(int iMesh, GmfKwdCod what, int nb )
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+    switch ( what ) {
+    case GmfVertices:          _libData->SetNbVertices( nb ); break;
+    case GmfEdges:             _libData->SetNbEdges   ( nb ); break;
+    case GmfRequiredEdges:     _libData->SetNbReqEdges( nb ); break;
+    case GmfTriangles:         _libData->SetNbTria    ( nb ); break;
+    case GmfRequiredTriangles: _libData->SetNbReqTria ( nb ); break;
+    default:;
+    }
+    return;
+#endif
+  }
+  ::GmfSetKwd(iMesh, what, nb );
+}
+
+//================================================================================
+/*!
+ * \brief Add coordinates of a node
+ */
+//================================================================================
+
+void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what, double x, double y, double z, int domain)
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+    _libData->AddNode( x, y, z, domain );
+    return;
+#endif
+  }
+  ::GmfSetLin(iMesh, what, x, y, z, domain);
+}
+
+//================================================================================
+/*!
+ * \brief Set number of field entities
+ *  \param [in] iMesh - solution file index
+ *  \param [in] what - solution type
+ *  \param [in] nbNodes - nb of entities
+ *  \param [in] nbTypes - nb of data entries in each entity
+ *  \param [in] type - types of the data entries
+ *
+ * Used to prepare to storing size at nodes
+ */
+//================================================================================
+
+void MG_Tetra_API::GmfSetKwd(int iMesh, GmfKwdCod what, int nbNodes, int dummy, int type[] )
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+    if ( what == GmfSolAtVertices ) _libData->SetNbReqVertices( nbNodes );
+    return;
+#endif
+  }
+  ::GmfSetKwd(iMesh, what, nbNodes, dummy, type );
+}
+
+//================================================================================
+/*!
+ * \brief Add solution data
+ */
+//================================================================================
+
+void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what, double vals[])
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+    _libData->AddSizeAtNode( vals[0] );
+    return;
+#endif
+  }
+  ::GmfSetLin(iMesh, what, vals);
+}
+
+//================================================================================
+/*!
+ * \brief Add edge nodes
+ */
+//================================================================================
+
+void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what, int node1, int node2, int domain )
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+    _libData->AddEdgeNodes( node1, node2, domain );
+    return;
+#endif
+  }
+  ::GmfSetLin(iMesh, what, node1, node2, domain );
+}
+
+//================================================================================
+/*!
+ * \brief Add a 'required' flag
+ */
+//================================================================================
+
+void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what, int id )
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+    return;
+#endif
+  }
+  ::GmfSetLin(iMesh, what, id );
+}
+
+//================================================================================
+/*!
+ * \brief Add triangle nodes
+ */
+//================================================================================
+
+void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what, int node1, int node2, int node3, int domain )
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+    _libData->AddTriaNodes( node1, node2, node3, domain );
+    return;
+#endif
+  }
+  ::GmfSetLin(iMesh, what, node1, node2, node3, domain );
+}
+
+//================================================================================
+/*!
+ * \brief Close a file
+ */
+//================================================================================
+
+void MG_Tetra_API::GmfCloseMesh( int iMesh )
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+    return;
+#endif
+  }
+  ::GmfCloseMesh( iMesh );
+  _openFiles.erase( iMesh );
+}
+
+//================================================================================
+/*!
+ * \brief Return true if the log is not empty
+ */
+//================================================================================
+
+bool MG_Tetra_API::HasLog()
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+    return !_libData->GetErrors().empty();
+#endif
+  }
+  SMESH_File file( _logFile );
+  return file.size() > 0;
+}
+
+//================================================================================
+/*!
+ * \brief Return log contents
+ */
+//================================================================================
+
+std::string MG_Tetra_API::GetLog()
+{
+  if ( _useLib ) {
+#ifdef USE_MG_LIBS
+    const std::string& err = _libData->GetErrors();
+    if ( !_logFile.empty() && !err.empty() )
+    {
+      SMESH_File file( _logFile, /*openForReading=*/false );
+      file.openForWriting();
+      file.write( err.c_str(), err.size() );
+    }
+    return err;
+#endif
+  }
+  SMESH_File file( _logFile );
+  return file.getPos();
+}
diff --git a/src/GHS3DPlugin/MG_Tetra_API.hxx b/src/GHS3DPlugin/MG_Tetra_API.hxx
new file mode 100644 (file)
index 0000000..ee4ad30
--- /dev/null
@@ -0,0 +1,86 @@
+// Copyright (C) 2004-2016  CEA/DEN, EDF R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+
+#ifndef __MG_Tetra_IO_HXX__
+#define __MG_Tetra_IO_HXX__
+
+extern "C"
+{
+#include "libmesh5.h"
+}
+#include <string>
+#include <set>
+
+/*!
+ * \brief Class providing a transparent switch between MG_Tetra usage as
+ *        a library and as an executable. API of libmesh5 inherited.
+ */
+class MG_Tetra_API
+{
+public:
+
+  MG_Tetra_API( volatile bool& cancelled_flag, double& progress );
+  ~MG_Tetra_API();
+
+  bool IsLibrary();
+  bool IsExecutable() { return !IsLibrary(); }
+  void SetUseExecutable();
+
+  // IN to MESHGEMS
+  int  GmfOpenMesh(const char* theFile, int rdOrWr, int ver, int dim);
+  void GmfSetKwd(int iMesh, GmfKwdCod what, int nb );
+  void GmfSetLin(int iMesh, GmfKwdCod what, double x, double y, double z, int domain);
+  void GmfSetKwd(int iMesh, GmfKwdCod what, int nbNodes, int dummy, int type[] ); // sol type
+  void GmfSetLin(int iMesh, GmfKwdCod what, double vals[]); // sol
+  void GmfSetLin(int iMesh, GmfKwdCod what, int node1, int node2, int domain ); // edge
+  void GmfSetLin(int iMesh, GmfKwdCod what, int id ); // required
+  void GmfSetLin(int iMesh, GmfKwdCod what, int node1, int node2, int node3, int domain ); // tria
+
+  bool Compute( const std::string& cmdLine, std::string& errStr );
+
+  // OUT from MESHGEMS
+  int  GmfOpenMesh(const char* theFile, int rdOrWr, int * ver, int * dim);
+  int  GmfStatKwd( int iMesh, GmfKwdCod what );
+  void GmfGotoKwd( int iMesh, GmfKwdCod what );
+  void GmfGetLin( int iMesh, GmfKwdCod what, int* nbNodes, int* faceInd, int* ori, int* domain, int dummy );
+  void GmfGetLin(int iMesh, GmfKwdCod what, float* x, float* y, float *z, int* domain );
+  void GmfGetLin(int iMesh, GmfKwdCod what, double* x, double* y, double *z, int* domain );
+  void GmfGetLin(int iMesh, GmfKwdCod what, int* node );
+  void GmfGetLin(int iMesh, GmfKwdCod what, int* node1, int* node2, int* domain );
+  void GmfGetLin(int iMesh, GmfKwdCod what, int* node1, int* node2, int* node3, int* domain );
+  void GmfGetLin(int iMesh, GmfKwdCod what, int* node1, int* node2, int* node3, int* node4, int* domain );
+  void GmfGetLin(int iMesh, GmfKwdCod what, int* node1, int* node2, int* node3, int* node4, int* node5, int* node6, int* node7, int* node8, int* domain );
+  void GmfCloseMesh( int iMesh );
+
+  void SetLogFile( const std::string& logFileName ) { _logFile = logFileName; }
+  bool HasLog();
+  std::string GetLog();
+
+
+  struct LibData;
+
+private:
+
+  bool          _useLib;
+  LibData*      _libData;
+  std::set<int> _openFiles;
+  std::string   _logFile;
+};
+
+#endif