Salome HOME
updated copyright message
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_Mesher.cxx
index c87731e4da743dd82ff7059e3f3ab029f093500c..331192c113482c600fb2dc31688659a3d2c374e0 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright (C) 2007-2019  CEA/DEN, EDF R&D, OPEN CASCADE
+// Copyright (C) 2007-2023  CEA, EDF, OPEN CASCADE
 //
 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
@@ -76,6 +76,7 @@
 #include <TopoDS.hxx>
 #include <TopoDS_Compound.hxx>
 
+#include <Basics_OCCTVersion.hxx>
 // Netgen include files
 #ifndef OCCGEOMETRY
 #define OCCGEOMETRY
 #include <meshing.hpp>
 //#include <ngexception.hpp>
 namespace netgen {
-#ifdef NETGEN_V5
-  extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, MeshingParameters&, int, int);
-#else
-  extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
-#endif
-  //extern void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh);
 
   NETGENPLUGIN_DLL_HEADER
   extern MeshingParameters mparam;
@@ -142,6 +137,8 @@ std::set<int> ShapesWithControlPoints; // <-- allows calling SetLocalSize() seve
 
 namespace
 {
+  inline void NOOP_Deleter(void *) { ; }
+
   //=============================================================================
   /*!
    *  Link - a pair of integer numbers
@@ -205,7 +202,7 @@ namespace
 
   list< TopoDS_Edge > getConnectedEdges( const TopoDS_Edge&                 edge,
                                          const TopoDS_Face&                 face,
-                                         const set< SMESH_subMesh* > &      computedSM,
+                                         const set< SMESH_subMesh* > &      /*computedSM*/,
                                          const SMESH_MesherHelper&          helper,
                                          map< SMESH_subMesh*, set< int > >& addedEdgeSM2Faces)
   {
@@ -249,7 +246,7 @@ namespace
       SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItFwd );
 
       bool connected = TopExp::CommonVertex( *ePrev, *eItFwd, vCommon );
-      bool computed  = sm->IsMeshComputed();
+      bool computed  = !sm->IsEmpty();
       bool added     = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
       bool doubled   = !eAdded.Add( *eItFwd );
       bool orientOK  = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
@@ -271,7 +268,7 @@ namespace
       SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItBack );
 
       bool connected = TopExp::CommonVertex( *ePrev, *eItBack, vCommon );
-      bool computed  = sm->IsMeshComputed();
+      bool computed  = !sm->IsEmpty();
       bool added     = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
       bool doubled   = !eAdded.Add( *eItBack );
       bool orientOK  = (( ePrev  ->Orientation() < TopAbs_INTERNAL ) ==
@@ -319,7 +316,7 @@ namespace
           OCC_CATCH_SIGNALS;
           BRepMesh_IncrementalMesh e(shape, 0.01, true);
         }
-        catch (Standard_Failure)
+        catch (Standard_Failure&)
         {
         }
   //       updated.erase( triangulation.operator->() );
@@ -384,7 +381,7 @@ namespace
 
   //================================================================================
   /*!
-   * \brief Restrict size of elements on the given edge 
+   * \brief Restrict size of elements on the given edge
    */
   //================================================================================
 
@@ -603,8 +600,22 @@ void NETGENPlugin_Mesher::SetDefaultParameters()
   _fineness               = NETGENPlugin_Hypothesis::GetDefaultFineness();
   mparams.uselocalh       = NETGENPlugin_Hypothesis::GetDefaultSurfaceCurvature();
   netgen::merge_solids    = NETGENPlugin_Hypothesis::GetDefaultFuseEdges();
+  // Unused argument but set 0 to initialise it
+  mparams.elementorder = 0;
+
+#ifdef NETGEN_V6
+
+  mparams.nthreads = NETGENPlugin_Hypothesis::GetDefaultNbThreads();
+
+  if ( getenv( "SALOME_NETGEN_DISABLE_MULTITHREADING" ))
+  {
+    mparams.nthreads = 1;
+    mparams.parallel_meshing = false;
+  }
+#endif
 }
 
+
 //=============================================================================
 /*!
  * Pass parameters to NETGEN
@@ -644,8 +655,14 @@ void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
     mparams.checkchartboundary = hyp->GetCheckChartBoundary();
     _simpleHyp                 = NULL;
     // mesh size file
+#ifdef NETGEN_V6
+    // std::string
+    mparams.meshsizefilename = hyp->GetMeshSizeFile();
+    mparams.nthreads = hyp->GetNbThreads();
+#else
+    // const char*
     mparams.meshsizefilename= hyp->GetMeshSizeFile().empty() ? 0 : hyp->GetMeshSizeFile().c_str();
-
+#endif
     const NETGENPlugin_Hypothesis::TLocalSize& localSizes = hyp->GetLocalSizesAndEntries();
     if ( !localSizes.empty() )
     {
@@ -657,7 +674,7 @@ void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
         double        val = (*it).second;
         // --
         GEOM::GEOM_Object_var aGeomObj;
-        SALOMEDS::SObject_var aSObj = SMESH_Gen_i::getStudyServant()->FindObjectID( entry.c_str() );
+        SALOMEDS::SObject_var aSObj = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->FindObjectID( entry.c_str() );
         if ( !aSObj->_is_nil() ) {
           CORBA::Object_var obj = aSObj->GetObject();
           aGeomObj = GEOM::GEOM_Object::_narrow(obj);
@@ -668,6 +685,12 @@ void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
       }
     }
   }
+
+#ifdef NETGEN_V6
+
+  netgen::mparam.closeedgefac = 2;
+
+#endif
 }
 
 //=============================================================================
@@ -730,7 +753,11 @@ void NETGENPlugin_Mesher::SetLocalSize( netgen::OCCGeometry& occgeo,
     int faceNgID = occgeo.fmap.FindIndex(shape);
     if ( faceNgID >= 1 )
     {
+#ifdef NETGEN_V6
+      occgeo.SetFaceMaxH(faceNgID-1, val, netgen::mparam);
+#else
       occgeo.SetFaceMaxH(faceNgID, val);
+#endif
       for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
         setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, ngMesh );
     }
@@ -795,7 +822,11 @@ void NETGENPlugin_Mesher::SetLocalSizeForChordalError( netgen::OCCGeometry& occg
       surfProp.SetParameters( 0, 0 );
       double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
       double    size = elemSizeForChordalError( _chordalError, 1 / maxCurv );
+#ifdef NETGEN_V6
+      occgeo.SetFaceMaxH( i-1, size * sizeCoef, netgen::mparam );
+#else
       occgeo.SetFaceMaxH( i, size * sizeCoef );
+#endif
       // limit size one edges
       TopTools_MapOfShape edgeMap;
       for ( TopExp_Explorer eExp( face, TopAbs_EDGE ); eExp.More(); eExp.Next() )
@@ -846,12 +877,21 @@ void NETGENPlugin_Mesher::SetLocalSizeForChordalError( netgen::OCCGeometry& occg
       {
         Standard_Integer n1,n2,n3;
         triangulation->Triangles()(i).Get( n1,n2,n3 );
+#if OCC_VERSION_LARGE < 0x07060000
         p [0] = triangulation->Nodes()(n1).Transformed(loc).XYZ();
         p [1] = triangulation->Nodes()(n2).Transformed(loc).XYZ();
         p [2] = triangulation->Nodes()(n3).Transformed(loc).XYZ();
         uv[0] = triangulation->UVNodes()(n1).XY();
         uv[1] = triangulation->UVNodes()(n2).XY();
         uv[2] = triangulation->UVNodes()(n3).XY();
+#else
+        p[0] = triangulation->Node(n1).Transformed(loc).XYZ();
+        p[1] = triangulation->Node(n2).Transformed(loc).XYZ();
+        p[2] = triangulation->Node(n3).Transformed(loc).XYZ();
+        uv[0] = triangulation->UVNode(n1).XY();
+        uv[1] = triangulation->UVNode(n2).XY();
+        uv[2] = triangulation->UVNode(n3).XY();
+#endif
         surfProp.SetParameters( uv[0].X(), uv[0].Y() );
         if ( !surfProp.IsCurvatureDefined() )
           break;
@@ -1009,7 +1049,14 @@ double NETGENPlugin_Mesher::GetDefaultMinSize(const TopoDS_Shape& geom,
       BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
     if ( triangulation.IsNull() ) continue;
     const double fTol = BRep_Tool::Tolerance( TopoDS::Face( fExp.Current() ));
-    const TColgp_Array1OfPnt&   points = triangulation->Nodes();
+#if OCC_VERSION_HEX < 0x070600
+    const TColgp_Array1OfPnt& points = triangulation->Nodes();
+#else
+    auto points = [&triangulation](Standard_Integer index) {
+      return triangulation->Node(index);
+    };
+#endif
+
     const Poly_Array1OfTriangle& trias = triangulation->Triangles();
     for ( int iT = trias.Lower(); iT <= trias.Upper(); ++iT )
     {
@@ -1153,7 +1200,7 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry&           occgeom,
         const vector<UVPtStruct>& points = fSide.GetUVPtStruct();
         if ( points.empty() )
           return false; // invalid node params?
-        int i, nbSeg = fSide.NbSegments();
+        smIdType i, nbSeg = fSide.NbSegments();
 
         // remember EDGEs of fSide to treat only once
         for ( int iE = 0; iE < fSide.NbEdges(); ++iE )
@@ -1288,11 +1335,11 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry&           occgeom,
           if ( id ) solidSMDSIDs[ bool( solidSMDSIDs[0] )] = meshDS->ShapeToIndex( *solid );
         }
       }
+      bool isShrunk = true;
       if ( proxyMesh && proxyMesh->GetProxySubMesh( geomFace ))
       {
         // if a proxy sub-mesh contains temporary faces, then these faces
         // should be used to mesh only one SOLID
-        bool hasTmp = false;
         smDS = proxyMesh->GetSubMesh( geomFace );
         SMDS_ElemIteratorPtr faces = smDS->GetElements();
         while ( faces->more() )
@@ -1300,7 +1347,7 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry&           occgeom,
           const SMDS_MeshElement* f = faces->next();
           if ( proxyMesh->IsTemporary( f ))
           {
-            hasTmp = true;
+            isShrunk = false;
             if ( solidSMDSIDs[1] && proxyMesh->HasPrismsOnTwoSides( meshDS->MeshElements( geomFace )))
               break;
             else
@@ -1319,7 +1366,7 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry&           occgeom,
           }
         }
         const int fID = occgeom.fmap.FindIndex( geomFace );
-        if ( !hasTmp ) // shrunk mesh
+        if ( isShrunk ) // shrunk mesh
         {
           // move netgen points according to moved nodes
           SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
@@ -1371,7 +1418,7 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry&           occgeom,
       {
         solidSMDSIDs[1] = 0;
       }
-      const bool hasVLOn2Sides = ( solidSMDSIDs[1] > 0 );
+      const bool hasVLOn2Sides = ( solidSMDSIDs[1] > 0 && !isShrunk );
 
       // Add ng face descriptors of meshed faces
       faceNgID++;
@@ -1431,7 +1478,7 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry&           occgeom,
         const SMDS_MeshElement* f = faces->next();
         if ( f->NbNodes() % 3 != 0 ) // not triangle
         {
-          PShapeIteratorPtr solidIt=helper.GetAncestors(geomFace,*sm->GetFather(),TopAbs_SOLID);
+          PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace,*sm->GetFather(),TopAbs_SOLID);
           if ( const TopoDS_Shape * solid = solidIt->next() )
             sm = _mesh->GetSubMesh( *solid );
           SMESH_BadInputElements* badElems =
@@ -1548,7 +1595,7 @@ void NETGENPlugin_Mesher::FixIntFaces(const netgen::OCCGeometry& occgeom,
                                       NETGENPlugin_Internals&    internalShapes)
 {
   SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
-  
+
   // find ng indices of internal faces
   set<int> ngFaceIds;
   for ( int ngFaceID = 1; ngFaceID <= occgeom.fmap.Extent(); ++ngFaceID )
@@ -1708,7 +1755,7 @@ namespace
     double dist3D = surf->Value( uv1.X(), uv1.Y() ).Distance( surf->Value( uv2.X(), uv2.Y() ));
     if ( stopHandler == 0 ) // stop recursion
       return dist3D;
-    
+
     // start recursion if necessary
     double dist2D = SMESH_MesherHelper::ApplyIn2D(surf, uv1, uv2, gp_XY_Subtracted, 0).Modulus();
     if ( fabs( dist3D - dist2D ) < dist2D * 1e-10 )
@@ -2178,7 +2225,7 @@ void NETGENPlugin_Mesher::AddIntVerticesInSolids(const netgen::OCCGeometry&
  *  \param wires - data of nodes on FACE boundary
  *  \param helper - mesher helper holding the FACE
  *  \param nodeVec - vector of nodes in which node index == netgen ID
- *  \retval SMESH_ComputeErrorPtr - error description 
+ *  \retval SMESH_ComputeErrorPtr - error description
  */
 //================================================================================
 
@@ -2193,7 +2240,7 @@ NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh&                    ngMesh,
   // ----------------------------
   // Check wires and count nodes
   // ----------------------------
-  int nbNodes = 0;
+  smIdType nbNodes = 0;
   for ( size_t iW = 0; iW < wires.size(); ++iW )
   {
     StdMeshers_FaceSidePtr wire = wires[ iW ];
@@ -2250,7 +2297,7 @@ NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh&                    ngMesh,
   {
     StdMeshers_FaceSidePtr       wire = wires[ iW ];
     const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
-    const int              nbSegments = wire->NbPoints() - 1;
+    const smIdType         nbSegments = wire->NbPoints() - 1;
 
     // assure the 1st node to be in node2ngID, which is needed to correctly
     // "close chain of segments" (see below) in case if the 1st node is not
@@ -2342,8 +2389,8 @@ NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh&                    ngMesh,
         SMESH_TNodeXYZ np1( n ), np2( uvPtVec[ i+1 ].node );
         // get an average size of adjacent segments to avoid sharp change of
         // element size (regression on issue 0020452, note 0010898)
-        int   iPrev = SMESH_MesherHelper::WrapIndex( i-1, nbSegments );
-        int   iNext = SMESH_MesherHelper::WrapIndex( i+1, nbSegments );
+        int   iPrev = SMESH_MesherHelper::WrapIndex( i-1, (int) nbSegments );
+        int   iNext = SMESH_MesherHelper::WrapIndex( i+1, (int) nbSegments );
         double sumH = segLen[ iPrev ] + segLen[ i ] + segLen[ iNext ];
         int   nbSeg = ( int( segLen[ iPrev ] > sumH / 100.)  +
                         int( segLen[ i     ] > sumH / 100.)  +
@@ -2456,14 +2503,14 @@ int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry&          occgeo,
   if ( quadHelper && !quadHelper->GetIsQuadratic() && quadHelper->GetTLinkNodeMap().empty() )
     quadHelper = 0;
 
-  int i, nbInitNod = initState._nbNodes;
+  int ngID, nbInitNod = initState._nbNodes;
   if ( initState._elementsRemoved )
   {
     // PAL23427. Update nodeVec to track removal of netgen free points as a result
     // of removal of faces in FillNgMesh() in the case of a shrunk sub-mesh
-    int ngID, nodeVecSize = nodeVec.size();
+    size_t i, nodeVecSize = nodeVec.size();
     const double eps = std::numeric_limits<double>::min();
-    for ( ngID = i = 1; i < nodeVecSize; ++ngID, ++i )
+    for ( i = ngID = 1; i < nodeVecSize; ++ngID, ++i )
     {
       gp_Pnt ngPnt( NGPOINT_COORDS( ngMesh.Point( ngID )));
       gp_Pnt node ( SMESH_NodeXYZ (nodeVec_ACCESS(i) ));
@@ -2485,7 +2532,7 @@ int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry&          occgeo,
 
   if ( nbNod > nbInitNod )
     nodeVec.resize( nbNod + 1 );
-  for ( i = nbInitNod+1; i <= nbNod; ++i )
+  for ( int i = nbInitNod+1; i <= nbNod; ++i )
   {
     const netgen::MeshPoint& ngPoint = ngMesh.Point(i);
     SMDS_MeshNode* node = NULL;
@@ -2520,7 +2567,7 @@ int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry&          occgeo,
   // -------------------------------------------
 
   int nbInitSeg = initState._nbSegments;
-  for (i = nbInitSeg+1; i <= nbSeg; ++i )
+  for ( int i = nbInitSeg+1; i <= nbSeg; ++i )
   {
     const netgen::Segment& seg = ngMesh.LineSegment(i);
     TopoDS_Edge aEdge;
@@ -2602,7 +2649,7 @@ int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry&          occgeo,
     ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(quadFaceID, /*solid1=*/0, /*solid2=*/0, 0));
 
   vector<const SMDS_MeshNode*> nodes;
-  for (i = nbInitFac+1; i <= nbFac; ++i )
+  for ( int i = nbInitFac+1; i <= nbFac; ++i )
   {
     const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
     const int        aGeomFaceInd = elem.GetIndex();
@@ -2683,9 +2730,9 @@ int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry&          occgeo,
   // Create tetrahedra
   // ------------------
 
-  for ( i = 1; i <= nbVol; ++i )
+  for ( int i = 1; i <= nbVol; ++i )
   {
-    const netgen::Element& elem = ngMesh.VolumeElement(i);      
+    const netgen::Element& elem = ngMesh.VolumeElement(i);
     int aSolidInd = elem.GetIndex();
     TopoDS_Solid aSolid;
     if ( aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent() )
@@ -2878,7 +2925,7 @@ bool NETGENPlugin_Mesher::Compute()
 
   // vector of nodes in which node index == netgen ID
   vector< const SMDS_MeshNode* > nodeVec;
-  
+
   {
     // ----------------
     // compute 1D mesh
@@ -2906,19 +2953,14 @@ bool NETGENPlugin_Mesher::Compute()
     occgeo.face_maxh = mparams.maxh;
 
     // Let netgen create _ngMesh and calculate element size on not meshed shapes
-#ifndef NETGEN_V5
-    char *optstr = 0;
-#endif
     int startWith = netgen::MESHCONST_ANALYSE;
     int endWith   = netgen::MESHCONST_ANALYSE;
     try
     {
       OCC_CATCH_SIGNALS;
-#ifdef NETGEN_V5
-      err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
-#else
-      err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
-#endif
+
+      err = ngLib.GenerateMesh(occgeo, startWith, endWith, _ngMesh);
+
       if(netgen::multithread.terminate)
         return false;
 
@@ -2931,7 +2973,12 @@ bool NETGENPlugin_Mesher::Compute()
     catch (netgen::NgException & ex)
     {
       comment << text(ex);
-      if ( mparams.meshsizefilename )
+#ifdef NETGEN_V6
+      bool hasSizeFile = !mparams.meshsizefilename.empty();
+#else
+      bool hasSizeFile = mparams.meshsizefilename;
+#endif
+      if ( hasSizeFile )
         throw SMESH_ComputeError(COMPERR_BAD_PARMETERS, comment );
     }
     err = 0; //- MESHCONST_ANALYSE isn't so important step
@@ -2948,7 +2995,7 @@ bool NETGENPlugin_Mesher::Compute()
     {
       // Pass 1D simple parameters to NETGEN
       // --------------------------------
-      int      nbSeg = _simpleHyp->GetNumberOfSegments();
+      double nbSeg   = (double) _simpleHyp->GetNumberOfSegments();
       double segSize = _simpleHyp->GetLocalLength();
       for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
       {
@@ -2984,12 +3031,9 @@ bool NETGENPlugin_Mesher::Compute()
         //OCCSetLocalMeshSize(intOccgeo, *_ngMesh); it deletes _ngMesh->localH
 
         // let netgen create a temporary mesh
-#ifdef NETGEN_V5
-        netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
-#else
-        netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
-#endif
-        if(netgen::multithread.terminate)
+        ngLib.GenerateMesh(intOccgeo, startWith, endWith, tmpNgMesh);
+
+        if ( netgen::multithread.terminate )
           return false;
 
         // copy LocalH from the main to temporary mesh
@@ -2997,11 +3041,8 @@ bool NETGENPlugin_Mesher::Compute()
 
         // compute mesh on internal edges
         startWith = endWith = netgen::MESHCONST_MESHEDGES;
-#ifdef NETGEN_V5
-        err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
-#else
-        err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
-#endif
+        err = ngLib.GenerateMesh(intOccgeo, startWith, endWith, tmpNgMesh);
+
         comment << text(err);
       }
       catch (Standard_Failure& ex)
@@ -3034,12 +3075,10 @@ bool NETGENPlugin_Mesher::Compute()
       try
       {
         OCC_CATCH_SIGNALS;
-#ifdef NETGEN_V5
-        err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
-#else
-        err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
-#endif
-        if(netgen::multithread.terminate)
+
+        err = ngLib.GenerateMesh(occgeo, startWith, endWith);
+
+        if ( netgen::multithread.terminate )
           return false;
 
         comment << text(err);
@@ -3148,12 +3187,10 @@ bool NETGENPlugin_Mesher::Compute()
       try
       {
         OCC_CATCH_SIGNALS;
-#ifdef NETGEN_V5
-        err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
-#else
-        err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
-#endif
-        if(netgen::multithread.terminate)
+
+        err = ngLib.GenerateMesh(occgeo, startWith, endWith);
+
+        if ( netgen::multithread.terminate )
           return false;
 
         comment << text (err);
@@ -3163,7 +3200,7 @@ bool NETGENPlugin_Mesher::Compute()
         comment << text(ex);
         //err = 1; -- try to make volumes anyway
       }
-      catch (netgen::NgException exc)
+      catch (netgen::NgException& exc)
       {
         comment << text(exc);
         //err = 1; -- try to make volumes anyway
@@ -3185,7 +3222,7 @@ bool NETGENPlugin_Mesher::Compute()
       FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
 
       // compute prismatic boundary volumes
-      int nbQuad = _mesh->NbQuadrangles();
+      smIdType nbQuad = _mesh->NbQuadrangles();
       SMESH_ProxyMesh::Ptr viscousMesh;
       if ( _viscousLayersHyp )
       {
@@ -3229,7 +3266,7 @@ bool NETGENPlugin_Mesher::Compute()
       // fill _ngMesh with faces of sub-meshes
       err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_2D ], &quadHelper));
       initState = NETGENPlugin_ngMeshInfo(_ngMesh, /*checkRemovedElems=*/true);
-      // toPython( _ngMesh );
+      // toPython( _ngMesh )
     }
     if (!err && _isVolume)
     {
@@ -3249,11 +3286,7 @@ bool NETGENPlugin_Mesher::Compute()
         }
         _ngMesh->SetGlobalH (mparams.maxh);
         mparams.grading = 0.4;
-#ifdef NETGEN_V5
-        _ngMesh->CalcLocalH(mparams.grading);
-#else
-        _ngMesh->CalcLocalH();
-#endif
+        ngLib.CalcLocalH( ngLib._ngMesh );
       }
       // Care of vertices internal in solids and internal faces (issue 0020676)
       if ( internals.hasInternalVertexInSolid() || internals.hasInternalFaces() )
@@ -3272,12 +3305,10 @@ bool NETGENPlugin_Mesher::Compute()
       try
       {
         OCC_CATCH_SIGNALS;
-#ifdef NETGEN_V5
-        err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
-#else
-        err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
-#endif
-        if(netgen::multithread.terminate)
+
+        err = ngLib.GenerateMesh(occgeo, startWith, endWith);
+
+        if ( netgen::multithread.terminate )
           return false;
 
         if ( comment.empty() ) // do not overwrite a previous error
@@ -3289,7 +3320,7 @@ bool NETGENPlugin_Mesher::Compute()
           comment << text(ex);
         err = 1;
       }
-      catch (netgen::NgException exc)
+      catch (netgen::NgException& exc)
       {
         if ( comment.empty() ) // do not overwrite a previous error
           comment << text(exc);
@@ -3304,12 +3335,10 @@ bool NETGENPlugin_Mesher::Compute()
         try
         {
           OCC_CATCH_SIGNALS;
-#ifdef NETGEN_V5
-          err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
-#else
-          err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
-#endif
-          if(netgen::multithread.terminate)
+
+          err = ngLib.GenerateMesh(occgeo, startWith, endWith);
+
+          if ( netgen::multithread.terminate )
             return false;
 
           if ( comment.empty() ) // do not overwrite a previous error
@@ -3320,7 +3349,7 @@ bool NETGENPlugin_Mesher::Compute()
           if ( comment.empty() ) // do not overwrite a previous error
             comment << text(ex);
         }
-        catch (netgen::NgException exc)
+        catch (netgen::NgException& exc)
         {
           if ( comment.empty() ) // do not overwrite a previous error
             comment << text(exc);
@@ -3347,8 +3376,11 @@ bool NETGENPlugin_Mesher::Compute()
           _ngMesh->Compress();
         }
         // convert to quadratic
-        netgen::OCCRefinementSurfaces ref (occgeo);
-        ref.MakeSecondOrder (*_ngMesh);
+#ifdef NETGEN_V6
+        occgeo.GetRefinement().MakeSecondOrder(*_ngMesh);
+#else
+        netgen::OCCRefinementSurfaces(occgeo).MakeSecondOrder(*_ngMesh);
+#endif
 
         // care of elements already loaded to SMESH
         // if ( initState._nbSegments > 0 )
@@ -3361,7 +3393,7 @@ bool NETGENPlugin_Mesher::Compute()
         if ( comment.empty() ) // do not overwrite a previous error
           comment << "Exception in netgen at passing to 2nd order ";
       }
-      catch (netgen::NgException exc)
+      catch (netgen::NgException& exc)
       {
         if ( comment.empty() ) // do not overwrite a previous error
           comment << exc.What();
@@ -3448,9 +3480,9 @@ bool NETGENPlugin_Mesher::Compute()
           bool smComputed = nbVol && !sm->IsEmpty();
           if ( smComputed && internals.hasInternalVertexInSolid( sm->GetId() ))
           {
-            int nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size();
+            size_t nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size();
             SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
-            smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > nbIntV );
+            smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > (smIdType) nbIntV );
           }
           SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
           if ( !smComputed && ( !smError || smError->IsOK() ))
@@ -3499,7 +3531,7 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
   const int hugeNb = std::numeric_limits<int>::max() / 100;
 
   // ----------------
-  // evaluate 1D 
+  // evaluate 1D
   // ----------------
   // pass 1D simple parameters to NETGEN
   if ( _simpleHyp )
@@ -3524,16 +3556,9 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
   // let netgen create _ngMesh and calculate element size on not meshed shapes
   NETGENPlugin_NetgenLibWrapper ngLib;
   netgen::Mesh *ngMesh = NULL;
-#ifndef NETGEN_V5
-  char *optstr = 0;
-#endif
   int startWith = netgen::MESHCONST_ANALYSE;
   int endWith   = netgen::MESHCONST_MESHEDGES;
-#ifdef NETGEN_V5
-  int err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
-#else
-  int err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
-#endif
+  int err = ngLib.GenerateMesh(occgeo, startWith, endWith, ngMesh);
 
   if(netgen::multithread.terminate)
     return false;
@@ -3565,7 +3590,7 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
   // }
   // calculate total nb of segments and length of edges
   double fullLen = 0.0;
-  int fullNbSeg = 0;
+  smIdType fullNbSeg = 0;
   int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge;
   TopTools_DataMapOfShapeInteger Edge2NbSeg;
   for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next())
@@ -3577,7 +3602,7 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
     double aLen = SMESH_Algo::EdgeLength(E);
     fullLen += aLen;
 
-    vector<int>& aVec = aResMap[_mesh->GetSubMesh(E)];
+    vector<smIdType>& aVec = aResMap[_mesh->GetSubMesh(E)];
     if ( aVec.empty() )
       aVec.resize( SMDSEntity_Last, 0);
     else
@@ -3594,7 +3619,7 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
     int aGeomEdgeInd = seg.epgeominfo[0].edgenr;
     if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
     {
-      vector<int>& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))];
+      vector<smIdType>& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))];
       aVec[ entity ]++;
     }
   }
@@ -3602,18 +3627,18 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
   TopTools_DataMapIteratorOfDataMapOfShapeInteger Edge2NbSegIt(Edge2NbSeg);
   for (; Edge2NbSegIt.More(); Edge2NbSegIt.Next())
   {
-    vector<int>& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())];
+    vector<smIdType>& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())];
     if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 )
       aVec[SMDSEntity_Node] = mparams.secondorder > 0  ? 2*aVec[ entity ]-1 : aVec[ entity ]-1;
 
     fullNbSeg += aVec[ entity ];
-    Edge2NbSeg( Edge2NbSegIt.Key() ) = aVec[ entity ];
+    Edge2NbSeg( Edge2NbSegIt.Key() ) = (int) aVec[ entity ];
   }
   if ( fullNbSeg == 0 )
     return false;
 
   // ----------------
-  // evaluate 2D 
+  // evaluate 2D
   // ----------------
   if ( _simpleHyp ) {
     if ( double area = _simpleHyp->GetMaxElementArea() ) {
@@ -3623,12 +3648,12 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
     }
     else {
       // length from edges
-      mparams.maxh = fullLen/fullNbSeg;
+      mparams.maxh = fullLen / double( fullNbSeg );
       mparams.grading = 0.2; // slow size growth
     }
   }
   mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
-  mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
+  mparams.maxh = min( mparams.maxh, fullLen / double( fullNbSeg ) * (1. + mparams.grading));
 
   for (TopExp_Explorer exp(_shape, TopAbs_FACE); exp.More(); exp.Next())
   {
@@ -3649,7 +3674,7 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
     int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.)));
     int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
 
-    vector<int> aVec(SMDSEntity_Last, 0);
+    vector<smIdType> aVec(SMDSEntity_Last, 0);
     if( mparams.secondorder > 0 ) {
       int nb1d_in = (nbFaces*3 - nb1d) / 2;
       aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
@@ -3679,7 +3704,7 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
         // using previous length from faces
       }
       mparams.grading = 0.4;
-      mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
+      mparams.maxh = min( mparams.maxh, fullLen / double( fullNbSeg ) * (1. + mparams.grading));
     }
     GProp_GProps G;
     BRepGProp::VolumeProperties(_shape,G);
@@ -3688,7 +3713,7 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
     tooManyElems = tooManyElems || ( aVolume/hugeNb > tetrVol );
     int nbVols = tooManyElems ? hugeNb : int(aVolume/tetrVol);
     int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
-    vector<int> aVec(SMDSEntity_Last, 0 );
+    vector<smIdType> aVec(SMDSEntity_Last, 0 );
     if ( tooManyElems ) // avoid FPE
     {
       aVec[SMDSEntity_Node] = hugeNb;
@@ -3712,7 +3737,7 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
   return true;
 }
 
-double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* holder,
+double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* /*holder*/,
                                         const int *       algoProgressTic,
                                         const double *    algoProgress) const
 {
@@ -3800,8 +3825,8 @@ NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
   vector<int> two(2);
   vector<int> three1(3), three2(3);
   const char* badEdgeStr = " multiple times in surface mesh";
-  const int   badEdgeStrLen = strlen( badEdgeStr );
-  const int   nbNodes = nodeVec.size();
+  const int   badEdgeStrLen = (int) strlen( badEdgeStr );
+  const int   nbNodes = (int) nodeVec.size();
 
   while( !file.eof() )
   {
@@ -3811,13 +3836,13 @@ NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
          two[0] < nbNodes  &&  two[1] < nbNodes )
     {
       err->myBadElements.push_back( new SMDS_LinearEdge( nodeVec[ two[0]], nodeVec[ two[1]] ));
-      file += badEdgeStrLen;
+      file += (int) badEdgeStrLen;
     }
     else if ( strncmp( file, "Intersecting: ", 14 ) == 0 )
     {
-// Intersecting: 
+// Intersecting:
 // openelement 18 with open element 126
-// 41  36  38  
+// 41  36  38
 // 69  70  72
       file.getLine();
       const char* pos = file;
@@ -3827,7 +3852,7 @@ NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
       ok = ok && file.getInts( three2 );
       for ( int i = 0; ok && i < 3; ++i )
         ok = ( three1[i] < nbNodes && nodeVec[ three1[i]]);
-      for ( int i = 0; ok && i < 3; ++i ) 
+      for ( int i = 0; ok && i < 3; ++i )
         ok = ( three2[i] < nbNodes && nodeVec[ three2[i]]);
       if ( ok )
       {
@@ -3878,8 +3903,63 @@ void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh )
           << "mesh = smesh.Mesh()" << std::endl << std::endl;
 
   using namespace netgen;
+
+#ifdef NETGEN_V6
+
+  for ( int i = 1; i <= ngMesh->GetNP(); i++)
+  {
+    const Point3d & p = ngMesh->Point(i);
+    outfile << "mesh.AddNode( ";
+    outfile << p.X() << ", ";
+    outfile << p.Y() << ", ";
+    outfile << p.Z() << ") ## "<< i << std::endl;
+  }
+
+  int nbDom = ngMesh->GetNDomains();
+  for ( int i = 0; i < nbDom; ++i )
+    outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< std::endl;
+
+  int nbDel = 0;
+  for (int i = 1; i <= ngMesh->GetNSE(); i++)
+  {
+    outfile << "mesh.AddFace([ ";
+    Element2d sel = ngMesh->SurfaceElement(i);
+    for (int j = 1; j <= sel.GetNP(); j++)
+      outfile << sel.PNum(j) << ( j < sel.GetNP() ? ", " : " ])");
+    if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
+    outfile << std::endl;
+    nbDel += sel.IsDeleted();
+
+    if (sel.GetIndex())
+    {
+      if ( int dom1 = ngMesh->GetFaceDescriptor(sel.GetIndex ()).DomainIn())
+        outfile << "grp"<< dom1 <<".Add([ " << i - nbDel << " ])" << std::endl;
+      if ( int dom2 = ngMesh->GetFaceDescriptor(sel.GetIndex ()).DomainOut())
+        outfile << "grp"<< dom2 <<".Add([ " << i - nbDel << " ])" << std::endl;
+    }
+  }
+
+  for (int i = 1; i <= ngMesh->GetNE(); i++)
+  {
+    Element el = ngMesh->VolumeElement(i);
+    outfile << "mesh.AddVolume([ ";
+    for (int j = 1; j <= el.GetNP(); j++)
+      outfile << el.PNum(j) << ( j < el.GetNP() ? ", " : " ])");
+    outfile << std::endl;
+  }
+
+  for (int i = 1; i <= ngMesh->GetNSeg(); i++)
+  {
+    const Segment & seg = ngMesh->LineSegment (i);
+    outfile << "mesh.AddEdge([ "
+            << seg[0]+1 << ", "
+            << seg[1]+1 << " ])" << std::endl;
+  }
+
+#else  //////// V 5
+
   PointIndex pi;
-  for (pi = PointIndex::BASE; 
+  for (pi = PointIndex::BASE;
        pi < ngMesh->GetNP()+PointIndex::BASE; pi++)
   {
     outfile << "mesh.AddNode( ";
@@ -3892,6 +3972,7 @@ void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh )
   for ( int i = 0; i < nbDom; ++i )
     outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< std::endl;
 
+  int nbDel = 0;
   SurfaceElementIndex sei;
   for (sei = 0; sei < ngMesh->GetNSE(); sei++)
   {
@@ -3901,13 +3982,14 @@ void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh )
       outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])");
     if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
     outfile << std::endl;
+    nbDel += sel.IsDeleted();
 
     if ((*ngMesh)[sei].GetIndex())
     {
       if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn())
-        outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 << " ])" << std::endl;
+        outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 - nbDel << " ])" << std::endl;
       if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut())
-        outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 << " ])" << std::endl;
+        outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 - nbDel  << " ])" << std::endl;
     }
   }
 
@@ -3927,6 +4009,9 @@ void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh )
             << seg[0] << ", "
             << seg[1] << " ])" << std::endl;
   }
+
+#endif
+
   std::cout << "Write " << pyFile << std::endl;
 }
 
@@ -3968,11 +4053,7 @@ void NETGENPlugin_ngMeshInfo::transferLocalH( netgen::Mesh* fromMesh,
 {
   if ( !fromMesh->LocalHFunctionGenerated() ) return;
   if ( !toMesh->LocalHFunctionGenerated() )
-#ifdef NETGEN_V5
-    toMesh->CalcLocalH(netgen::mparam.grading);
-#else
-    toMesh->CalcLocalH();
-#endif
+    NETGENPlugin_NetgenLibWrapper::CalcLocalH( toMesh );
 
   const size_t size = sizeof( netgen::LocalH );
   _copyOfLocalH = new char[ size ];
@@ -4358,10 +4439,15 @@ int& NETGENPlugin_NetgenLibWrapper::instanceCounter()
  */
 //================================================================================
 
-NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper()
+NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper():
+  _ngMesh(0)
 {
   if ( instanceCounter() == 0 )
+  {
     Ng_Init();
+    if ( !netgen::testout )
+      netgen::testout = new ofstream( "test.out" );
+  }
 
   ++instanceCounter();
 
@@ -4371,21 +4457,10 @@ NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper()
   _ngcerr           = NULL;
   if ( !getenv( "KEEP_NETGEN_OUTPUT" ))
   {
-    // redirect all netgen output (mycout,myerr,cout) to _outputFileName
-    _outputFileName = getOutputFileName();
-    _ngcout         = netgen::mycout;
-    _ngcerr         = netgen::myerr;
-    netgen::mycout  = new ofstream ( _outputFileName.c_str() );
-    netgen::myerr   = netgen::mycout;
-    _coutBuffer     = std::cout.rdbuf();
-#ifdef _DEBUG_
-    std::cout << "NOTE: netgen output is redirected to file " << _outputFileName << std::endl;
-#else
-    std::cout.rdbuf( netgen::mycout->rdbuf() );
-#endif
+    setOutputFile(getOutputFileName());
   }
 
-  _ngMesh = Ng_NewMesh();
+  setMesh( Ng_NewMesh() );
 }
 
 //================================================================================
@@ -4398,7 +4473,7 @@ NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
 {
   --instanceCounter();
 
-  Ng_DeleteMesh( _ngMesh );
+  Ng_DeleteMesh( ngMesh() );
   Ng_Exit();
   RemoveTmpFiles();
   if ( _coutBuffer )
@@ -4418,8 +4493,69 @@ NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
 void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh )
 {
   if ( _ngMesh )
-    Ng_DeleteMesh( _ngMesh );
-  _ngMesh = mesh;
+    Ng_DeleteMesh( ngMesh() );
+  _ngMesh = (netgen::Mesh*) mesh;
+}
+
+//================================================================================
+/*!
+ * \brief Perform a step of mesh generation
+ *  \param [inout] occgeo - geometry to mesh
+ *  \param [inout] startWith - start step
+ *  \param [inout] endWith - end step
+ *  \param [inout] ngMesh - netgen mesh
+ *  \return int - is error
+ */
+//================================================================================
+
+int NETGENPlugin_NetgenLibWrapper::GenerateMesh( netgen::OCCGeometry& occgeo,
+                                                 int startWith, int endWith,
+                                                 netgen::Mesh* & ngMesh )
+{
+  int err = 0;
+  if ( !ngMesh )
+    ngMesh = new netgen::Mesh;
+
+  // To dump mparam
+  // netgen::mparam.Print(std::cerr);
+
+#ifdef NETGEN_V6
+
+  ngMesh->SetGeometry( shared_ptr<netgen::NetgenGeometry>( &occgeo, &NOOP_Deleter ));
+
+  netgen::mparam.perfstepsstart = startWith;
+  netgen::mparam.perfstepsend   = endWith;
+  std::shared_ptr<netgen::Mesh> meshPtr( ngMesh, &NOOP_Deleter );
+  err = occgeo.GenerateMesh( meshPtr, netgen::mparam );
+
+#else
+  #ifdef NETGEN_V5
+
+  err = netgen::OCCGenerateMesh(occgeo, ngMesh, netgen::mparam, startWith, endWith);
+
+  #else
+
+  char *optstr = 0;
+  err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
+
+  #endif
+#endif
+  return err;
+}
+
+//================================================================================
+/*!
+ * \brief Create a mesh size tree
+ */
+//================================================================================
+
+void NETGENPlugin_NetgenLibWrapper::CalcLocalH( netgen::Mesh * ngMesh )
+{
+#if defined( NETGEN_V5 ) || defined( NETGEN_V6 )
+  ngMesh->CalcLocalH(netgen::mparam.grading);
+#else
+  ngMesh->CalcLocalH();
+#endif
 }
 
 //================================================================================
@@ -4432,7 +4568,7 @@ std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName()
 {
   std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
 
-  TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
+  TCollection_AsciiString aGenericName = aTmpDir.c_str();
   aGenericName += "NETGEN_";
 #ifndef WIN32
   aGenericName += getpid();
@@ -4445,6 +4581,27 @@ std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName()
 
   return aGenericName.ToCString();
 }
+//================================================================================
+/*!
+ * \brief Set output file name for netgen log
+ */
+//================================================================================
+
+void NETGENPlugin_NetgenLibWrapper::setOutputFile(std::string outputfile)
+{
+  // redirect all netgen output (mycout,myerr,cout) to _outputFileName
+  _outputFileName = outputfile;
+  _ngcout         = netgen::mycout;
+  _ngcerr         = netgen::myerr;
+  netgen::mycout  = new ofstream ( _outputFileName.c_str() );
+  netgen::myerr   = netgen::mycout;
+  _coutBuffer     = std::cout.rdbuf();
+#ifdef _DEBUG_
+  std::cout << "NOTE: netgen output is redirected to file " << _outputFileName << std::endl;
+#else
+  std::cout.rdbuf( netgen::mycout->rdbuf() );
+#endif
+}
 
 //================================================================================
 /*!