Salome HOME
#17338 [CEA 17337] NETGEN3D regression - Illegal position in Geomsearch
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_Mesher.cxx
index 680fd9f01afc600912f89f621a966db714299b96..75f3758d6414e4f2140391febe30e04840b01b4d 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
+// Copyright (C) 2007-2019  CEA/DEN, EDF R&D, OPEN CASCADE
 //
 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
 #include "NETGENPlugin_SimpleHypothesis_3D.hxx"
 
 #include <SMDS_FaceOfNodes.hxx>
+#include <SMDS_LinearEdge.hxx>
 #include <SMDS_MeshElement.hxx>
 #include <SMDS_MeshNode.hxx>
 #include <SMESHDS_Mesh.hxx>
 #include <SMESH_Block.hxx>
 #include <SMESH_Comment.hxx>
 #include <SMESH_ComputeError.hxx>
+#include <SMESH_ControlPnt.hxx>
 #include <SMESH_File.hxx>
 #include <SMESH_Gen_i.hxx>
 #include <SMESH_Mesh.hxx>
 
 #include <utilities.h>
 
+#include <BRepAdaptor_Surface.hxx>
 #include <BRepBuilderAPI_Copy.hxx>
+#include <BRepLProp_SLProps.hxx>
+#include <BRepMesh_IncrementalMesh.hxx>
+#include <BRep_Builder.hxx>
 #include <BRep_Tool.hxx>
 #include <Bnd_B3d.hxx>
+#include <GeomLib_IsPlanarSurface.hxx>
 #include <NCollection_Map.hxx>
+#include <Poly_Triangulation.hxx>
 #include <Standard_ErrorHandler.hxx>
 #include <Standard_ProgramError.hxx>
 #include <TColStd_MapOfInteger.hxx>
 #include <TopExp.hxx>
 #include <TopExp_Explorer.hxx>
+#include <TopLoc_Location.hxx>
 #include <TopTools_DataMapIteratorOfDataMapOfShapeInteger.hxx>
 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
 #include <TopTools_DataMapOfShapeInteger.hxx>
 #include <TopTools_DataMapOfShapeShape.hxx>
 #include <TopTools_MapOfShape.hxx>
 #include <TopoDS.hxx>
+#include <TopoDS_Compound.hxx>
 
 // Netgen include files
 #ifndef OCCGEOMETRY
@@ -80,8 +90,14 @@ namespace netgen {
   extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
 #endif
   //extern void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh);
+
+  NETGENPLUGIN_DLL_HEADER
   extern MeshingParameters mparam;
+
+  NETGENPLUGIN_DLL_HEADER
   extern volatile multithreadt multithread;
+
+  NETGENPLUGIN_DLL_HEADER
   extern bool merge_solids;
 
   // values used for occgeo.facemeshstatus
@@ -119,6 +135,10 @@ TopTools_IndexedMapOfShape ShapesWithLocalSize;
 std::map<int,double> VertexId2LocalSize;
 std::map<int,double> EdgeId2LocalSize;
 std::map<int,double> FaceId2LocalSize;
+std::map<int,double> SolidId2LocalSize;
+
+std::vector<SMESHUtils::ControlPnt> ControlPoints;
+std::set<int> ShapesWithControlPoints; // <-- allows calling SetLocalSize() several times w/o recomputing ControlPoints
 
 //=============================================================================
 /*!
@@ -135,12 +155,14 @@ NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh*         mesh,
     _optimize(true),
     _fineness(NETGENPlugin_Hypothesis::GetDefaultFineness()),
     _isViscousLayers2D(false),
+    _chordalError(-1), // means disabled
     _ngMesh(NULL),
     _occgeom(NULL),
     _curShapeIndex(-1),
     _progressTic(1),
     _totalTime(1.0),
     _simpleHyp(NULL),
+    _viscousLayersHyp(NULL),
     _ptrToMe(NULL)
 {
   SetDefaultParameters();
@@ -148,11 +170,14 @@ NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh*         mesh,
   VertexId2LocalSize.clear();
   EdgeId2LocalSize.clear();
   FaceId2LocalSize.clear();
+  SolidId2LocalSize.clear();
+  ControlPoints.clear();
+  ShapesWithControlPoints.clear();
 }
 
 //================================================================================
 /*!
- * Destuctor
+ * Destructor
  */
 //================================================================================
 
@@ -191,6 +216,7 @@ void NETGENPlugin_Mesher::SetSelfPointer( NETGENPlugin_Mesher ** ptr )
 void NETGENPlugin_Mesher::SetDefaultParameters()
 {
   netgen::MeshingParameters& mparams = netgen::mparam;
+  mparams = netgen::MeshingParameters();
   // maximal mesh edge size
   mparams.maxh            = 0;//NETGENPlugin_Hypothesis::GetDefaultMaxSize();
   mparams.minh            = 0;
@@ -239,6 +265,8 @@ void SetLocalSize(TopoDS_Shape GeomShape, double LocalSize)
     EdgeId2LocalSize[key] = LocalSize;
   } else if (GeomType == TopAbs_FACE) {
     FaceId2LocalSize[key] = LocalSize;
+  } else if (GeomType == TopAbs_SOLID) {
+    SolidId2LocalSize[key] = LocalSize;
   }
 }
 
@@ -254,46 +282,55 @@ void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
     netgen::MeshingParameters& mparams = netgen::mparam;
     // Initialize global NETGEN parameters:
     // maximal mesh segment size
-    mparams.maxh            = hyp->GetMaxSize();
+    mparams.maxh               = hyp->GetMaxSize();
     // maximal mesh element linear size
-    mparams.minh            = hyp->GetMinSize();
+    mparams.minh               = hyp->GetMinSize();
     // minimal number of segments per edge
-    mparams.segmentsperedge = hyp->GetNbSegPerEdge();
+    mparams.segmentsperedge    = hyp->GetNbSegPerEdge();
     // rate of growth of size between elements
-    mparams.grading         = hyp->GetGrowthRate();
+    mparams.grading            = hyp->GetGrowthRate();
     // safety factor for curvatures (elements per radius)
-    mparams.curvaturesafety = hyp->GetNbSegPerRadius();
+    mparams.curvaturesafety    = hyp->GetNbSegPerRadius();
     // create elements of second order
-    mparams.secondorder     = hyp->GetSecondOrder() ? 1 : 0;
+    mparams.secondorder        = hyp->GetSecondOrder() ? 1 : 0;
     // quad-dominated surface meshing
-    mparams.quad            = hyp->GetQuadAllowed() ? 1 : 0;
-    _optimize               = hyp->GetOptimize();
-    _fineness               = hyp->GetFineness();
-    mparams.uselocalh       = hyp->GetSurfaceCurvature();
-    netgen::merge_solids    = hyp->GetFuseEdges();
-    _simpleHyp              = NULL;
-
-    SMESH_Gen_i*              smeshGen_i = SMESH_Gen_i::GetSMESHGen();
-    CORBA::Object_var           anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
-    SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
-    SALOMEDS::Study_var          myStudy = aStudyMgr->GetStudyByID(hyp->GetStudyId());
-
-    const NETGENPlugin_Hypothesis::TLocalSize   localSizes = hyp->GetLocalSizesAndEntries();
-    NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin();
-    for ( ; it != localSizes.end() ; it++)
-    {
-      std::string entry = (*it).first;
-      double        val = (*it).second;
-      // --
-      GEOM::GEOM_Object_var aGeomObj;
-      SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
-      if ( !aSObj->_is_nil() ) {
-        CORBA::Object_var obj = aSObj->GetObject();
-        aGeomObj = GEOM::GEOM_Object::_narrow(obj);
-        aSObj->UnRegister();
-      }
-      TopoDS_Shape S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
-      SetLocalSize(S, val);
+    mparams.quad               = hyp->GetQuadAllowed() ? 1 : 0;
+    _optimize                  = hyp->GetOptimize();
+    _fineness                  = hyp->GetFineness();
+    mparams.uselocalh          = hyp->GetSurfaceCurvature();
+    netgen::merge_solids       = hyp->GetFuseEdges();
+    _chordalError              = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.;
+    mparams.optsteps2d         = _optimize ? hyp->GetNbSurfOptSteps() : 0;
+    mparams.optsteps3d         = _optimize ? hyp->GetNbVolOptSteps()  : 0;
+    mparams.elsizeweight       = hyp->GetElemSizeWeight();
+    mparams.opterrpow          = hyp->GetWorstElemMeasure();
+    mparams.delaunay           = hyp->GetUseDelauney();
+    mparams.checkoverlap       = hyp->GetCheckOverlapping();
+    mparams.checkchartboundary = hyp->GetCheckChartBoundary();
+    _simpleHyp                 = NULL;
+    // mesh size file
+    mparams.meshsizefilename= hyp->GetMeshSizeFile().empty() ? 0 : hyp->GetMeshSizeFile().c_str();
+
+    const NETGENPlugin_Hypothesis::TLocalSize& localSizes = hyp->GetLocalSizesAndEntries();
+    if ( !localSizes.empty() )
+    {
+      SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen();
+      NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin();
+      for ( ; it != localSizes.end() ; it++)
+      {
+        std::string entry = (*it).first;
+        double        val = (*it).second;
+        // --
+        GEOM::GEOM_Object_var aGeomObj;
+        SALOMEDS::SObject_var aSObj = SMESH_Gen_i::getStudyServant()->FindObjectID( entry.c_str() );
+        if ( !aSObj->_is_nil() ) {
+          CORBA::Object_var obj = aSObj->GetObject();
+          aGeomObj = GEOM::GEOM_Object::_narrow(obj);
+          aSObj->UnRegister();
+        }
+        TopoDS_Shape S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
+        ::SetLocalSize(S, val);
+      }
     }
   }
 }
@@ -311,6 +348,17 @@ void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_SimpleHypothesis_2D*
     SetDefaultParameters();
 }
 
+//================================================================================
+/*!
+ * \brief Store a Viscous Layers hypothesis
+ */
+//================================================================================
+
+void NETGENPlugin_Mesher::SetParameters(const StdMeshers_ViscousLayers* hyp )
+{
+  _viscousLayersHyp = hyp;
+}
+
 //=============================================================================
 /*!
  *  Link - a pair of integer numbers
@@ -530,28 +578,287 @@ namespace
    */
   //================================================================================
 
-  void makeQuadratic( const TopTools_IndexedMapOfShape& shapes,
-                      SMESH_Mesh*                       mesh )
+  // void makeQuadratic( const TopTools_IndexedMapOfShape& shapes,
+  //                     SMESH_Mesh*                       mesh )
+  // {
+  //   for ( int i = 1; i <= shapes.Extent(); ++i )
+  //   {
+  //     SMESHDS_SubMesh* smDS = mesh->GetMeshDS()->MeshElements( shapes(i) );
+  //     if ( !smDS ) continue;
+  //     SMDS_ElemIteratorPtr elemIt = smDS->GetElements();
+  //     if ( !elemIt->more() ) continue;
+  //     const SMDS_MeshElement* e = elemIt->next();
+  //     if ( !e || e->IsQuadratic() )
+  //       continue;
+
+  //     TIDSortedElemSet elems;
+  //     elems.insert( e );
+  //     while ( elemIt->more() )
+  //       elems.insert( elems.end(), elemIt->next() );
+
+  //     SMESH_MeshEditor( mesh ).ConvertToQuadratic( /*3d=*/false, elems, /*biQuad=*/false );
+  //   }
+  // }
+
+  //================================================================================
+  /*!
+   * \brief Restrict size of elements on the given edge 
+   */
+  //================================================================================
+
+  void setLocalSize(const TopoDS_Edge& edge,
+                    double             size,
+                    netgen::Mesh&      mesh,
+                    const bool         overrideMinH = true)
   {
-    for ( int i = 1; i <= shapes.Extent(); ++i )
+    if ( size <= std::numeric_limits<double>::min() )
+      return;
+    Standard_Real u1, u2;
+    Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u1, u2);
+    if ( curve.IsNull() )
     {
-      SMESHDS_SubMesh* smDS = mesh->GetMeshDS()->MeshElements( shapes(i) );
-      if ( !smDS ) continue;
-      SMDS_ElemIteratorPtr elemIt = smDS->GetElements();
-      if ( !elemIt->more() ) continue;
-      const SMDS_MeshElement* e = elemIt->next();
-      if ( !e || e->IsQuadratic() )
-        continue;
+      TopoDS_Iterator vIt( edge );
+      if ( !vIt.More() ) return;
+      gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vIt.Value() ));
+      NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size, overrideMinH );
+    }
+    else
+    {
+      const int nb = (int)( 1.5 * SMESH_Algo::EdgeLength( edge ) / size );
+      Standard_Real delta = (u2-u1)/nb;
+      for(int i=0; i<nb; i++)
+      {
+        Standard_Real u = u1 + delta*i;
+        gp_Pnt p = curve->Value(u);
+        NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size, overrideMinH );
+        netgen::Point3d pi(p.X(), p.Y(), p.Z());
+        double resultSize = mesh.GetH(pi);
+        if ( resultSize - size > 0.1*size )
+          // netgen does restriction iff oldH/newH > 1.2 (localh.cpp:136)
+          NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), resultSize/1.201, overrideMinH );
+      }
+    }
+  }
+
+  //================================================================================
+  /*!
+   * \brief Return triangle size for a given chordalError and radius of curvature
+   */
+  //================================================================================
+
+  double elemSizeForChordalError( double chordalError, double radius )
+  {
+    if ( 2 * radius < chordalError )
+      return 1.5 * radius;
+    return Sqrt( 3 ) * Sqrt( chordalError * ( 2 * radius - chordalError ));
+  }
+
+} // namespace
+
+//================================================================================
+/*!
+ * \brief Set local size on shapes defined by SetParameters()
+ */
+//================================================================================
+
+void NETGENPlugin_Mesher::SetLocalSize( netgen::OCCGeometry& occgeo,
+                                        netgen::Mesh&        ngMesh)
+{
+  // edges
+  std::map<int,double>::const_iterator it;
+  for( it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
+  {
+    int   key = (*it).first;
+    double hi = (*it).second;
+    const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
+    setLocalSize( TopoDS::Edge(shape), hi, ngMesh );
+  }
+  // vertices
+  for(it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
+  {
+    int   key = (*it).first;
+    double hi = (*it).second;
+    const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
+    gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex(shape) );
+    NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, p.XYZ(), hi );
+  }
+  // faces
+  for(it=FaceId2LocalSize.begin(); it!=FaceId2LocalSize.end(); it++)
+  {
+    int    key = (*it).first;
+    double val = (*it).second;
+    const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
+    int faceNgID = occgeo.fmap.FindIndex(shape);
+    if ( faceNgID >= 1 )
+    {
+      occgeo.SetFaceMaxH(faceNgID, val);
+      for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
+        setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, ngMesh );
+    }
+    else if ( !ShapesWithControlPoints.count( key ))
+    {
+      SMESHUtils::createPointsSampleFromFace( TopoDS::Face( shape ), val, ControlPoints );
+      ShapesWithControlPoints.insert( key );
+    }
+  }
+  //solids
+  for(it=SolidId2LocalSize.begin(); it!=SolidId2LocalSize.end(); it++)
+  {
+    int    key = (*it).first;
+    double val = (*it).second;
+    if ( !ShapesWithControlPoints.count( key ))
+    {
+      const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
+      SMESHUtils::createPointsSampleFromSolid( TopoDS::Solid( shape ), val, ControlPoints );
+      ShapesWithControlPoints.insert( key );
+    }
+  }
+
+  if ( !ControlPoints.empty() )
+  {
+    for ( size_t i = 0; i < ControlPoints.size(); ++i )
+      NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, ControlPoints[i].XYZ(), ControlPoints[i].Size() );
+  }
+  return;
+}
+
+//================================================================================
+/*!
+ * \brief Restrict local size to achieve a required _chordalError
+ */
+//================================================================================
+
+void NETGENPlugin_Mesher::SetLocalSizeForChordalError( netgen::OCCGeometry& occgeo,
+                                                       netgen::Mesh&        ngMesh)
+{
+  if ( _chordalError <= 0. )
+    return;
 
-      TIDSortedElemSet elems;
-      elems.insert( e );
-      while ( elemIt->more() )
-        elems.insert( elems.end(), elemIt->next() );
+  TopLoc_Location loc;
+  BRepLProp_SLProps surfProp( 2, 1e-6 );
+  const double sizeCoef = 0.95;
 
-      SMESH_MeshEditor( mesh ).ConvertToQuadratic( /*3d=*/false, elems, /*biQuad=*/false );
+  // find non-planar FACEs with non-constant curvature
+  std::vector<int> fInd;
+  for ( int i = 1; i <= occgeo.fmap.Extent(); ++i )
+  {
+    const TopoDS_Face& face = TopoDS::Face( occgeo.fmap( i ));
+    BRepAdaptor_Surface surfAd( face, false );
+    switch ( surfAd.GetType() )
+    {
+    case GeomAbs_Plane:
+      continue;
+    case GeomAbs_Cylinder:
+    case GeomAbs_Sphere:
+    case GeomAbs_Torus: // constant curvature
+    {
+      surfProp.SetSurface( surfAd );
+      surfProp.SetParameters( 0, 0 );
+      double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
+      double    size = elemSizeForChordalError( _chordalError, 1 / maxCurv );
+      occgeo.SetFaceMaxH( i, size * sizeCoef );
+      // limit size one edges
+      TopTools_MapOfShape edgeMap;
+      for ( TopExp_Explorer eExp( face, TopAbs_EDGE ); eExp.More(); eExp.Next() )
+        if ( edgeMap.Add( eExp.Current() ))
+          setLocalSize( TopoDS::Edge( eExp.Current() ), size, ngMesh, /*overrideMinH=*/false );
+      break;
+    }
+    default:
+      Handle(Geom_Surface) surf = BRep_Tool::Surface( face, loc );
+      if ( GeomLib_IsPlanarSurface( surf ).IsPlanar() )
+        continue;
+      fInd.push_back( i );
     }
   }
+  // set local size
+  if ( !fInd.empty() )
+  {
+    BRep_Builder b;
+    TopoDS_Compound allFacesComp;
+    b.MakeCompound( allFacesComp );
+    for ( size_t i = 0; i < fInd.size(); ++i )
+      b.Add( allFacesComp, occgeo.fmap( fInd[i] ));
+
+    // copy the shape to avoid spoiling its triangulation
+    TopoDS_Shape allFacesCompCopy = BRepBuilderAPI_Copy( allFacesComp );
+
+    // create triangulation with desired chordal error
+    BRepMesh_IncrementalMesh( allFacesCompCopy,
+                              _chordalError,
+                              /*isRelative = */Standard_False,
+                              /*theAngDeflection = */ 0.5,
+                              /*isInParallel = */Standard_True);
+
+    // loop on FACEs
+    for ( TopExp_Explorer fExp( allFacesCompCopy, TopAbs_FACE ); fExp.More(); fExp.Next() )
+    {
+      const TopoDS_Face& face = TopoDS::Face( fExp.Current() );
+      Handle(Poly_Triangulation) triangulation = BRep_Tool::Triangulation ( face, loc );
+      if ( triangulation.IsNull() ) continue;
+
+      BRepAdaptor_Surface surf( face, false );
+      surfProp.SetSurface( surf );
+
+      gp_XY    uv[3];
+      gp_XYZ    p[3];
+      double size[3];
+      for ( int i = 1; i <= triangulation->NbTriangles(); ++i )
+      {
+        Standard_Integer n1,n2,n3;
+        triangulation->Triangles()(i).Get( n1,n2,n3 );
+        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();
+        surfProp.SetParameters( uv[0].X(), uv[0].Y() );
+        if ( !surfProp.IsCurvatureDefined() )
+          break;
+
+        for ( int n = 0; n < 3; ++n ) // get size at triangle nodes
+        {
+          surfProp.SetParameters( uv[n].X(), uv[n].Y() );
+          double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
+          size[n] = elemSizeForChordalError( _chordalError, 1 / maxCurv );
+        }
+        for ( int n1 = 0; n1 < 3; ++n1 ) // limit size along each triangle edge
+        {
+          int n2 = ( n1 + 1 ) % 3;
+          double minSize = size[n1], maxSize = size[n2];
+          if ( size[n1] > size[n2] )
+            minSize = size[n2], maxSize = size[n1];
 
+          if ( maxSize / minSize < 1.2 ) // netgen ignores size difference < 1.2
+          {
+            ngMesh.RestrictLocalHLine ( netgen::Point3d( p[n1].X(), p[n1].Y(), p[n1].Z() ),
+                                        netgen::Point3d( p[n2].X(), p[n2].Y(), p[n2].Z() ),
+                                        sizeCoef * minSize );
+          }
+          else
+          {
+            gp_XY uvVec( uv[n2] - uv[n1] );
+            double len = ( p[n1] - p[n2] ).Modulus();
+            int     nb = int( len / minSize ) + 1;
+            for ( int j = 0; j <= nb; ++j )
+            {
+              double r = double( j ) / nb;
+              gp_XY uvj = uv[n1] + r * uvVec;
+
+              surfProp.SetParameters( uvj.X(), uvj.Y() );
+              double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
+              double       h = elemSizeForChordalError( _chordalError, 1 / maxCurv );
+
+              const gp_Pnt& pj = surfProp.Value();
+              netgen::Point3d ngP( pj.X(), pj.Y(), pj.Z());
+              ngMesh.RestrictLocalH( ngP, h * sizeCoef );
+            }
+          }
+        }
+      }
+    }
+  }
 }
 
 //================================================================================
@@ -572,9 +879,6 @@ void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry&     occgeo,
   BRepBndLib::Add (shape, bb);
   double x1,y1,z1,x2,y2,z2;
   bb.Get (x1,y1,z1,x2,y2,z2);
-  MESSAGE("shape bounding box:\n" <<
-          "(" << x1 << " " << y1 << " " << z1 << ") " <<
-          "(" << x2 << " " << y2 << " " << z2 << ")");
   netgen::Point<3> p1 = netgen::Point<3> (x1,y1,z1);
   netgen::Point<3> p2 = netgen::Point<3> (x2,y2,z2);
   occgeo.boundingbox = netgen::Box<3> (p1,p2);
@@ -618,7 +922,7 @@ void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry&     occgeo,
         if ( shape.ShapeType() != TopAbs_VERTEX )
           shape = subShapes( subShapes.FindIndex( shape ));// shape -> index -> oriented shape
         if ( shape.Orientation() >= TopAbs_INTERNAL )
-          shape.Orientation( TopAbs_FORWARD ); // isuue 0020676
+          shape.Orientation( TopAbs_FORWARD ); // issue 0020676
         switch ( shape.ShapeType() ) {
         case TopAbs_FACE  : occgeo.fmap.Add( shape ); break;
         case TopAbs_EDGE  : occgeo.emap.Add( shape ); break;
@@ -687,7 +991,7 @@ double NETGENPlugin_Mesher::GetDefaultMinSize(const TopoDS_Shape& geom,
   }
   else
   {
-    minh = 3 * sqrt( minh ); // triangulation for visualization is rather fine
+    minh = sqrt( minh ); // triangulation for visualization is rather fine
     //cout << "TRIANGULATION minh = " <<minh << endl;
   }
   if ( minh > 0.5 * maxSize )
@@ -804,8 +1108,8 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry&           occgeom,
         bool isForwad = ( fOri == eNotSeam.Orientation() || fOri >= TopAbs_INTERNAL );
 
         // get all nodes from connected <edges>
-        const bool isQuad = smDS->IsQuadratic();
-        StdMeshers_FaceSide fSide( face, edges, _mesh, isForwad, isQuad );
+        const bool skipMedium = netgen::mparam.secondorder;//smDS->IsQuadratic();
+        StdMeshers_FaceSide fSide( face, edges, _mesh, isForwad, skipMedium, &helper );
         const vector<UVPtStruct>& points = fSide.GetUVPtStruct();
         if ( points.empty() )
           return false; // invalid node params?
@@ -933,13 +1237,6 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry&           occgeom,
 
       // Find solids the geomFace bounds
       int solidID1 = 0, solidID2 = 0;
-      StdMeshers_QuadToTriaAdaptor* quadAdaptor =
-        dynamic_cast<StdMeshers_QuadToTriaAdaptor*>( proxyMesh.get() );
-      if ( quadAdaptor )
-      {
-        solidID1 = occgeom.somap.FindIndex( quadAdaptor->GetShape() );
-      }
-      else
       {
         PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace, *sm->GetFather(), TopAbs_SOLID);
         while ( const TopoDS_Shape * solid = solidIt->next() )
@@ -949,6 +1246,81 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry&           occgeom,
           else                              solidID1 = id;
         }
       }
+      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() )
+        {
+          const SMDS_MeshElement* f = faces->next();
+          if ( proxyMesh->IsTemporary( f ))
+          {
+            hasTmp = true;
+            std::vector<const SMDS_MeshNode*> fNodes( f->begin_nodes(), f->end_nodes() );
+            std::vector<const SMDS_MeshElement*> vols;
+            if ( _mesh->GetMeshDS()->GetElementsByNodes( fNodes, vols, SMDSAbs_Volume ) == 1 )
+            {
+              int geomID = vols[0]->getshapeId();
+              const TopoDS_Shape& solid =  helper.GetMeshDS()->IndexToShape( geomID );
+              if ( !solid.IsNull() )
+                solidID1 = occgeom.somap.FindIndex ( solid );
+              solidID2 = 0;
+              break;
+            }
+          }
+        }
+        // exclude faces generated by NETGEN from computation of 3D mesh
+        const int fID = occgeom.fmap.FindIndex( geomFace );
+        if ( !hasTmp ) // shrunk mesh
+        {
+          // move netgen points according to moved nodes
+          SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
+          while ( smIt->more() )
+          {
+            SMESH_subMesh* sub = smIt->next();
+            if ( !sub->GetSubMeshDS() ) continue;
+            SMDS_NodeIteratorPtr nodeIt = sub->GetSubMeshDS()->GetNodes();
+            while ( nodeIt->more() )
+            {
+              const SMDS_MeshNode* n = nodeIt->next();
+              int ngID = ngNodeId( n, ngMesh, nodeNgIdMap );
+              netgen::MeshPoint& ngPoint = ngMesh.Point( ngID );
+              ngPoint(0) = n->X();
+              ngPoint(1) = n->Y();
+              ngPoint(2) = n->Z();
+            }
+          }
+          // remove faces near boundary to avoid their overlapping
+          // with shrunk faces
+          for ( int i = 1; i <= ngMesh.GetNSE(); ++i )
+          {
+            const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
+            if ( elem.GetIndex() == fID )
+            {
+              for ( int iN = 0; iN < elem.GetNP(); ++iN )
+                if ( ngMesh[ elem[ iN ]].Type() != netgen::SURFACEPOINT )
+                {
+                  ngMesh.DeleteSurfaceElement( i );
+                  break;
+                }
+            }
+          }
+        }
+        //if ( hasTmp )
+        {
+          faceNgID++;
+          ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID,/*solid1=*/0,/*solid2=*/0,0 ));
+          for (int i = 1; i <= ngMesh.GetNSE(); ++i )
+          {
+            const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
+            if ( elem.GetIndex() == fID )
+              const_cast< netgen::Element2d& >( elem ).SetIndex( faceNgID );
+          }
+        }
+      }
       // Add ng face descriptors of meshed faces
       faceNgID++;
       ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, solidID1, solidID2, 0 ));
@@ -991,8 +1363,6 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry&           occgeom,
       cout << "SMESH face " << helper.GetMeshDS()->ShapeToIndex( geomFace )
            << " internal="<<isInternalFace << endl;
 #endif
-      if ( proxyMesh )
-        smDS = proxyMesh->GetSubMesh( geomFace );
 
       SMDS_ElemIteratorPtr faces = smDS->GetElements();
       while ( faces->more() )
@@ -1003,9 +1373,11 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry&           occgeom,
           PShapeIteratorPtr solidIt=helper.GetAncestors(geomFace,*sm->GetFather(),TopAbs_SOLID);
           if ( const TopoDS_Shape * solid = solidIt->next() )
             sm = _mesh->GetSubMesh( *solid );
-          SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
-          smError.reset( new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH,"Not triangle sub-mesh"));
-          smError->myBadElements.push_back( f );
+          SMESH_BadInputElements* badElems =
+            new SMESH_BadInputElements( helper.GetMeshDS(), COMPERR_BAD_INPUT_MESH,
+                                        "Not triangle sub-mesh");
+          badElems->add( f );
+          sm->GetComputeError().reset( badElems );
           return false;
         }
 
@@ -1291,7 +1663,7 @@ namespace
   struct TIntVData
   {
     gp_XY uv;        //!< UV in face parametric space
-    int   ngId;      //!< ng id of corrsponding node
+    int   ngId;      //!< ng id of corresponding node
     gp_XY uvClose;   //!< UV of closest boundary node
     int   ngIdClose; //!< ng id of closest boundary node
   };
@@ -1309,10 +1681,15 @@ namespace
     int   ngIdCloseN; //!< ng id of closest node of the closest 2d mesh element
   };
 
-  inline double dist2(const netgen::MeshPoint& p1, const netgen::MeshPoint& p2)
+  inline double dist2( const netgen::MeshPoint& p1, const netgen::MeshPoint& p2 )
   {
     return gp_Pnt( NGPOINT_COORDS(p1)).SquareDistance( gp_Pnt( NGPOINT_COORDS(p2)));
   }
+
+  // inline double dist2(const netgen::MeshPoint& p, const SMDS_MeshNode* n )
+  // {
+  //   return gp_Pnt( NGPOINT_COORDS(p)).SquareDistance( SMESH_NodeXYZ(n));
+  // }
 }
 
 //================================================================================
@@ -1499,6 +1876,7 @@ void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry&     o
     }
 
   }
+  ngMesh.CalcSurfacesOfNode();
 }
 
 //================================================================================
@@ -1520,7 +1898,7 @@ void NETGENPlugin_Mesher::AddIntVerticesInSolids(const netgen::OCCGeometry&
   ofstream py(DUMP_TRIANGLES_SCRIPT);
   py << "import SMESH"<< endl
      << "from salome.smesh import smeshBuilder"<<endl
-     << "smesh = smeshBuilder.New(salome.myStudy)"<<endl
+     << "smesh = smeshBuilder.New()"<<endl
      << "m = smesh.Mesh(name='triangles')" << endl;
 #endif
   if ((int) nodeVec.size() < ngMesh.GetNP() )
@@ -1824,7 +2202,7 @@ NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh&                    ngMesh,
     int edgeID = 1, posID = -2;
     bool isInternalWire = false;
     double vertexNormPar = 0;
-    //const int prevNbNGSeg = ngMesh.GetNSeg();
+    const int prevNbNGSeg = ngMesh.GetNSeg();
     for ( int i = 0; i < nbSegments; ++i ) // loop on segments
     {
       // Add the first point of a segment
@@ -1947,7 +2325,7 @@ NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh&                    ngMesh,
         netgen::Segment& prevSeg = ngMesh.LineSegment( i-1 );
         if ( seg[0] == prevSeg[1] && seg[1] == prevSeg[0] )
         {
-          cout << "Segment: " << seg.edgenr << endl << "\tis REVRESE of the previous one" << endl;
+          cout << "Segment: " << seg.edgenr << endl << "\tis REVERSE of the previous one" << endl;
           continue;
         }
       }
@@ -1962,6 +2340,8 @@ NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh&                    ngMesh,
            << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
     }
     cout << "--END WIRE " << iW << endl;
+#else
+    SMESH_Comment __not_unused_variable( prevNbNGSeg );
 #endif
 
   } // loop on WIREs of a FACE
@@ -2007,19 +2387,41 @@ int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry&          occgeo,
   SMESHDS_Mesh* meshDS = sMesh.GetMeshDS();
 
   // quadHelper is used for either
-  // 1) making quadratic elements when a lower dimention mesh is loaded
-  //    to SMESH before convertion to quadratic by NETGEN
+  // 1) making quadratic elements when a lower dimension mesh is loaded
+  //    to SMESH before conversion to quadratic by NETGEN
   // 2) sewing of quadratic elements with quadratic elements of sub-meshes
   if ( quadHelper && !quadHelper->GetIsQuadratic() && quadHelper->GetTLinkNodeMap().empty() )
     quadHelper = 0;
 
+  int i, 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();
+    const double eps = std::numeric_limits<double>::min();
+    for ( ngID = i = 1; i < nodeVecSize; ++ngID, ++i )
+    {
+      gp_Pnt ngPnt( NGPOINT_COORDS( ngMesh.Point( ngID )));
+      gp_Pnt node ( SMESH_NodeXYZ (nodeVec_ACCESS(i) ));
+      if ( ngPnt.SquareDistance( node ) < eps )
+      {
+        nodeVec[ ngID ] = nodeVec[ i ];
+      }
+      else
+      {
+        --ngID;
+      }
+    }
+    nodeVec.resize( ngID );
+    nbInitNod = ngID - 1;
+  }
   // -------------------------------------
   // Create and insert nodes into nodeVec
   // -------------------------------------
 
   nodeVec.resize( nbNod + 1 );
-  int i, nbInitNod = initState._nbNodes;
-  for (i = nbInitNod+1; i <= nbNod; ++i )
+  for ( i = nbInitNod+1; i <= nbNod; ++i )
   {
     const netgen::MeshPoint& ngPoint = ngMesh.Point(i);
     SMDS_MeshNode* node = NULL;
@@ -2278,45 +2680,6 @@ int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry&          occgeo,
 
 namespace
 {
-  //================================================================================
-  /*!
-   * \brief Restrict size of elements on the given edge 
-   */
-  //================================================================================
-
-  void setLocalSize(const TopoDS_Edge& edge,
-                    double             size,
-                    netgen::Mesh&      mesh)
-  {
-    if ( size <= std::numeric_limits<double>::min() )
-      return;
-    Standard_Real u1, u2;
-    Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u1, u2);
-    if ( curve.IsNull() )
-    {
-      TopoDS_Iterator vIt( edge );
-      if ( !vIt.More() ) return;
-      gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vIt.Value() ));
-      NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
-    }
-    else
-    {
-      const int nb = (int)( 1.5 * SMESH_Algo::EdgeLength( edge ) / size );
-      Standard_Real delta = (u2-u1)/nb;
-      for(int i=0; i<nb; i++)
-      {
-        Standard_Real u = u1 + delta*i;
-        gp_Pnt p = curve->Value(u);
-        NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
-        netgen::Point3d pi(p.X(), p.Y(), p.Z());
-        double resultSize = mesh.GetH(pi);
-        if ( resultSize - size > 0.1*size )
-          // netgen does restriction iff oldH/newH > 1.2 (localh.cpp:136)
-          NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), resultSize/1.201 );
-      }
-    }
-  }
-
   //================================================================================
   /*!
    * \brief Convert error into text
@@ -2414,23 +2777,11 @@ bool NETGENPlugin_Mesher::Compute()
   NETGENPlugin_NetgenLibWrapper ngLib;
 
   netgen::MeshingParameters& mparams = netgen::mparam;
-  MESSAGE("Compute with:\n"
-          " max size = " << mparams.maxh << "\n"
-          " segments per edge = " << mparams.segmentsperedge);
-  MESSAGE("\n"
-          " growth rate = " << mparams.grading << "\n"
-          " elements per radius = " << mparams.curvaturesafety << "\n"
-          " second order = " << mparams.secondorder << "\n"
-          " quad allowed = " << mparams.quad << "\n"
-          " surface curvature = " << mparams.uselocalh << "\n"
-          " fuse edges = " << netgen::merge_solids);
 
   SMESH_ComputeErrorPtr error = SMESH_ComputeError::New();
   SMESH_MesherHelper quadHelper( *_mesh );
   quadHelper.SetIsQuadratic( mparams.secondorder );
 
-  static string debugFile = "/tmp/ngMesh.py"; /* to call toPython( _ngMesh, debugFile )
-                                                 while debugging netgen */
   // -------------------------
   // Prepare OCC geometry
   // -------------------------
@@ -2513,6 +2864,12 @@ bool NETGENPlugin_Mesher::Compute()
     {
       comment << text(ex);
     }
+    catch (netgen::NgException & ex)
+    {
+      comment << text(ex);
+      if ( mparams.meshsizefilename )
+        throw SMESH_ComputeError(COMPERR_BAD_PARMETERS, comment );
+    }
     err = 0; //- MESHCONST_ANALYSE isn't so important step
     if ( !_ngMesh )
       return false;
@@ -2520,6 +2877,9 @@ bool NETGENPlugin_Mesher::Compute()
 
     _ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
 
+    if ( !mparams.uselocalh ) // mparams.grading is not taken into account yet
+      _ngMesh->LocalHFunction().SetGrading( mparams.grading );
+
     if ( _simpleHyp )
     {
       // Pass 1D simple parameters to NETGEN
@@ -2536,36 +2896,9 @@ bool NETGENPlugin_Mesher::Compute()
     }
     else // if ( ! _simpleHyp )
     {
-      // Local size on vertices and edges
-      // --------------------------------
-      for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
-      {
-        int key = (*it).first;
-        double hi = (*it).second;
-        const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
-        const TopoDS_Edge& e = TopoDS::Edge(shape);
-        setLocalSize( e, hi, *_ngMesh );
-      }
-      for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
-      {
-        int key = (*it).first;
-        double hi = (*it).second;
-        const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
-        const TopoDS_Vertex& v = TopoDS::Vertex(shape);
-        gp_Pnt p = BRep_Tool::Pnt(v);
-        NETGENPlugin_Mesher::RestrictLocalSize( *_ngMesh, p.XYZ(), hi );
-      }
-      for(map<int,double>::const_iterator it=FaceId2LocalSize.begin();
-          it!=FaceId2LocalSize.end(); it++)
-      {
-        int key = (*it).first;
-        double val = (*it).second;
-        const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
-        int faceNgID = occgeo.fmap.FindIndex(shape);
-        occgeo.SetFaceMaxH(faceNgID, val);
-        for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
-          setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *_ngMesh );
-      }
+      // Local size on shapes
+      SetLocalSize( occgeo, *_ngMesh );
+      SetLocalSizeForChordalError( occgeo, *_ngMesh );
     }
 
     // Precompute internal edges (issue 0020676) in order to
@@ -2708,7 +3041,9 @@ bool NETGENPlugin_Mesher::Compute()
       }
 
       // Build viscous layers
-      if ( _isViscousLayers2D )
+      if (( _isViscousLayers2D ) ||
+          ( !occgeo.fmap.IsEmpty() &&
+            StdMeshers_ViscousLayers2D::HasProxyMesh( TopoDS::Face( occgeo.fmap(1) ), *_mesh )))
       {
         if ( !internals.hasInternalVertexInFace() ) {
           FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
@@ -2722,6 +3057,8 @@ bool NETGENPlugin_Mesher::Compute()
           viscousMesh = StdMeshers_ViscousLayers2D::Compute( *_mesh, F );
           if ( !viscousMesh )
             return false;
+          if ( viscousMesh->NbProxySubMeshes() == 0 )
+            continue;
           // exclude from computation ng segments built on EDGEs of F
           for (int i = 1; i <= _ngMesh->GetNSeg(); i++)
           {
@@ -2733,7 +3070,7 @@ bool NETGENPlugin_Mesher::Compute()
           helper.SetSubShape( F );
           TSideVector wires =
             StdMeshers_FaceSide::GetFaceWires( F, *_mesh, /*skipMediumNodes=*/true,
-                                               error, viscousMesh );
+                                               error, &helper, viscousMesh );
           error = AddSegmentsToMesh( *_ngMesh, occgeo, wires, helper, nodeVec );
 
           if ( !error ) error = SMESH_ComputeError::New();
@@ -2777,37 +3114,58 @@ bool NETGENPlugin_Mesher::Compute()
     // generate volume mesh
     // ---------------------
     // Fill _ngMesh with nodes and faces of computed 2D submeshes
-    if ( !err && _isVolume && ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad ))
+    if ( !err && _isVolume &&
+         ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad || _viscousLayersHyp ))
     {
       // load SMESH with computed segments and faces
       FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
 
+      // compute prismatic boundary volumes
+      int nbQuad = _mesh->NbQuadrangles();
+      SMESH_ProxyMesh::Ptr viscousMesh;
+      if ( _viscousLayersHyp )
+      {
+        viscousMesh = _viscousLayersHyp->Compute( *_mesh, _shape );
+        if ( !viscousMesh )
+          return false;
+      }
       // compute pyramids on quadrangles
-      SMESH_ProxyMesh::Ptr proxyMesh;
-      if ( _mesh->NbQuadrangles() > 0 )
+      vector<SMESH_ProxyMesh::Ptr> pyramidMeshes( occgeo.somap.Extent() );
+      if ( nbQuad > 0 )
         for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
         {
-          StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
-          proxyMesh.reset( Adaptor );
-
-          int nbPyrams = _mesh->NbPyramids();
-          Adaptor->Compute( *_mesh, occgeo.somap(iS) );
-          if ( nbPyrams != _mesh->NbPyramids() )
+          StdMeshers_QuadToTriaAdaptor* adaptor = new StdMeshers_QuadToTriaAdaptor;
+          pyramidMeshes[ iS-1 ].reset( adaptor );
+          bool ok = adaptor->Compute( *_mesh, occgeo.somap(iS), viscousMesh.get() );
+          if ( !ok )
+            return false;
+        }
+      // add proxy faces to NG mesh
+      list< SMESH_subMesh* > viscousSM;
+      for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
+      {
+        list< SMESH_subMesh* > quadFaceSM;
+        for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next())
+          if ( pyramidMeshes[iS-1] && pyramidMeshes[iS-1]->GetProxySubMesh( face.Current() ))
           {
-            list< SMESH_subMesh* > quadFaceSM;
-            for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next())
-              if ( Adaptor->GetProxySubMesh( face.Current() ))
-              {
-                quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
-                meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
-              }
-            FillNgMesh(occgeo, *_ngMesh, nodeVec, quadFaceSM, &quadHelper, proxyMesh);
+            quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
+            meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
           }
-        }
+          else if ( viscousMesh && viscousMesh->GetProxySubMesh( face.Current() ))
+          {
+            viscousSM.push_back( _mesh->GetSubMesh( face.Current() ));
+            meshedSM[ MeshDim_2D ].remove( viscousSM.back() );
+          }
+        if ( !quadFaceSM.empty() )
+          FillNgMesh(occgeo, *_ngMesh, nodeVec, quadFaceSM, &quadHelper, pyramidMeshes[iS-1]);
+      }
+      if ( !viscousSM.empty() )
+        FillNgMesh(occgeo, *_ngMesh, nodeVec, viscousSM, &quadHelper, viscousMesh );
+
       // fill _ngMesh with faces of sub-meshes
       err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_2D ], &quadHelper));
-      initState = NETGENPlugin_ngMeshInfo(_ngMesh);
-      //toPython( _ngMesh, "/tmp/ngPython.py");
+      initState = NETGENPlugin_ngMeshInfo(_ngMesh, /*checkRemovedElems=*/true);
+      // toPython( _ngMesh );
     }
     if (!err && _isVolume)
     {
@@ -2857,18 +3215,18 @@ bool NETGENPlugin_Mesher::Compute()
         if(netgen::multithread.terminate)
           return false;
 
-        if ( comment.empty() ) // do not overwrite a previos error
+        if ( comment.empty() ) // do not overwrite a previous error
           comment << text(err);
       }
       catch (Standard_Failure& ex)
       {
-        if ( comment.empty() ) // do not overwrite a previos error
+        if ( comment.empty() ) // do not overwrite a previous error
           comment << text(ex);
         err = 1;
       }
       catch (netgen::NgException exc)
       {
-        if ( comment.empty() ) // do not overwrite a previos error
+        if ( comment.empty() ) // do not overwrite a previous error
           comment << text(exc);
         err = 1;
       }
@@ -2889,17 +3247,17 @@ bool NETGENPlugin_Mesher::Compute()
           if(netgen::multithread.terminate)
             return false;
 
-          if ( comment.empty() ) // do not overwrite a previos error
+          if ( comment.empty() ) // do not overwrite a previous error
             comment << text(err);
         }
         catch (Standard_Failure& ex)
         {
-          if ( comment.empty() ) // do not overwrite a previos error
+          if ( comment.empty() ) // do not overwrite a previous error
             comment << text(ex);
         }
         catch (netgen::NgException exc)
         {
-          if ( comment.empty() ) // do not overwrite a previos error
+          if ( comment.empty() ) // do not overwrite a previous error
             comment << text(exc);
         }
       }
@@ -2916,7 +3274,10 @@ bool NETGENPlugin_Mesher::Compute()
           {
             const netgen::Segment & seg = _ngMesh->LineSegment (i);
             if ( seg.epgeominfo[ 0 ].edgenr == 0 )
+            {
               _ngMesh->DeleteSegment( i );
+              initState._nbSegments--;
+            }
           }
           _ngMesh->Compress();
         }
@@ -2932,12 +3293,12 @@ bool NETGENPlugin_Mesher::Compute()
       }
       catch (Standard_Failure& ex)
       {
-        if ( comment.empty() ) // do not overwrite a previos error
+        if ( comment.empty() ) // do not overwrite a previous error
           comment << "Exception in netgen at passing to 2nd order ";
       }
       catch (netgen::NgException exc)
       {
-        if ( comment.empty() ) // do not overwrite a previos error
+        if ( comment.empty() ) // do not overwrite a previous error
           comment << exc.What();
       }
     }
@@ -2945,30 +3306,34 @@ bool NETGENPlugin_Mesher::Compute()
 
   _ticTime = 0.98 / _progressTic;
 
-  int nbNod = _ngMesh->GetNP();
-  int nbSeg = _ngMesh->GetNSeg();
+  //int nbNod = _ngMesh->GetNP();
+  //int nbSeg = _ngMesh->GetNSeg();
   int nbFac = _ngMesh->GetNSE();
   int nbVol = _ngMesh->GetNE();
   bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
 
-  MESSAGE((err ? "Mesh Generation failure" : "End of Mesh Generation") <<
-          ", nb nodes: "    << nbNod <<
-          ", nb segments: " << nbSeg <<
-          ", nb faces: "    << nbFac <<
-          ", nb volumes: "  << nbVol);
-
   // Feed back the SMESHDS with the generated Nodes and Elements
   if ( true /*isOK*/ ) // get whatever built
   {
     FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
 
     if ( quadHelper.GetIsQuadratic() ) // remove free nodes
+    {
       for ( size_t i = 0; i < nodeVec.size(); ++i )
         if ( nodeVec[i] && nodeVec[i]->NbInverseElements() == 0 )
+        {
           _mesh->GetMeshDS()->RemoveFreeNode( nodeVec[i], 0, /*fromGroups=*/false );
+          nodeVec[i]=0;
+        }
+      for ( size_t i = nodeVec.size()-1; i > 0; --i ) // remove trailing removed nodes
+        if ( !nodeVec[i] )
+          nodeVec.resize( i );
+        else
+          break;
+    }
   }
   SMESH_ComputeErrorPtr readErr = ReadErrors(nodeVec);
-  if ( readErr && !readErr->myBadElements.empty() )
+  if ( readErr && readErr->HasBadElems() )
   {
     error = readErr;
     if ( !comment.empty() && !readErr->myComment.empty() ) comment += "\n";
@@ -3025,14 +3390,15 @@ bool NETGENPlugin_Mesher::Compute()
           SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
           if ( !smComputed && ( !smError || smError->IsOK() ))
           {
-            smError.reset( new SMESH_ComputeError( *error ));
+            smError = error;
             if ( nbVol && SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
             {
               smError->myName = COMPERR_WARNING;
             }
-            else if ( !smError->myBadElements.empty() ) // bad surface mesh
+            else if ( smError->HasBadElems() ) // bad surface mesh
             {
-              if ( !hasBadElemOnSolid( smError->myBadElements, sm ))
+              if ( !hasBadElemOnSolid
+                   ( static_cast<SMESH_BadInputElements*>( smError.get() )->myBadElements, sm ))
                 smError.reset();
             }
           }
@@ -3061,9 +3427,8 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
   // Prepare OCC geometry
   // -------------------------
   netgen::OCCGeometry occgeo;
-  list< SMESH_subMesh* > meshedSM[4]; // for 0-3 dimensions
   NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
-  PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
+  PrepareOCCgeometry( occgeo, _shape, *_mesh, 0, &internals );
 
   bool tooManyElems = false;
   const int hugeNb = std::numeric_limits<int>::max() / 100;
@@ -3114,53 +3479,25 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
       sm->GetComputeError().reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED ));
     return false;
   }
-  if ( _simpleHyp )
-  {
-    // Pass 1D simple parameters to NETGEN
-    // --------------------------------
-    int      nbSeg = _simpleHyp->GetNumberOfSegments();
-    double segSize = _simpleHyp->GetLocalLength();
-    for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
-    {
-      const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
-      if ( nbSeg )
-        segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
-      setLocalSize( e, segSize, *ngMesh );
-    }
-  }
-  else // if ( ! _simpleHyp )
-  {
-    // Local size on vertices and edges
-    // --------------------------------
-    for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
-    {
-      int key = (*it).first;
-      double hi = (*it).second;
-      const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
-      const TopoDS_Edge& e = TopoDS::Edge(shape);
-      setLocalSize( e, hi, *ngMesh );
-    }
-    for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
-    {
-      int key = (*it).first;
-      double hi = (*it).second;
-      const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
-      const TopoDS_Vertex& v = TopoDS::Vertex(shape);
-      gp_Pnt p = BRep_Tool::Pnt(v);
-      NETGENPlugin_Mesher::RestrictLocalSize( *ngMesh, p.XYZ(), hi );
-    }
-    for(map<int,double>::const_iterator it=FaceId2LocalSize.begin();
-        it!=FaceId2LocalSize.end(); it++)
-    {
-      int key = (*it).first;
-      double val = (*it).second;
-      const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
-      int faceNgID = occgeo.fmap.FindIndex(shape);
-      occgeo.SetFaceMaxH(faceNgID, val);
-      for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
-        setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *ngMesh );
-    }
-  }
+  // if ( _simpleHyp )
+  // {
+  //   // Pass 1D simple parameters to NETGEN
+  //   // --------------------------------
+  //   int      nbSeg = _simpleHyp->GetNumberOfSegments();
+  //   double segSize = _simpleHyp->GetLocalLength();
+  //   for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
+  //   {
+  //     const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
+  //     if ( nbSeg )
+  //       segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
+  //     setLocalSize( e, segSize, *ngMesh );
+  //   }
+  // }
+  // else // if ( ! _simpleHyp )
+  // {
+  //   // Local size on shapes
+  //   SetLocalSize( occgeo, *ngMesh );
+  // }
   // calculate total nb of segments and length of edges
   double fullLen = 0.0;
   int fullNbSeg = 0;
@@ -3239,9 +3576,9 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
     int nb1d = 0;
     if ( !tooManyElems )
     {
-      TopTools_MapOfShape egdes;
+      TopTools_MapOfShape edges;
       for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next())
-        if ( egdes.Add( exp1.Current() ))
+        if ( edges.Add( exp1.Current() ))
           nb1d += Edge2NbSeg.Find(exp1.Current());
     }
     int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.)));
@@ -3360,10 +3697,19 @@ double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* holder,
       //      << " " << doneTime / _totalTime / _progressTic << endl;
     }
   }
+
   if ( _ticTime > 0 )
     progress  = Max( *algoProgressTic * _ticTime, *algoProgress );
+
   if ( progress > 0 )
   {
+    if ( _isVolume &&
+         netgen::multithread.task[0] == 'D'/*elaunay meshing*/ &&
+         progress > voluMeshingTime )
+    {
+      progress = voluMeshingTime;
+      ((double&) _ticTime) = voluMeshingTime / _totalTime / _progressTic;
+    }
     ((int&) *algoProgressTic )++;
     ((double&) *algoProgress) = progress;
   }
@@ -3372,26 +3718,6 @@ double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* holder,
   return Min( progress, 0.99 );
 }
 
-//================================================================================
-/*!
- * \brief Remove "test.out" and "problemfaces" files in current directory
- */
-//================================================================================
-
-void NETGENPlugin_Mesher::RemoveTmpFiles()
-{
-  bool rm =  SMESH_File("test.out").remove() ;
-#ifndef WIN32
-  if (rm && netgen::testout)
-  {
-    delete netgen::testout;
-    netgen::testout = 0;
-  }
-#endif
-  SMESH_File("problemfaces").remove();
-  SMESH_File("occmesh.rep").remove();
-}
-
 //================================================================================
 /*!
  * \brief Read mesh entities preventing successful computation from "test.out" file
@@ -3401,8 +3727,10 @@ void NETGENPlugin_Mesher::RemoveTmpFiles()
 SMESH_ComputeErrorPtr
 NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
 {
-  SMESH_ComputeErrorPtr err = SMESH_ComputeError::New
-    (COMPERR_BAD_INPUT_MESH, "Some edges multiple times in surface mesh");
+  if ( nodeVec.size() < 2 ) return SMESH_ComputeErrorPtr();
+  SMESH_BadInputElements* err =
+    new SMESH_BadInputElements( nodeVec.back()->GetMesh(), COMPERR_BAD_INPUT_MESH,
+                                "Some edges multiple times in surface mesh");
   SMESH_File file("test.out");
   vector<int> two(2);
   vector<int> three1(3), three2(3);
@@ -3459,10 +3787,10 @@ NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
 
 #ifdef _DEBUG_
   size_t nbBadElems = err->myBadElements.size();
-  nbBadElems = 0;
+  if ( nbBadElems ) nbBadElems++; // avoid warning: variable set but not used
 #endif
 
-  return err;
+  return SMESH_ComputeErrorPtr( err );
 }
 
 //================================================================================
@@ -3473,16 +3801,16 @@ NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
  */
 //================================================================================
 
-void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh,
-                                    const std::string&  pyFile)
+void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh )
 {
-  ofstream outfile(pyFile.c_str(), ios::out);
+  const char*  pyFile = "/tmp/ngMesh.py";
+  ofstream outfile( pyFile, ios::out );
   if ( !outfile ) return;
 
-  outfile << "import SMESH" << endl
-          << "from salome.smesh import smeshBuilder" << endl
-          << "smesh = smeshBuilder.New(salome.myStudy)" << endl
-          << "mesh = smesh.Mesh()" << endl << endl;
+  outfile << "import salome, SMESH" << std::endl
+          << "from salome.smesh import smeshBuilder" << std::endl
+          << "smesh = smeshBuilder.New()" << std::endl
+          << "mesh = smesh.Mesh()" << std::endl << std::endl;
 
   using namespace netgen;
   PointIndex pi;
@@ -3492,12 +3820,12 @@ void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh,
     outfile << "mesh.AddNode( ";
     outfile << (*ngMesh)[pi](0) << ", ";
     outfile << (*ngMesh)[pi](1) << ", ";
-    outfile << (*ngMesh)[pi](2) << ") ## "<< pi << endl;
+    outfile << (*ngMesh)[pi](2) << ") ## "<< pi << std::endl;
   }
 
   int nbDom = ngMesh->GetNDomains();
   for ( int i = 0; i < nbDom; ++i )
-    outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< endl;
+    outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< std::endl;
 
   SurfaceElementIndex sei;
   for (sei = 0; sei < ngMesh->GetNSE(); sei++)
@@ -3507,14 +3835,14 @@ void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh,
     for (int j = 0; j < sel.GetNP(); j++)
       outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])");
     if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
-    outfile << endl;
+    outfile << std::endl;
 
     if ((*ngMesh)[sei].GetIndex())
     {
       if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn())
-        outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 << " ])" << endl;
+        outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 << " ])" << std::endl;
       if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut())
-        outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 << " ])" << endl;
+        outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 << " ])" << std::endl;
     }
   }
 
@@ -3524,7 +3852,7 @@ void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh,
     outfile << "mesh.AddVolume([ ";
     for (int j = 0; j < el.GetNP(); j++)
       outfile << el[j] << ( j+1 < el.GetNP() ? ", " : " ])");
-    outfile << endl;
+    outfile << std::endl;
   }
 
   for (int i = 1; i <= ngMesh->GetNSeg(); i++)
@@ -3532,9 +3860,9 @@ void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh,
     const Segment & seg = ngMesh->LineSegment (i);
     outfile << "mesh.AddEdge([ "
             << seg[0] << ", "
-            << seg[1] << " ])" << endl;
+            << seg[1] << " ])" << std::endl;
   }
-  cout << "Write " << pyFile << endl;
+  std::cout << "Write " << pyFile << std::endl;
 }
 
 //================================================================================
@@ -3543,8 +3871,9 @@ void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh,
  */
 //================================================================================
 
-NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh):
-  _copyOfLocalH(0)
+NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh,
+                                                  bool          checkRemovedElems):
+  _elementsRemoved( false ), _copyOfLocalH(0)
 {
   if ( ngMesh )
   {
@@ -3552,6 +3881,10 @@ NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh):
     _nbSegments = ngMesh->GetNSeg();
     _nbFaces    = ngMesh->GetNSE();
     _nbVolumes  = ngMesh->GetNE();
+
+    if ( checkRemovedElems )
+      for ( int i = 1; i <= ngMesh->GetNSE() &&  !_elementsRemoved; ++i )
+        _elementsRemoved = ngMesh->SurfaceElement(i).IsDeleted();
   }
   else
   {
@@ -3650,7 +3983,7 @@ NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh&         mesh,
       {
         _intShapes.insert( meshDS->ShapeToIndex( f.Current() ));
 
-        // egdes
+        // edges
         list< TopoDS_Shape > edges;
         for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next())
           if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 )
@@ -3942,6 +4275,18 @@ SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
   return const_cast<SMESH_Mesh&>( _mesh );
 }
 
+//================================================================================
+/*!
+ * \brief Access to a counter of NETGENPlugin_NetgenLibWrapper instances
+ */
+//================================================================================
+
+int& NETGENPlugin_NetgenLibWrapper::instanceCounter()
+{
+  static int theCouner = 0;
+  return theCouner;
+}
+
 //================================================================================
 /*!
  * \brief Initialize netgen library
@@ -3950,19 +4295,26 @@ SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
 
 NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper()
 {
-  Ng_Init();
+  if ( instanceCounter() == 0 )
+    Ng_Init();
+
+  ++instanceCounter();
 
   _isComputeOk      = false;
   _coutBuffer       = NULL;
+  _ngcout           = NULL;
+  _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_
-    cout << "NOTE: netgen output is redirected to file " << _outputFileName << endl;
+    std::cout << "NOTE: netgen output is redirected to file " << _outputFileName << std::endl;
 #else
     std::cout.rdbuf( netgen::mycout->rdbuf() );
 #endif
@@ -3979,9 +4331,11 @@ NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper()
 
 NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
 {
+  --instanceCounter();
+
   Ng_DeleteMesh( _ngMesh );
   Ng_Exit();
-  NETGENPlugin_Mesher::RemoveTmpFiles();
+  RemoveTmpFiles();
   if ( _coutBuffer )
     std::cout.rdbuf( _coutBuffer );
 #ifdef _DEBUG_
@@ -4027,6 +4381,26 @@ std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName()
   return aGenericName.ToCString();
 }
 
+//================================================================================
+/*!
+ * \brief Remove "test.out" and "problemfaces" files in current directory
+ */
+//================================================================================
+
+void NETGENPlugin_NetgenLibWrapper::RemoveTmpFiles()
+{
+  bool rm =  SMESH_File("test.out").remove() ;
+#ifndef WIN32
+  if ( rm && netgen::testout && instanceCounter() == 0 )
+  {
+    delete netgen::testout;
+    netgen::testout = 0;
+  }
+#endif
+  SMESH_File("problemfaces").remove();
+  SMESH_File("occmesh.rep").remove();
+}
+
 //================================================================================
 /*!
  * \brief Remove file with netgen output
@@ -4037,18 +4411,19 @@ void NETGENPlugin_NetgenLibWrapper::removeOutputFile()
 {
   if ( !_outputFileName.empty() )
   {
-    if ( netgen::mycout )
+    if ( _ngcout )
     {
       delete netgen::mycout;
-      netgen::mycout = 0;
-      netgen::myerr = 0;
+      netgen::mycout = _ngcout;
+      netgen::myerr  = _ngcerr;
+      _ngcout        = 0;
     }
     string    tmpDir = SALOMEDS_Tool::GetDirFromPath ( _outputFileName );
     string aFileName = SALOMEDS_Tool::GetNameFromPath( _outputFileName ) + ".out";
-    SALOMEDS::ListOfFileNames_var aFiles = new SALOMEDS::ListOfFileNames;
-    aFiles->length(1);
-    aFiles[0] = aFileName.c_str();
+    SALOMEDS_Tool::ListOfFiles aFiles;
+    aFiles.reserve(1);
+    aFiles.push_back(aFileName.c_str());
 
-    SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles.in(), true );
+    SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles, true );
   }
 }