Salome HOME
Merge branch V7_3_1_BR
[modules/smesh.git] / src / StdMeshers / StdMeshers_ViscousLayers2D.cxx
index 4e4d0ed8e28e716e8e9c84a69667af733c7ecac9..7e51343806582b8efe075c49f1ae779e1d08eeee 100644 (file)
@@ -1,9 +1,9 @@
-// Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
+// Copyright (C) 2007-2014  CEA/DEN, EDF R&D, OPEN CASCADE
 //
 // This library is free software; you can redistribute it and/or
 // modify it under the terms of the GNU Lesser General Public
 // License as published by the Free Software Foundation; either
-// version 2.1 of the License.
+// version 2.1 of the License, or (at your option) any later version.
 //
 // This library is distributed in the hope that it will be useful,
 // but WITHOUT ANY WARRANTY; without even the implied warranty of
 #include <TColStd_Array1OfReal.hxx>
 #include <TopExp.hxx>
 #include <TopExp_Explorer.hxx>
+#include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
 #include <TopTools_IndexedMapOfShape.hxx>
+#include <TopTools_ListIteratorOfListOfShape.hxx>
+#include <TopTools_ListOfShape.hxx>
 #include <TopTools_MapOfShape.hxx>
 #include <TopoDS.hxx>
 #include <TopoDS_Edge.hxx>
@@ -225,13 +228,17 @@ namespace VISCOUS_2D
 
     bool          _isBlocked;// is more inflation possible or not
 
-    gp_XY         _normal2D; // to pcurve
+    gp_XY         _normal2D; // to curve
     double        _len2dTo3dRatio; // to pass 2D <--> 3D
     gp_Ax2d       _ray;      // a ray starting at _uvOut
 
     vector<gp_XY> _uvRefined; // divisions by layers
 
     bool SetNewLength( const double length );
+
+#ifdef _DEBUG_
+    int           _ID;
+#endif
   };
   //--------------------------------------------------------------------------------
   /*!
@@ -272,13 +279,13 @@ namespace VISCOUS_2D
     }
     bool IsAdjacent( const _Segment& seg, const _LayerEdge* LE=0 ) const
     {
-      if ( LE && seg._indexInLine < _lEdges.size() &&
-           ( seg._uv[0] == & LE->_uvIn ||
-             seg._uv[1] == & LE->_uvIn ))
-        return true;
+      if ( LE /*&& seg._indexInLine < _lEdges.size()*/ )
+        return ( seg._uv[0] == & LE->_uvIn ||
+                 seg._uv[1] == & LE->_uvIn );
       return ( & seg == &_leftLine->_segments.back() ||
                & seg == &_rightLine->_segments[0] );
     }
+    bool IsConcave() const;
   };
   //--------------------------------------------------------------------------------
   /*!
@@ -293,6 +300,7 @@ namespace VISCOUS_2D
 
     bool Compute(const _Segment& seg1, const _Segment& seg2, bool seg2IsRay = false )
     {
+      // !!! If seg2IsRay, returns true at any _param2 !!!
       const double eps = 1e-10;
       _vec1  = seg1.p2() - seg1.p1(); 
       _vec2  = seg2.p2() - seg2.p1(); 
@@ -303,10 +311,8 @@ namespace VISCOUS_2D
       _param1 = _vec2.Crossed(_vec21) / _D; 
       if (_param1 < -eps || _param1 > 1 + eps )
         return false;
-      _param2 = _vec1.Crossed(_vec21) / _D; 
-      if (_param2 < -eps || ( !seg2IsRay && _param2 > 1 + eps ))
-        return false;
-      return true;
+      _param2 = _vec1.Crossed(_vec21) / _D;
+      return seg2IsRay || ( _param2 > -eps && _param2 < 1 + eps );
     }
     bool Compute( const _Segment& seg1, const gp_Ax2d& ray )
     {
@@ -332,11 +338,11 @@ namespace VISCOUS_2D
                       const StdMeshers_ViscousLayers2D* theHyp);
     SMESH_ComputeErrorPtr GetError() const { return _error; }
     // does it's job
-    SMESH_ProxyMesh::Ptr  Compute();
+    SMESH_ProxyMesh::Ptr  Compute(const TopoDS_Shape& theShapeHypAssignedTo);
 
   private:
 
-    bool findEdgesWithLayers();
+    bool findEdgesWithLayers(const TopoDS_Shape& theShapeHypAssignedTo);
     bool makePolyLines();
     bool inflate();
     bool fixCollisions();
@@ -347,10 +353,13 @@ namespace VISCOUS_2D
                               const TopoDS_Edge& E,
                               const TopoDS_Vertex& V);
     void setLenRatio( _LayerEdge& LE, const gp_Pnt& pOut );
-    void setLayerEdgeData( _LayerEdge&           lEdge,
-                           const double          u,
-                           Handle(Geom2d_Curve)& pcurve,
-                           const bool            reverse);
+    void setLayerEdgeData( _LayerEdge&                 lEdge,
+                           const double                u,
+                           Handle(Geom2d_Curve)&       pcurve,
+                           Handle(Geom_Curve)&         curve,
+                           const gp_Pnt                pOut,
+                           const bool                  reverse,
+                           GeomAPI_ProjectPointOnSurf* faceProj);
     void adjustCommonEdge( _PolyLine& LL, _PolyLine& LR );
     void calcLayersHeight(const double    totalThick,
                           vector<double>& heights);
@@ -379,6 +388,8 @@ namespace VISCOUS_2D
     SMESH_MesherHelper          _helper;
     TSideVector                 _faceSideVec; // wires (StdMeshers_FaceSide) of _face
     vector<_PolyLine>           _polyLineVec; // fronts to advance
+    bool                        _is2DIsotropic; // is same U and V resoulution of _face
+    vector<TopoDS_Face>         _clearedFaces; // FACEs whose mesh was removed by shrink()
 
     double                      _fPowN; // to compute thickness of layers
     double                      _thickness; // required or possible layers thickness
@@ -391,6 +402,7 @@ namespace VISCOUS_2D
     // are inflated along such EDGEs but then such _LayerEdge's are turned into
     // a node on VERTEX, i.e. all nodes on a _LayerEdge are melded into one node.
     
+    int                         _nbLE; // for DEBUG
   };
 
   //================================================================================
@@ -398,15 +410,60 @@ namespace VISCOUS_2D
    * \brief Returns StdMeshers_ViscousLayers2D for the FACE
    */
   const StdMeshers_ViscousLayers2D* findHyp(SMESH_Mesh&        theMesh,
-                                            const TopoDS_Face& theFace)
+                                            const TopoDS_Face& theFace,
+                                            TopoDS_Shape*      assignedTo=0)
   {
     SMESH_HypoFilter hypFilter
       ( SMESH_HypoFilter::HasName( StdMeshers_ViscousLayers2D::GetHypType() ));
     const SMESH_Hypothesis * hyp =
-      theMesh.GetHypothesis( theFace, hypFilter, /*ancestors=*/true );
+      theMesh.GetHypothesis( theFace, hypFilter, /*ancestors=*/true, assignedTo );
     return dynamic_cast< const StdMeshers_ViscousLayers2D* > ( hyp );
   }
 
+  //================================================================================
+  /*!
+   * \brief Returns ids of EDGEs not to create Viscous Layers on
+   *  \param [in] theHyp - the hypothesis, holding edges either to ignore or not to.
+   *  \param [in] theFace - the FACE whose EDGEs are checked.
+   *  \param [in] theMesh - the mesh.
+   *  \param [in,out] theEdgeIds - container returning EDGEs to ignore.
+   *  \return int - number of found EDGEs of the FACE.
+   */
+  //================================================================================
+
+  int getEdgesToIgnore( const StdMeshers_ViscousLayers2D* theHyp,
+                        const TopoDS_Shape&               theFace,
+                        const SMESHDS_Mesh*               theMesh,
+                        set< int > &                      theEdgeIds)
+  {
+    int nbToEdgesIgnore = 0;
+    vector<TGeomID> ids = theHyp->GetBndShapes();
+    if ( theHyp->IsToIgnoreShapes() ) // EDGEs to ignore are given
+    {
+      for ( size_t i = 0; i < ids.size(); ++i )
+      {
+        const TopoDS_Shape& E = theMesh->IndexToShape( ids[i] );
+        if ( !E.IsNull() &&
+             E.ShapeType() == TopAbs_EDGE &&
+             SMESH_MesherHelper::IsSubShape( E, theFace ))
+        {
+          theEdgeIds.insert( ids[i] );
+          ++nbToEdgesIgnore;
+        }
+      }
+    }
+    else // EDGEs to make the Viscous Layers on are given
+    {
+      TopExp_Explorer E( theFace, TopAbs_EDGE );
+      for ( ; E.More(); E.Next(), ++nbToEdgesIgnore )
+        theEdgeIds.insert( theMesh->ShapeToIndex( E.Current() ));
+
+      for ( size_t i = 0; i < ids.size(); ++i )
+        nbToEdgesIgnore -= theEdgeIds.erase( ids[i] );
+    }
+    return nbToEdgesIgnore;
+  }
+
 } // namespace VISCOUS_2D
 
 //================================================================================
@@ -432,17 +489,18 @@ StdMeshers_ViscousLayers2D::Compute(SMESH_Mesh&        theMesh,
 {
   SMESH_ProxyMesh::Ptr pm;
 
-  const StdMeshers_ViscousLayers2D* vlHyp = VISCOUS_2D::findHyp( theMesh, theFace );
+  TopoDS_Shape hypAssignedTo;
+  const StdMeshers_ViscousLayers2D* vlHyp = VISCOUS_2D::findHyp( theMesh, theFace, &hypAssignedTo );
   if ( vlHyp )
   {
     VISCOUS_2D::_ViscousBuilder2D builder( theMesh, theFace, vlHyp );
-    pm = builder.Compute();
+    pm = builder.Compute( hypAssignedTo );
     SMESH_ComputeErrorPtr error = builder.GetError();
     if ( error && !error->IsOK() )
       theMesh.GetSubMesh( theFace )->GetComputeError() = error;
     else if ( !pm )
       pm.reset( new SMESH_ProxyMesh( theMesh ));
-    if ( getenv("ONLY_VL2D"))
+    if ( getenv("__ONLY__VL2D__"))
       pm.reset();
   }
   else
@@ -495,13 +553,15 @@ _ViscousBuilder2D::_ViscousBuilder2D(SMESH_Mesh&                       theMesh,
   _mesh( &theMesh ), _face( theFace ), _hyp( theHyp ), _helper( theMesh )
 {
   _helper.SetSubShape( _face );
-  _helper.SetElementsOnShape(true);
+  _helper.SetElementsOnShape( true );
 
-  //_face.Orientation( TopAbs_FORWARD );
+  _face.Orientation( TopAbs_FORWARD ); // 2D logic works only in this case
   _surface = BRep_Tool::Surface( _face );
 
   if ( _hyp )
     _fPowN = pow( _hyp->GetStretchFactor(), _hyp->GetNumberLayers() );
+
+  _nbLE = 0;
 }
 
 //================================================================================
@@ -512,7 +572,6 @@ _ViscousBuilder2D::_ViscousBuilder2D(SMESH_Mesh&                       theMesh,
 
 bool _ViscousBuilder2D::error(const string& text )
 {
-  cout << "_ViscousBuilder2D::error " << text << endl;
   _error->myName    = COMPERR_ALGO_FAILED;
   _error->myComment = string("Viscous layers builder 2D: ") + text;
   if ( SMESH_subMesh* sm = _mesh->GetSubMesh( _face ) )
@@ -522,8 +581,9 @@ bool _ViscousBuilder2D::error(const string& text )
       _error->myAlgo = smError->myAlgo;
     smError = _error;
   }
-  //makeGroupOfLE(); // debug
-
+#ifdef _DEBUG_
+  cout << "_ViscousBuilder2D::error " << text << endl;
+#endif
   return false;
 }
 
@@ -533,14 +593,14 @@ bool _ViscousBuilder2D::error(const string& text )
  */
 //================================================================================
 
-SMESH_ProxyMesh::Ptr _ViscousBuilder2D::Compute()
+SMESH_ProxyMesh::Ptr _ViscousBuilder2D::Compute(const TopoDS_Shape& theShapeHypAssignedTo)
 {
   _error       = SMESH_ComputeError::New(COMPERR_OK);
   _faceSideVec = StdMeshers_FaceSide::GetFaceWires( _face, *_mesh, true, _error );
   if ( !_error->IsOK() )
     return _proxyMesh;
 
-  if ( !findEdgesWithLayers() ) // analysis of a shape
+  if ( !findEdgesWithLayers(theShapeHypAssignedTo) ) // analysis of a shape
     return _proxyMesh;
 
   if ( ! makePolyLines() ) // creation of fronts
@@ -569,19 +629,19 @@ SMESH_ProxyMesh::Ptr _ViscousBuilder2D::Compute()
  */
 //================================================================================
 
-bool _ViscousBuilder2D::findEdgesWithLayers()
+bool _ViscousBuilder2D::findEdgesWithLayers(const TopoDS_Shape& theShapeHypAssignedTo)
 {
   // collect all EDGEs to ignore defined by hyp
-  int nbMyEdgesIgnored = 0;
-  vector<TGeomID> ids = _hyp->GetBndShapesToIgnore();
-  for ( size_t i = 0; i < ids.size(); ++i )
-  {
-    const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[i] );
-    if ( !s.IsNull() && s.ShapeType() == TopAbs_EDGE ) {
-      _ignoreShapeIds.insert( ids[i] );
-      nbMyEdgesIgnored += ( _helper.IsSubShape( s, _face ));
-    }
-  }
+  int nbMyEdgesIgnored = getEdgesToIgnore( _hyp, _face, getMeshDS(), _ignoreShapeIds );
+
+  // get all shared EDGEs
+  TopTools_MapOfShape sharedEdges;
+  TopTools_IndexedDataMapOfShapeListOfShape facesOfEdgeMap;
+  TopExp::MapShapesAndAncestors( theShapeHypAssignedTo,
+                                 TopAbs_EDGE, TopAbs_FACE, facesOfEdgeMap);
+  for ( int iE = 1; iE <= facesOfEdgeMap.Extent(); ++iE )
+    if ( facesOfEdgeMap( iE ).Extent() > 1 )
+      sharedEdges.Add( facesOfEdgeMap.FindKey( iE ));
 
   // check all EDGEs of the _face
   int totalNbEdges = 0;
@@ -590,32 +650,34 @@ bool _ViscousBuilder2D::findEdgesWithLayers()
     StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
     totalNbEdges += wire->NbEdges();
     for ( int iE = 0; iE < wire->NbEdges(); ++iE )
-      if ( _helper.NbAncestors( wire->Edge( iE ), *_mesh, TopAbs_FACE ) > 1 )
+    {
+      if ( sharedEdges.Contains( wire->Edge( iE )))
       {
         // ignore internal EDGEs (shared by several FACEs)
-        TGeomID edgeID = getMeshDS()->ShapeToIndex( wire->Edge( iE ));
+        const TGeomID edgeID = wire->EdgeID( iE );
         _ignoreShapeIds.insert( edgeID );
 
         // check if ends of an EDGE are to be added to _noShrinkVert
-        PShapeIteratorPtr faceIt = _helper.GetAncestors( wire->Edge( iE ), *_mesh, TopAbs_FACE );
-        while ( const TopoDS_Shape* neighbourFace = faceIt->next() )
+        const TopTools_ListOfShape& faceList = facesOfEdgeMap.FindFromKey( wire->Edge( iE ));
+        TopTools_ListIteratorOfListOfShape faceIt( faceList );
+        for ( ; faceIt.More(); faceIt.Next() )
         {
-          if ( neighbourFace->IsSame( _face )) continue;
-          SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *neighbourFace );
+          const TopoDS_Shape& neighbourFace = faceIt.Value();
+          if ( neighbourFace.IsSame( _face )) continue;
+          SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, neighbourFace );
           if ( !algo ) continue;
 
           const StdMeshers_ViscousLayers2D* viscHyp = 0;
           const list <const SMESHDS_Hypothesis *> & allHyps =
-            algo->GetUsedHypothesis(*_mesh, *neighbourFace, /*noAuxiliary=*/false);
+            algo->GetUsedHypothesis(*_mesh, neighbourFace, /*noAuxiliary=*/false);
           list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
           for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
             viscHyp = dynamic_cast<const StdMeshers_ViscousLayers2D*>( *hyp );
 
           set<TGeomID> neighbourIgnoreEdges;
-          if (viscHyp) {
-            vector<TGeomID> ids = _hyp->GetBndShapesToIgnore();
-            neighbourIgnoreEdges.insert( ids.begin(), ids.end() );
-          }
+          if (viscHyp)
+            getEdgesToIgnore( viscHyp, neighbourFace, getMeshDS(), neighbourIgnoreEdges );
+
           for ( int iV = 0; iV < 2; ++iV )
           {
             TopoDS_Vertex vertex = iV ? wire->LastVertex(iE) : wire->FirstVertex(iE);
@@ -626,19 +688,39 @@ bool _ViscousBuilder2D::findEdgesWithLayers()
               PShapeIteratorPtr edgeIt = _helper.GetAncestors( vertex, *_mesh, TopAbs_EDGE );
               while ( const TopoDS_Shape* edge = edgeIt->next() )
                 if ( !edge->IsSame( wire->Edge( iE )) &&
-                     neighbourIgnoreEdges.count( getMeshDS()->ShapeToIndex( *edge )))
+                     _helper.IsSubShape( *edge, neighbourFace ) &&
+                     ( neighbourIgnoreEdges.count( getMeshDS()->ShapeToIndex( *edge )) ||
+                       sharedEdges.Contains( *edge )))
+                {
                   _noShrinkVert.insert( getMeshDS()->ShapeToIndex( vertex ));
+                  break;
+                }
             }
           }
         }
       }
+    }
+  }
+
+  // add VERTEXes w/o layers to _ignoreShapeIds (this is used by toShrinkForAdjacent())
+  for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
+  {
+    StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
+    for ( int iE = 0; iE < wire->NbEdges(); ++iE )
+    {
+      TGeomID edge1 = wire->EdgeID( iE );
+      TGeomID edge2 = wire->EdgeID( iE+1 );
+      if ( _ignoreShapeIds.count( edge1 ) && _ignoreShapeIds.count( edge2 ))
+        _ignoreShapeIds.insert( getMeshDS()->ShapeToIndex( wire->LastVertex( iE )));
+    }
   }
+
   return ( nbMyEdgesIgnored < totalNbEdges );
 }
 
 //================================================================================
 /*!
- * \brief Create the inner front of the viscous layers and prepare data for infation
+ * \brief Create the inner front of the viscous layers and prepare data for inflation
  */
 //================================================================================
 
@@ -649,9 +731,35 @@ bool _ViscousBuilder2D::makePolyLines()
   // count total nb of EDGEs to allocate _polyLineVec
   int nbEdges = 0;
   for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
-    nbEdges += _faceSideVec[ iWire ]->NbEdges();
+  {
+    StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
+    nbEdges += wire->NbEdges();
+    if ( wire->GetUVPtStruct().empty() && wire->NbPoints() > 0 )
+      return error("Invalid node parameters on some EDGE");
+  }
   _polyLineVec.resize( nbEdges );
 
+  // check if 2D normal should be computed by 3D one by means of projection
+  GeomAPI_ProjectPointOnSurf* faceProj = 0;
+  TopLoc_Location loc;
+  {
+    _LayerEdge tmpLE;
+    const UVPtStruct& uv = _faceSideVec[0]->GetUVPtStruct()[0];
+    gp_Pnt p = SMESH_TNodeXYZ( uv.node );
+    tmpLE._uvOut.SetCoord( uv.u, uv.v );
+    tmpLE._normal2D.SetCoord( 1., 0. );
+    setLenRatio( tmpLE, p );
+    const double r1 = tmpLE._len2dTo3dRatio;
+    tmpLE._normal2D.SetCoord( 0., 1. );
+    setLenRatio( tmpLE, p );
+    const double r2 = tmpLE._len2dTo3dRatio;
+    // projection is needed if two _len2dTo3dRatio's differ too much
+    const double maxR = Max( r2, r1 );
+    if ( Abs( r2-r1 )/maxR > 0.2*maxR )
+      faceProj = & _helper.GetProjector( _face, loc );
+  }
+  _is2DIsotropic = !faceProj;
+
   // Assign data to _PolyLine's
   // ---------------------------
 
@@ -660,8 +768,6 @@ bool _ViscousBuilder2D::makePolyLines()
   {
     StdMeshers_FaceSidePtr      wire = _faceSideVec[ iWire ];
     const vector<UVPtStruct>& points = wire->GetUVPtStruct();
-    if ( points.empty() && wire->NbPoints() > 0 )
-      return error("Invalid node parameters on some EDGE");
     int iPnt = 0;
     for ( int iE = 0; iE < wire->NbEdges(); ++iE )
     {
@@ -684,23 +790,29 @@ bool _ViscousBuilder2D::makePolyLines()
       // TODO: add more _LayerEdge's to strongly curved EDGEs
       // in order not to miss collisions
 
+      double u; gp_Pnt p;
+      Handle(Geom_Curve)   curve  = BRep_Tool::Curve( L._wire->Edge( iE ), loc, u, u );
       Handle(Geom2d_Curve) pcurve = L._wire->Curve2d( L._edgeInd );
       const bool reverse = (( L._wire->Edge( iE ).Orientation() == TopAbs_REVERSED ) ^
                             (_face.Orientation()                == TopAbs_REVERSED ));
       for ( int i = L._firstPntInd; i <= L._lastPntInd; ++i )
       {
         _LayerEdge& lEdge = L._lEdges[ i - L._firstPntInd ];
-        const double u = ( i == L._firstPntInd ? wire->FirstU(iE) : points[ i ].param );
-        setLayerEdgeData( lEdge, u, pcurve, reverse );
-        setLenRatio( lEdge, SMESH_TNodeXYZ( points[ i ].node ) );
+        u = ( i == L._firstPntInd ? wire->FirstU(iE) : points[ i ].param );
+        p = SMESH_TNodeXYZ( points[ i ].node );
+        setLayerEdgeData( lEdge, u, pcurve, curve, p, reverse, faceProj );
+        setLenRatio( lEdge, p );
       }
-      if ( L._lastPntInd - L._firstPntInd + 1 < 3 ) // add 3d _LayerEdge in the middle
+      if ( L._lastPntInd - L._firstPntInd + 1 < 3 ) // add 3-d _LayerEdge in the middle
       {
         L._lEdges[2] = L._lEdges[1];
-        const double u = 0.5 * ( wire->FirstU(iE) + wire->LastU(iE) );
-        setLayerEdgeData( L._lEdges[1], u, pcurve, reverse );
-        gp_Pnt p = 0.5 * ( SMESH_TNodeXYZ( points[ L._firstPntInd ].node ) +
-                           SMESH_TNodeXYZ( points[ L._lastPntInd ].node ));
+        u = 0.5 * ( wire->FirstU(iE) + wire->LastU(iE) );
+        if ( !curve.IsNull() )
+          p = curve->Value( u );
+        else
+          p = 0.5 * ( SMESH_TNodeXYZ( points[ L._firstPntInd ].node ) +
+                      SMESH_TNodeXYZ( points[ L._lastPntInd ].node ));
+        setLayerEdgeData( L._lEdges[1], u, pcurve, curve, p, reverse, faceProj );
         setLenRatio( L._lEdges[1], p );
       }
     }
@@ -767,13 +879,13 @@ bool _ViscousBuilder2D::makePolyLines()
             {
               double  distToL2 = intersection._param2 / L1._lEdges[iLE]._len2dTo3dRatio;
               double psblThick = distToL2 / ( 1 + L1._advancable + L2._advancable );
-              if ( maxPossibleThick < psblThick )
-                maxPossibleThick = psblThick;
+              maxPossibleThick = Max( psblThick, maxPossibleThick );
             }
         }
       }
     }
-    _thickness = Min( _hyp->GetTotalThickness(), maxPossibleThick );
+    if ( maxPossibleThick > 0. )
+      _thickness = Min( _hyp->GetTotalThickness(), maxPossibleThick );
   }
 
   // Adjust _LayerEdge's at _PolyLine's extremities
@@ -818,8 +930,8 @@ bool _ViscousBuilder2D::makePolyLines()
   for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
   {
     lineBoxes[ iPoLine ] = *_polyLineVec[ iPoLine ]._segTree->getBox();
-    if ( _polyLineVec[ iPoLine ]._advancable )
-      lineBoxes[ iPoLine ].Enlarge( maxLen2dTo3dRatio * _thickness * 2 );
+    lineBoxes[ iPoLine ].Enlarge( maxLen2dTo3dRatio * _thickness * 
+                                  ( _polyLineVec[ iPoLine ]._advancable ? 2. : 1.2 ));
   }
   // _reachableLines
   for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
@@ -962,15 +1074,18 @@ void _ViscousBuilder2D::adjustCommonEdge( _PolyLine& LL, _PolyLine& LR )
           lastIntersection._param1 = intersection._param1;
           lastIntersection._param2 = intersection._param2;
         }
-        if ( iLE >= L._lEdges.size () - 1 )
+        if ( iLE >= L._lEdges.size() - 1 )
         {
           // all _LayerEdge's intersect the segCommon, limit inflation
-          // of remaining 2 _LayerEdge's
+          // of remaining 3 _LayerEdge's
           vector< _LayerEdge > newEdgeVec( Min( 3, L._lEdges.size() ));
           newEdgeVec.front() = L._lEdges.front();
           newEdgeVec.back()  = L._lEdges.back();
           if ( newEdgeVec.size() == 3 )
-            newEdgeVec[1] = L._lEdges[ L._lEdges.size() / 2 ];
+          {
+            newEdgeVec[1] = L._lEdges[ isR ? (L._lEdges.size() - 2) : 1 ];
+            newEdgeVec[1]._len2dTo3dRatio *= lastIntersection._param2;
+          }
           L._lEdges.swap( newEdgeVec );
           if ( !isR ) std::swap( lastIntersection._param1 , lastIntersection._param2 );
           L._lEdges.front()._len2dTo3dRatio *= lastIntersection._param1; // ??
@@ -1013,22 +1128,52 @@ void _ViscousBuilder2D::adjustCommonEdge( _PolyLine& LL, _PolyLine& LR )
  */
 //================================================================================
 
-void _ViscousBuilder2D::setLayerEdgeData( _LayerEdge&           lEdge,
-                                          const double          u,
-                                          Handle(Geom2d_Curve)& pcurve,
-                                          const bool            reverse)
+void _ViscousBuilder2D::setLayerEdgeData( _LayerEdge&                 lEdge,
+                                          const double                u,
+                                          Handle(Geom2d_Curve)&       pcurve,
+                                          Handle(Geom_Curve)&         curve,
+                                          const gp_Pnt                pOut,
+                                          const bool                  reverse,
+                                          GeomAPI_ProjectPointOnSurf* faceProj)
 {
-  gp_Pnt2d uv; gp_Vec2d tangent;
-  pcurve->D1( u, uv, tangent );
-  tangent.Normalize();
-  if ( reverse )
-    tangent.Reverse();
+  gp_Pnt2d uv;
+  if ( faceProj && !curve.IsNull() )
+  {
+    uv = pcurve->Value( u );
+    gp_Vec tangent; gp_Pnt p; gp_Vec du, dv;
+    curve->D1( u, p, tangent );
+    if ( reverse )
+      tangent.Reverse();
+    _surface->D1( uv.X(), uv.Y(), p, du, dv );
+    gp_Vec faceNorm = du ^ dv;
+    gp_Vec normal   = faceNorm ^ tangent;
+    normal.Normalize();
+    p = pOut.XYZ() + normal.XYZ() * /*1e-2 * */_hyp->GetTotalThickness() / _hyp->GetNumberLayers();
+    faceProj->Perform( p );
+    if ( !faceProj->IsDone() || faceProj->NbPoints() < 1 )
+      return setLayerEdgeData( lEdge, u, pcurve, curve, p, reverse, NULL );
+    Quantity_Parameter U,V;
+    faceProj->LowerDistanceParameters(U,V);
+    lEdge._normal2D.SetCoord( U - uv.X(), V - uv.Y() );
+    lEdge._normal2D.Normalize();
+  }
+  else
+  {
+    gp_Vec2d tangent;
+    pcurve->D1( u, uv, tangent );
+    tangent.Normalize();
+    if ( reverse )
+      tangent.Reverse();
+    lEdge._normal2D.SetCoord( -tangent.Y(), tangent.X() );
+  }
   lEdge._uvOut = lEdge._uvIn = uv.XY();
-  lEdge._normal2D.SetCoord( -tangent.Y(), tangent.X() );
-  lEdge._ray.SetLocation( lEdge._uvOut );
+  lEdge._ray.SetLocation ( lEdge._uvOut );
   lEdge._ray.SetDirection( lEdge._normal2D );
   lEdge._isBlocked = false;
   lEdge._length2D  = 0;
+#ifdef _DEBUG_
+  lEdge._ID        = _nbLE++;
+#endif
 }
 
 //================================================================================
@@ -1079,7 +1224,7 @@ bool _ViscousBuilder2D::inflate()
           {
             double distToL2 = intersection._param2 / L1._lEdges[iLE]._len2dTo3dRatio;
             double     size = distToL2 / ( 1 + L1._advancable + L2._advancable );
-            if ( size < minSize )
+            if ( 1e-10 < size && size < minSize )
               minSize = size;
             if ( size > maxSize )
               maxSize = size;
@@ -1196,7 +1341,6 @@ bool _ViscousBuilder2D::fixCollisions()
 {
   // look for intersections of _Segment's by intersecting _LayerEdge's with
   // _Segment's
-  //double maxStep = 0, minStep = 1e+100;
   vector< const _Segment* > foundSegs;
   _SegmentIntersection intersection;
 
@@ -1225,10 +1369,10 @@ bool _ViscousBuilder2D::fixCollisions()
             double         newLen2D = dist2DToL2 / 2;
             if ( newLen2D < 1.1 * LE1._length2D ) // collision!
             {
-              if ( newLen2D < LE1._length2D )
+              if ( newLen2D > 0 || !L1._advancable )
               {
                 blockedEdgesList.push_back( &LE1 );
-                if ( L1._advancable )
+                if ( L1._advancable && newLen2D > 0 )
                 {
                   edgeLenLimitList.push_back( make_pair( &LE1, newLen2D ));
                   blockedEdgesList.push_back( &L2._lEdges[ foundSegs[i]->_indexInLine     ]);
@@ -1236,14 +1380,16 @@ bool _ViscousBuilder2D::fixCollisions()
                 }
                 else // here dist2DToL2 < 0 and LE1._length2D == 0
                 {
-                  _LayerEdge LE2[2] = { L2._lEdges[ foundSegs[i]->_indexInLine     ],
-                                        L2._lEdges[ foundSegs[i]->_indexInLine + 1 ] };
-                  _Segment outSeg2( LE2[0]._uvOut, LE2[1]._uvOut );
+                  _LayerEdge* LE2[2] = { & L2._lEdges[ foundSegs[i]->_indexInLine     ],
+                                         & L2._lEdges[ foundSegs[i]->_indexInLine + 1 ] };
+                  _Segment outSeg2( LE2[0]->_uvOut, LE2[1]->_uvOut );
                   intersection.Compute( outSeg2, LE1._ray );
                   newLen2D = intersection._param2 / 2;
-
-                  edgeLenLimitList.push_back( make_pair( &LE2[0], newLen2D ));
-                  edgeLenLimitList.push_back( make_pair( &LE2[1], newLen2D ));
+                  if ( newLen2D > 0 )
+                  {
+                    edgeLenLimitList.push_back( make_pair( LE2[0], newLen2D ));
+                    edgeLenLimitList.push_back( make_pair( LE2[1], newLen2D ));
+                  }
                 }
               }
             }
@@ -1253,12 +1399,52 @@ bool _ViscousBuilder2D::fixCollisions()
     }
   }
 
+  // limit length of _LayerEdge's that are extrema of _PolyLine's
+  // to avoid intersection of these _LayerEdge's
+  for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
+  {
+    _PolyLine& L = _polyLineVec[ iL1 ];
+    if ( L._lEdges.size() < 4 ) // all intermediate _LayerEdge's intersect with extremum ones
+    {
+      _LayerEdge& LEL = L._leftLine->_lEdges.back();
+      _LayerEdge& LER = L._lEdges.back();
+      _Segment segL( LEL._uvOut, LEL._uvIn );
+      _Segment segR( LER._uvOut, LER._uvIn );
+      double newLen2DL, newLen2DR;
+      if ( intersection.Compute( segL, LER._ray ))
+      {
+        newLen2DR = intersection._param2 / 2;
+        newLen2DL = LEL._length2D * intersection._param1 / 2;
+      }
+      else if ( intersection.Compute( segR, LEL._ray ))
+      {
+        newLen2DL = intersection._param2 / 2;
+        newLen2DR = LER._length2D * intersection._param1 / 2;
+      }
+      else
+      {
+        continue;
+      }
+      if ( newLen2DL > 0 && newLen2DR > 0 )
+      {
+        if ( newLen2DL < 1.1 * LEL._length2D )
+          edgeLenLimitList.push_back( make_pair( &LEL, newLen2DL ));
+        if ( newLen2DR < 1.1 * LER._length2D )
+          edgeLenLimitList.push_back( make_pair( &LER, newLen2DR ));
+      }
+    }
+  }
+
   // set limited length to _LayerEdge's
   list< pair< _LayerEdge*, double > >::iterator edge2Len = edgeLenLimitList.begin();
   for ( ; edge2Len != edgeLenLimitList.end(); ++edge2Len )
   {
     _LayerEdge* LE = edge2Len->first;
-    LE->SetNewLength( edge2Len->second / LE->_len2dTo3dRatio );
+    if ( LE->_length2D > edge2Len->second )
+    {
+      LE->_isBlocked = false;
+      LE->SetNewLength( edge2Len->second / LE->_len2dTo3dRatio );
+    }
     LE->_isBlocked = true;
   }
 
@@ -1302,10 +1488,19 @@ bool _ViscousBuilder2D::shrink()
     if ( nbAdvancable == 0 )
       continue;
 
-    const TopoDS_Edge&        E = L._wire->Edge      ( L._edgeInd );
-    const int            edgeID = L._wire->EdgeID    ( L._edgeInd );
-    const double        edgeLen = L._wire->EdgeLength( L._edgeInd );
-    Handle(Geom2d_Curve) pcurve = L._wire->Curve2d   ( L._edgeInd );
+    const TopoDS_Vertex&  V1 = L._wire->FirstVertex( L._edgeInd );
+    const TopoDS_Vertex&  V2 = L._wire->LastVertex ( L._edgeInd );
+    const int           v1ID = getMeshDS()->ShapeToIndex( V1 );
+    const int           v2ID = getMeshDS()->ShapeToIndex( V2 );
+    const bool isShrinkableL = ! _noShrinkVert.count( v1ID ) && L._leftLine->_advancable;
+    const bool isShrinkableR = ! _noShrinkVert.count( v2ID ) && L._rightLine->_advancable;
+    if ( !isShrinkableL && !isShrinkableR )
+      continue;
+
+    const TopoDS_Edge&        E = L._wire->Edge       ( L._edgeInd );
+    const int            edgeID = L._wire->EdgeID     ( L._edgeInd );
+    const double        edgeLen = L._wire->EdgeLength ( L._edgeInd );
+    Handle(Geom2d_Curve) pcurve = L._wire->Curve2d    ( L._edgeInd );
     const bool     edgeReversed = ( E.Orientation() == TopAbs_REVERSED );
 
     SMESH_MesherHelper helper( *_mesh ); // to create nodes and edges on E
@@ -1321,10 +1516,12 @@ bool _ViscousBuilder2D::shrink()
       {
         adjFace = TopoDS::Face( *f );
         SMESH_ProxyMesh::Ptr pm = _ProxyMeshHolder::FindProxyMeshOfFace( adjFace, *_mesh );
-        if ( !pm || pm->NbProxySubMeshes() == 0 )
+        if ( !pm || pm->NbProxySubMeshes() == 0 /*|| !pm->GetProxySubMesh( E )*/)
         {
           // There are no viscous layers on an adjacent FACE, clear it's 2D mesh
           removeMeshFaces( adjFace );
+          // if ( removeMeshFaces( adjFace ))
+          //   _clearedFaces.push_back( adjFace ); // to re-compute after all
         }
         else
         {
@@ -1334,7 +1531,7 @@ bool _ViscousBuilder2D::shrink()
           //
           const vector<UVPtStruct>& points = L._wire->GetUVPtStruct();
           int iPFrom = L._firstPntInd, iPTo = L._lastPntInd;
-          if ( L._leftLine->_advancable )
+          if ( isShrinkableL )
           {
             vector<gp_XY>& uvVec = L._lEdges.front()._uvRefined;
             for ( int i = 0; i < _hyp->GetNumberLayers(); ++i ) {
@@ -1343,7 +1540,7 @@ bool _ViscousBuilder2D::shrink()
               uvVec.push_back ( pcurve->Value( uvPt.param ).XY() );
             }
           }
-          if ( L._rightLine->_advancable )
+          if ( isShrinkableR )
           {
             vector<gp_XY>& uvVec = L._lEdges.back()._uvRefined;
             for ( int i = 0; i < _hyp->GetNumberLayers(); ++i ) {
@@ -1354,8 +1551,8 @@ bool _ViscousBuilder2D::shrink()
           }
           // make proxy sub-mesh data of present nodes
           //
-          if ( L._leftLine->_advancable )  iPFrom += _hyp->GetNumberLayers();
-          if ( L._rightLine->_advancable ) iPTo   -= _hyp->GetNumberLayers();
+          if ( isShrinkableL ) iPFrom += _hyp->GetNumberLayers();
+          if ( isShrinkableR ) iPTo   -= _hyp->GetNumberLayers();
           UVPtStructVec nodeDataVec( & points[ iPFrom ], & points[ iPTo + 1 ]);
 
           double normSize = nodeDataVec.back().normParam - nodeDataVec.front().normParam;
@@ -1427,6 +1624,8 @@ bool _ViscousBuilder2D::shrink()
       if ( !L2->_advancable &&
            !toShrinkForAdjacent( adjFace, E, L._wire->FirstVertex( L._edgeInd + isR )))
         continue;
+      if ( isR ? !isShrinkableR : !isShrinkableL )
+        continue;
 
       double & u = isR ? u2 : u1; // param to move
       double  u0 = isR ? ul : uf; // init value of the param to move
@@ -1463,17 +1662,17 @@ bool _ViscousBuilder2D::shrink()
           length1D = Abs( u - curveInt.Point( 1 ).ParamOnFirst() );
           double maxDist2d = 2 * L2->_lEdges[ iLSeg2 ]._length2D;
           isConvex = ( length1D < maxDist2d * len1dTo2dRatio );
-                                                  /*  |L  seg2     
-                                                   *  |  o---o--- 
-                                                   *  | /    |    
-                                                   *  |/     |  L2
-                                                   *  x------x---      */
+          /*                                          |L  seg2
+           *                                          |  o---o---
+           *                                          | /    |
+           *                                          |/     |  L2
+           *                                          x------x---      */
         }
-        if ( !isConvex ) { /* concave VERTEX */   /*  o-----o--- 
-                                                   *   \    |    
+        if ( !isConvex ) { /* concave VERTEX */   /*  o-----o---
+                                                   *   \    |
                                                    *    \   |  L2
-                                                   *     x--x--- 
-                                                   *    /        
+                                                   *     x--x---
+                                                   *    /
                                                    * L /               */
           length2D = L2->_lEdges[ iFSeg2 ]._length2D;
           //if ( L2->_advancable ) continue;
@@ -1559,7 +1758,7 @@ bool _ViscousBuilder2D::shrink()
       {
         const SMDS_MeshElement* segment = segIt->next();
         if ( segment->getshapeId() != edgeID ) continue;
-        
+
         const int nbNodes = segment->NbNodes();
         for ( int i = 0; i < nbNodes; ++i )
         {
@@ -1630,16 +1829,16 @@ bool _ViscousBuilder2D::shrink()
       }
       // concatenate nodeDataVec and nodeDataForAdjacent
       nodeDataVec.insert(( isRShrinkedForAdjacent ? nodeDataVec.end() : nodeDataVec.begin() ),
-                          nodeDataForAdjacent.begin(), nodeDataForAdjacent.end() );
+                         nodeDataForAdjacent.begin(), nodeDataForAdjacent.end() );
     }
 
     // Extend nodeDataVec by a node located at the end of not shared _LayerEdge
     /*      n - to add to nodeDataVec
-     *      o-----o--- 
-     *      |\    |    
+     *      o-----o---
+     *      |\    |
      *      | o---o---
      *      | |x--x--- L2
-     *      | /        
+     *      | /
      *      |/ L
      *      x
      *     /    */
@@ -1677,7 +1876,7 @@ bool _ViscousBuilder2D::shrink()
       nodeDataVec.insert(( isR ? nodeDataVec.end() : nodeDataVec.begin() ), ptOfNode );
 
       // recompute normParam of nodes in nodeDataVec
-      newLength = GCPnts_AbscissaPoint::Length( curve, 
+      newLength = GCPnts_AbscissaPoint::Length( curve,
                                                 nodeDataVec.front().param,
                                                 nodeDataVec.back().param);
       for ( size_t iP = 1; iP < nodeDataVec.size(); ++iP )
@@ -1713,11 +1912,15 @@ bool _ViscousBuilder2D::toShrinkForAdjacent( const TopoDS_Face&   adjFace,
                                              const TopoDS_Edge&   E,
                                              const TopoDS_Vertex& V)
 {
-  if ( const StdMeshers_ViscousLayers2D* vlHyp = findHyp( *_mesh, adjFace ))
+  if ( _noShrinkVert.count( getMeshDS()->ShapeToIndex( V )))
+    return false;
+
+  TopoDS_Shape hypAssignedTo;
+  if ( const StdMeshers_ViscousLayers2D* vlHyp = findHyp( *_mesh, adjFace, &hypAssignedTo ))
   {
     VISCOUS_2D::_ViscousBuilder2D builder( *_mesh, adjFace, vlHyp );
     builder._faceSideVec = StdMeshers_FaceSide::GetFaceWires( adjFace, *_mesh, true, _error );
-    builder.findEdgesWithLayers();
+    builder.findEdgesWithLayers( hypAssignedTo );
 
     PShapeIteratorPtr edgeIt = _helper.GetAncestors( V, *_mesh, TopAbs_EDGE );
     while ( const TopoDS_Shape* edgeAtV = edgeIt->next() )
@@ -1732,7 +1935,7 @@ bool _ViscousBuilder2D::toShrinkForAdjacent( const TopoDS_Face&   adjFace,
   }
   return false;
 }
-  
+
 //================================================================================
 /*!
  * \brief Make faces
@@ -1741,6 +1944,10 @@ bool _ViscousBuilder2D::toShrinkForAdjacent( const TopoDS_Face&   adjFace,
 
 bool _ViscousBuilder2D::refine()
 {
+  // find out orientation of faces to create
+  bool isReverse = 
+    ( _helper.GetSubShapeOri( _mesh->GetShapeToMesh(), _face ) == TopAbs_REVERSED );
+
   // store a proxyMesh in a sub-mesh
   // make faces on each _PolyLine
   vector< double > layersHeight;
@@ -1751,18 +1958,18 @@ bool _ViscousBuilder2D::refine()
     if ( !L._advancable ) continue;
 
     // replace an inactive (1st) _LayerEdge with an active one of a neighbour _PolyLine
-    size_t iLE = 0, nbLE = L._lEdges.size();
+    //size_t iLE = 0, nbLE = L._lEdges.size();
     const bool leftEdgeShared  = L.IsCommonEdgeShared( *L._leftLine );
     const bool rightEdgeShared = L.IsCommonEdgeShared( *L._rightLine );
     if ( /*!L._leftLine->_advancable &&*/ leftEdgeShared )
     {
       L._lEdges[0] = L._leftLine->_lEdges.back();
-      iLE += int( !L._leftLine->_advancable );
+      //iLE += int( !L._leftLine->_advancable );
     }
     if ( !L._rightLine->_advancable && rightEdgeShared )
     {
       L._lEdges.back() = L._rightLine->_lEdges[0];
-      --nbLE;
+      //--nbLE;
     }
 
     // limit length of neighbour _LayerEdge's to avoid sharp change of layers thickness
@@ -1778,20 +1985,21 @@ bool _ViscousBuilder2D::refine()
     {
       size_t iF = 0, iL = L._lEdges.size()-1;
       size_t *i = isR ? &iL : &iF;
-      //size_t iRef = *i;
       _LayerEdge* prevLE = & L._lEdges[ *i ];
       double weight = 0;
       for ( ++iF, --iL; iF < L._lEdges.size()-1; ++iF, --iL )
       {
         _LayerEdge& LE = L._lEdges[*i];
-        if ( prevLE->_length2D > 0 ) {
+        if ( prevLE->_length2D > 0 )
+        {
           gp_XY tangent ( LE._normal2D.Y(), -LE._normal2D.X() );
           weight += Abs( tangent * ( prevLE->_uvIn - LE._uvIn )) / segLen.back();
-          gp_XY prevTang = ( LE._uvOut - prevLE->_uvOut );
-          gp_XY prevNorm    = gp_XY( -prevTang.Y(), prevTang.X() );
-          double prevProj   = prevNorm * ( prevLE->_uvIn - prevLE->_uvOut );
+          // gp_XY prevTang( LE._uvOut - prevLE->_uvOut );
+          // gp_XY prevNorm( -prevTang.Y(), prevTang.X() );
+          gp_XY prevNorm = LE._normal2D;
+          double prevProj = prevNorm * ( prevLE->_uvIn - prevLE->_uvOut );
           if ( prevProj > 0 ) {
-            prevProj /= prevTang.Modulus();
+            prevProj /= prevNorm.Modulus();
             if ( LE._length2D < prevProj )
               weight += 0.75 * ( 1 - weight ); // length decrease is more preferable
             LE._length2D  = weight * LE._length2D + ( 1 - weight ) * prevProj;
@@ -1801,8 +2009,13 @@ bool _ViscousBuilder2D::refine()
         prevLE = & LE;
       }
     }
+    // DEBUG:  to see _uvRefined. cout can be redirected to hide NETGEN output
+    // cerr << "import smesh" << endl << "mesh = smesh.Mesh()"<< endl;
 
-    // calculate intermediate UV on _LayerEdge's ( _LayerEdge::_uvRefined )
+    // calculate intermediate UV on _LayerEdge's ( _LayerEdge::_uvRefined )   
+    size_t iLE = 0, nbLE = L._lEdges.size();
+    if ( ! L._lEdges[0]._uvRefined.empty() )     ++iLE;
+    if ( ! L._lEdges.back()._uvRefined.empty() ) --nbLE;
     for ( ; iLE < nbLE; ++iLE )
     {
       _LayerEdge& LE = L._lEdges[iLE];
@@ -1813,13 +2026,21 @@ bool _ViscousBuilder2D::refine()
       }
       for ( size_t i = 0; i < layersHeight.size(); ++i )
         LE._uvRefined.push_back( LE._uvOut + LE._normal2D * layersHeight[i] );
+
+      // DEBUG:  to see _uvRefined
+      // for ( size_t i = 0; i < LE._uvRefined.size(); ++i )
+      // {
+      //   gp_XY uv = LE._uvRefined[i];
+      //   gp_Pnt p = _surface->Value( uv.X(), uv.Y() );
+      //   cerr << "mesh.AddNode( " << p.X() << ", "  << p.Y() << ", "  << p.Z() << " )" << endl;
+      // }
     }
 
     // nodes to create 1 layer of faces
     vector< const SMDS_MeshNode* > outerNodes( L._lastPntInd - L._firstPntInd + 1 );
     vector< const SMDS_MeshNode* > innerNodes( L._lastPntInd - L._firstPntInd + 1 );
 
-    // initialize outerNodes by node on the L._wire
+    // initialize outerNodes by nodes of the L._wire
     const vector<UVPtStruct>& points = L._wire->GetUVPtStruct();
     for ( int i = L._firstPntInd; i <= L._lastPntInd; ++i )
       outerNodes[ i-L._firstPntInd ] = points[i].node;
@@ -1834,24 +2055,45 @@ bool _ViscousBuilder2D::refine()
       normPar[ i - L._firstPntInd ] = ( points[i].normParam - normF ) / normDist;
 
     // Create layers of faces
-
-    bool hasLeftNode  = ( !L._leftLine->_rightNodes.empty() && leftEdgeShared  );
-    bool hasRightNode = ( !L._rightLine->_leftNodes.empty() && rightEdgeShared );
+    
+    const TopoDS_Vertex&  V1 = L._wire->FirstVertex( L._edgeInd );
+    const TopoDS_Vertex&  V2 = L._wire->LastVertex ( L._edgeInd );
+    const int           v1ID = getMeshDS()->ShapeToIndex( V1 );
+    const int           v2ID = getMeshDS()->ShapeToIndex( V2 );
+    const bool isShrinkableL = ! _noShrinkVert.count( v1ID );
+    const bool isShrinkableR = ! _noShrinkVert.count( v2ID );
+
+    bool hasLeftNode     = ( !L._leftLine->_rightNodes.empty() && leftEdgeShared  );
+    bool hasRightNode    = ( !L._rightLine->_leftNodes.empty() && rightEdgeShared );
     bool hasOwnLeftNode  = ( !L._leftNodes.empty() );
     bool hasOwnRightNode = ( !L._rightNodes.empty() );
+    bool isClosedEdge    = ( outerNodes.front() == outerNodes.back() );
     size_t iS,
-      iN0 = ( hasLeftNode || hasOwnLeftNode || _polyLineVec.size() == 1 ),
-      nbN = innerNodes.size() - ( hasRightNode || hasOwnRightNode );
+      iN0 = ( hasLeftNode || hasOwnLeftNode || isClosedEdge || !isShrinkableL ),
+      nbN = innerNodes.size() - ( hasRightNode || hasOwnRightNode || !isShrinkableR);
     L._leftNodes .reserve( _hyp->GetNumberLayers() );
     L._rightNodes.reserve( _hyp->GetNumberLayers() );
+    int cur = 0, prev = -1; // to take into account orientation of _face
+    if ( isReverse ) std::swap( cur, prev );
     for ( int iF = 0; iF < _hyp->GetNumberLayers(); ++iF ) // loop on layers of faces
     {
       // get accumulated length of intermediate segments
-      for ( iS = 1; iS < segLen.size(); ++iS )
-      {
-        double sLen = (L._lEdges[iS-1]._uvRefined[iF] - L._lEdges[iS]._uvRefined[iF] ).Modulus();
-        segLen[iS] = segLen[iS-1] + sLen;
-      }
+      if ( _is2DIsotropic )
+        for ( iS = 1; iS < segLen.size(); ++iS )
+        {
+          double sLen = (L._lEdges[iS-1]._uvRefined[iF] - L._lEdges[iS]._uvRefined[iF] ).Modulus();
+          segLen[iS] = segLen[iS-1] + sLen;
+        }
+      else
+        for ( iS = 1; iS < segLen.size(); ++iS )
+        {
+          const gp_XY& uv1 = L._lEdges[iS-1]._uvRefined[iF];
+          const gp_XY& uv2 = L._lEdges[iS  ]._uvRefined[iF];
+          gp_Pnt p1 = _surface->Value( uv1.X(), uv1.Y() );
+          gp_Pnt p2 = _surface->Value( uv2.X(), uv2.Y() );
+          double sLen = p1.Distance( p2 );
+          segLen[iS] = segLen[iS-1] + sLen;
+        }
       // normalize the accumulated length
       for ( iS = 1; iS < segLen.size(); ++iS )
         segLen[iS] /= segLen.back();
@@ -1872,15 +2114,16 @@ bool _ViscousBuilder2D::refine()
       else if ( hasLeftNode )  innerNodes.front() = L._leftLine->_rightNodes[ iF ];
       if ( hasOwnRightNode )   innerNodes.back()  = L._rightNodes[ iF ];
       else if ( hasRightNode ) innerNodes.back()  = L._rightLine->_leftNodes[ iF ];
-      if ( _polyLineVec.size() == 1 ) innerNodes.front() = innerNodes.back(); // circle
-      if ( !hasOwnLeftNode )  L._leftNodes.push_back( innerNodes.front() );
-      if ( !hasOwnRightNode ) L._rightNodes.push_back( innerNodes.back() );
+      if ( isClosedEdge )      innerNodes.front() = innerNodes.back(); // circle
+      if ( !isShrinkableL )    innerNodes.front() = outerNodes.front();
+      if ( !isShrinkableR )    innerNodes.back()  = outerNodes.back();
+      if ( !hasOwnLeftNode )   L._leftNodes.push_back( innerNodes.front() );
+      if ( !hasOwnRightNode )  L._rightNodes.push_back( innerNodes.back() );
 
       // create faces
-      // TODO care of orientation
       for ( size_t i = 1; i < innerNodes.size(); ++i )
-        if ( SMDS_MeshElement* f = _helper.AddFace( outerNodes[ i-1 ], outerNodes[ i ],
-                                                    innerNodes[ i ],   innerNodes[ i-1 ]))
+        if ( SMDS_MeshElement* f = _helper.AddFace( outerNodes[ i+prev ], outerNodes[ i+cur ],
+                                                    innerNodes[ i+cur  ], innerNodes[ i+prev ]))
           L._newFaces.insert( L._newFaces.end(), f );
 
       outerNodes.swap( innerNodes );
@@ -1897,11 +2140,14 @@ bool _ViscousBuilder2D::refine()
         continue;
 
       for ( size_t i = 1; i < lNodes.size(); ++i )
-        _helper.AddFace( lNodes[ i-1 ], rNodes[ i-1 ],
-                         rNodes[ i ],   lNodes[ i ]);
+        _helper.AddFace( lNodes[ i+prev ], rNodes[ i+prev ],
+                         rNodes[ i+cur ],  lNodes[ i+cur ]);
 
       const UVPtStruct& ptOnVertex = points[ isR ? L._lastPntInd : L._firstPntInd ];
-      _helper.AddFace( ptOnVertex.node, rNodes[ 0 ], lNodes[ 0 ]);
+      if ( isReverse )
+        _helper.AddFace( ptOnVertex.node, lNodes[ 0 ], rNodes[ 0 ]);
+      else
+        _helper.AddFace( ptOnVertex.node, rNodes[ 0 ], lNodes[ 0 ]);
     }
 
     // Fill the _ProxyMeshOfFace
@@ -1927,6 +2173,14 @@ bool _ViscousBuilder2D::refine()
 
   } // loop on _PolyLine's
 
+  // re-compute FACEs whose mesh was removed by shrink()
+  for ( size_t i = 0; i < _clearedFaces.size(); ++i )
+  {
+    SMESH_subMesh* sm = _mesh->GetSubMesh( _clearedFaces[i] );
+    if ( sm->GetComputeState() == SMESH_subMesh::READY_TO_COMPUTE )
+      sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
+  }
+
   return true;
 }
 
@@ -2087,6 +2341,24 @@ bool _PolyLine::IsCommonEdgeShared( const _PolyLine& other )
   return false;
 }
 
+//================================================================================
+/*!
+ * \brief Return \c true if the EDGE of this _PolyLine is concave
+ */
+//================================================================================
+
+bool _PolyLine::IsConcave() const
+{
+  if ( _lEdges.size() < 2 )
+    return false;
+
+  gp_Vec2d v1( _lEdges[0]._uvOut, _lEdges[1]._uvOut );
+  gp_Vec2d v2( _lEdges[0]._uvOut, _lEdges[2]._uvOut );
+  const double size2 = v2.Magnitude();
+
+  return ( v1 ^ v2 ) / size2 < -1e-3 * size2;
+}
+
 //================================================================================
 /*!
  * \brief Constructor of SegmentTree