Salome HOME
IPAL52557: TC7.5.0: default value in Hypothesis is different in new and saved studies
[modules/smesh.git] / src / StdMeshers / StdMeshers_ViscousLayers.cxx
index 685b141fe09831619318af086650c4caebf9b845..704144d7a6d3a5c74f9315050c0640226ff920a7 100644 (file)
@@ -44,6 +44,7 @@
 #include "SMESH_subMeshEventListener.hxx"
 #include "StdMeshers_FaceSide.hxx"
 
+#include <Adaptor3d_HSurface.hxx>
 #include <BRepAdaptor_Curve2d.hxx>
 #include <BRepAdaptor_Surface.hxx>
 #include <BRepLProp_SLProps.hxx>
@@ -75,6 +76,8 @@
 #include <TopoDS_Face.hxx>
 #include <TopoDS_Vertex.hxx>
 #include <gp_Ax1.hxx>
+#include <gp_Cone.hxx>
+#include <gp_Sphere.hxx>
 #include <gp_Vec.hxx>
 #include <gp_XY.hxx>
 
 #include <cmath>
 #include <limits>
 
+#ifdef _DEBUG_
 //#define __myDEBUG
+//#define __NOT_INVALIDATE_BAD_SMOOTH
+#endif
 
 using namespace std;
 
@@ -95,6 +101,16 @@ namespace VISCOUS_3D
   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
 
   const double theMinSmoothCosin = 0.1;
+  const double theSmoothThickToElemSizeRatio = 0.3;
+
+  // what part of thickness is allowed till intersection
+  // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
+  const double theThickToIntersection = 1.5;
+
+  bool needSmoothing( double cosin, double tgtThick, double elemSize )
+  {
+    return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
+  }
 
   /*!
    * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
@@ -103,7 +119,8 @@ namespace VISCOUS_3D
   struct _MeshOfSolid : public SMESH_ProxyMesh,
                         public SMESH_subMeshEventListenerData
   {
-    bool _n2nMapComputed;
+    bool                  _n2nMapComputed;
+    SMESH_ComputeErrorPtr _warning;
 
     _MeshOfSolid( SMESH_Mesh* mesh)
       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
@@ -167,7 +184,8 @@ namespace VISCOUS_3D
                               SMESH_subMeshEventListenerData* data,
                               const SMESH_Hypothesis*         hyp)
     {
-      if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
+      if ( SMESH_subMesh::COMPUTE_EVENT       == eventType &&
+           SMESH_subMesh::CHECK_COMPUTE_STATE != event)
       {
         // delete SMESH_ProxyMesh containing temporary faces
         subMesh->DeleteEventListener( this );
@@ -222,6 +240,7 @@ namespace VISCOUS_3D
       sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
     }
   }
+  struct _SolidData;
   //--------------------------------------------------------------------------------
   /*!
    * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
@@ -237,19 +256,19 @@ namespace VISCOUS_3D
              const SMDS_MeshNode* nNext=0,
              const SMDS_MeshNode* nOpp=0)
       : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
-    bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
+    bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt, double& vol) const
     {
       const double M[3][3] =
         {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
          { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
          { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
-      double determinant = ( + M[0][0]*M[1][1]*M[2][2]
-                             + M[0][1]*M[1][2]*M[2][0]
-                             + M[0][2]*M[1][0]*M[2][1]
-                             - M[0][0]*M[1][2]*M[2][1]
-                             - M[0][1]*M[1][0]*M[2][2]
-                             - M[0][2]*M[1][1]*M[2][0]);
-      return determinant > 1e-100;
+      vol = ( + M[0][0]*M[1][1]*M[2][2]
+              + M[0][1]*M[1][2]*M[2][0]
+              + M[0][2]*M[1][0]*M[2][1]
+              - M[0][0]*M[1][2]*M[2][1]
+              - M[0][1]*M[1][0]*M[2][2]
+              - M[0][2]*M[1][1]*M[2][0]);
+      return vol > 1e-100;
     }
     bool IsForward(const gp_XY&         tgtUV,
                    const SMDS_MeshNode* smoothedNode,
@@ -267,6 +286,12 @@ namespace VISCOUS_3D
     {
       return _nPrev == other._nNext || _nNext == other._nPrev;
     }
+    static void GetSimplices( const SMDS_MeshNode* node,
+                              vector<_Simplex>&   simplices,
+                              const set<TGeomID>& ingnoreShapes,
+                              const _SolidData*   dataToCheckOri = 0,
+                              const bool          toSort = false);
+    static void SortSimplices(vector<_Simplex>& simplices);
   };
   //--------------------------------------------------------------------------------
   /*!
@@ -295,30 +320,12 @@ namespace VISCOUS_3D
     double lenDelta(double len) const { return _k * ( _r + len ); }
     double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
   };
-  struct _LayerEdge;
   //--------------------------------------------------------------------------------
-  /*!
-   * Structure used to smooth a _LayerEdge (master) based on an EDGE.
-   */
-  struct _2NearEdges
-  {
-    // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
-    const SMDS_MeshNode* _nodes[2];
-    // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
-    //gp_XYZ               _vec[2];
-    double               _wgt[2]; // weights of _nodes
-    _LayerEdge*          _edges[2];
 
-     // normal to plane passing through _LayerEdge._normal and tangent of EDGE
-    gp_XYZ*              _plnNorm;
+  struct _2NearEdges;
+  struct _LayerEdge;
+  typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
 
-    _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
-    void reverse() {
-      std::swap( _nodes[0], _nodes[1] );
-      std::swap( _wgt  [0], _wgt  [1] );
-      std::swap( _edges[0], _edges[1] );
-    }
-  };
   //--------------------------------------------------------------------------------
   /*!
    * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
@@ -326,6 +333,8 @@ namespace VISCOUS_3D
    */
   struct _LayerEdge
   {
+    typedef gp_XYZ (_LayerEdge::*PSmooFun)();
+
     vector< const SMDS_MeshNode*> _nodes;
 
     gp_XYZ              _normal; // to solid surface
@@ -339,6 +348,7 @@ namespace VISCOUS_3D
     // simplices connected to the source node (_nodes[0]);
     // used for smoothing and quality check of _LayerEdge's based on the FACE
     vector<_Simplex>    _simplices;
+    PSmooFun            _smooFunction; // smoothing function
     // data for smoothing of _LayerEdge's based on the EDGE
     _2NearEdges*        _2neibors;
 
@@ -353,7 +363,9 @@ namespace VISCOUS_3D
                              const SMDS_MeshNode* n2,
                              SMESH_MesherHelper&  helper);
     void InvalidateStep( int curStep, bool restoreLength=false );
-    bool Smooth(int& badNb);
+    void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
+                            const TNode2Edge&     n2eMap);
+    int  Smooth(const int step, const bool isConcaveFace, const bool findBest);
     bool SmoothOnEdge(Handle(Geom_Surface)& surface,
                       const TopoDS_Face&    F,
                       SMESH_MesherHelper&   helper);
@@ -368,10 +380,35 @@ namespace VISCOUS_3D
                        double&              dist,
                        const double&        epsilon) const;
     gp_Ax1 LastSegment(double& segLen) const;
+    gp_XY  LastUV( const TopoDS_Face& F ) const;
     bool   IsOnEdge() const { return _2neibors; }
     gp_XYZ Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
     void   SetCosin( double cosin );
+    int    NbSteps() const { return _pos.size() - 1; } // nb inlation steps
+
+    gp_XYZ smoothLaplacian();
+    gp_XYZ smoothAngular();
+    gp_XYZ smoothLengthWeighted();
+    gp_XYZ smoothCentroidal();
+    gp_XYZ smoothNefPolygon();
+
+    enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
+    static const int theNbSmooFuns = FUN_NB;
+    static PSmooFun _funs[theNbSmooFuns];
+    static const char* _funNames[theNbSmooFuns+1];
+    int smooFunID( PSmooFun fun=0) const;
   };
+  _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
+                                                            &_LayerEdge::smoothLengthWeighted,
+                                                            &_LayerEdge::smoothCentroidal,
+                                                            &_LayerEdge::smoothNefPolygon,
+                                                            &_LayerEdge::smoothAngular };
+  const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
+                                                         "LengthWeighted",
+                                                         "Centroidal",
+                                                         "NefPolygon",
+                                                         "Angular",
+                                                         "None"};
   struct _LayerEdgeCmp
   {
     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
@@ -381,6 +418,53 @@ namespace VISCOUS_3D
     }
   };
   //--------------------------------------------------------------------------------
+  /*!
+   * A 2D half plane used by _LayerEdge::smoothNefPolygon()
+   */
+  struct _halfPlane
+  {
+    gp_XY _pos, _dir, _inNorm;
+    bool IsOut( const gp_XY p, const double tol ) const
+    {
+      return _inNorm * ( p - _pos ) < -tol;
+    }
+    bool FindInterestion( const _halfPlane& hp, gp_XY & intPnt )
+    {
+      const double eps = 1e-10;
+      double D = _dir.Crossed( hp._dir );
+      if ( fabs(D) < std::numeric_limits<double>::min())
+        return false;
+      gp_XY vec21 = _pos - hp._pos; 
+      double u = hp._dir.Crossed( vec21 ) / D; 
+      intPnt = _pos + _dir * u;
+      return true;
+    }
+  };
+  //--------------------------------------------------------------------------------
+  /*!
+   * Structure used to smooth a _LayerEdge based on an EDGE.
+   */
+  struct _2NearEdges
+  {
+    double               _wgt  [2]; // weights of _nodes
+    _LayerEdge*          _edges[2];
+
+     // normal to plane passing through _LayerEdge._normal and tangent of EDGE
+    gp_XYZ*              _plnNorm;
+
+    _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
+    const SMDS_MeshNode* tgtNode(bool is2nd) {
+      return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
+    }
+    const SMDS_MeshNode* srcNode(bool is2nd) {
+      return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
+    }
+    void reverse() {
+      std::swap( _wgt  [0], _wgt  [1] );
+      std::swap( _edges[0], _edges[1] );
+    }
+  };
+  //--------------------------------------------------------------------------------
   /*!
    * \brief Convex FACE whose radius of curvature is less than the thickness of 
    *        layers. It is used to detect distortion of prisms based on a convex
@@ -406,30 +490,60 @@ namespace VISCOUS_3D
   };
 
   //--------------------------------------------------------------------------------
+  /*!
+   * \brief Layers parameters got by averaging several hypotheses
+   */
+  struct AverageHyp
+  {
+    AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
+      :_nbLayers(0), _nbHyps(0), _thickness(0), _stretchFactor(0)
+    {
+      Add( hyp );
+    }
+    void Add( const StdMeshers_ViscousLayers* hyp )
+    {
+      if ( hyp )
+      {
+        _nbHyps++;
+        _nbLayers       = hyp->GetNumberLayers();
+        //_thickness     += hyp->GetTotalThickness();
+        _thickness      = Max( _thickness, hyp->GetTotalThickness() );
+        _stretchFactor += hyp->GetStretchFactor();
+      }
+    }
+    double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
+    double GetStretchFactor()  const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
+    int    GetNumberLayers()   const { return _nbLayers; }
+  private:
+    int     _nbLayers, _nbHyps;
+    double  _thickness, _stretchFactor;
+  };
 
-  typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
-  
   //--------------------------------------------------------------------------------
   /*!
    * \brief Data of a SOLID
    */
   struct _SolidData
   {
+    typedef const StdMeshers_ViscousLayers* THyp;
     TopoDS_Shape                    _solid;
-    const StdMeshers_ViscousLayers* _hyp;
-    TopoDS_Shape                    _hypShape;
+    TGeomID                         _index; // SOLID id
     _MeshOfSolid*                   _proxyMesh;
-    set<TGeomID>                    _reversedFaceIds;
-    set<TGeomID>                    _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDS
+    list< THyp >                    _hyps;
+    list< TopoDS_Shape >            _hypShapes;
+    map< TGeomID, THyp >            _face2hyp; // filled if _hyps.size() > 1
+    set< TGeomID >                  _reversedFaceIds;
+    set< TGeomID >                  _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
 
-    double                          _stepSize, _stepSizeCoeff;
+    double                          _stepSize, _stepSizeCoeff, _geomSize;
     const SMDS_MeshNode*            _stepSizeNodes[2];
 
-    TNode2Edge                      _n2eMap;
+    TNode2Edge                      _n2eMap; // nodes and _LayerEdge's based on them
+
     // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
     map< TGeomID, TNode2Edge* >     _s2neMap;
     // edges of _n2eMap. We keep same data in two containers because
-    // iteration over the map is 5 time longer than over the vector
+    // iteration over the map is 5 times longer than over the vector
     vector< _LayerEdge* >           _edges;
 
     // key:   an id of shape (EDGE or VERTEX) shared by a FACE with
@@ -441,8 +555,9 @@ namespace VISCOUS_3D
     // Convex FACEs whose radius of curvature is less than the thickness of layers
     map< TGeomID, _ConvexFace >      _convexFaces;
 
-    // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
-    set< TGeomID >                   _noShrinkFaces;
+    // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
+    // the adjacent SOLID
+    set< TGeomID >                   _noShrinkShapes;
 
     // <EDGE to smooth on> to <it's curve> -- for analytic smooth
     map< TGeomID,Handle(Geom_Curve)> _edge2curve;
@@ -450,30 +565,34 @@ namespace VISCOUS_3D
     // end indices in _edges of _LayerEdge on each shape, first go shapes to smooth
     vector< int >                    _endEdgeOnShape;
     int                              _nbShapesToSmooth;
+    set< TGeomID >                   _concaveFaces;
 
-    double                           _epsilon; // precision for SegTriaInter()
+    // data of averaged StdMeshers_ViscousLayers parameters for each shape with _LayerEdge's
+    vector< AverageHyp >             _hypOnShape;
+    double                           _maxThickness; // of all _hyps
+    double                           _minThickness; // of all _hyps
 
-    int                              _index; // for debug
+    double                           _epsilon; // precision for SegTriaInter()
 
-    _SolidData(const TopoDS_Shape&             s=TopoDS_Shape(),
-               const StdMeshers_ViscousLayers* h=0,
-               const TopoDS_Shape&             hs=TopoDS_Shape(),
-               _MeshOfSolid*                   m=0)
-      :_solid(s), _hyp(h), _hypShape(hs), _proxyMesh(m) {}
+    _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
+               _MeshOfSolid*       m=0)
+      :_solid(s), _proxyMesh(m) {}
     ~_SolidData();
 
     Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&    E,
                                        const int             iFrom,
                                        const int             iTo,
-                                       Handle(Geom_Surface)& surface,
                                        const TopoDS_Face&    F,
-                                       SMESH_MesherHelper&   helper);
+                                       SMESH_MesherHelper&   helper,
+                                       vector<_LayerEdge* >* edges=0);
 
     void SortOnEdge( const TopoDS_Edge&  E,
                      const int           iFrom,
                      const int           iTo,
                      SMESH_MesherHelper& helper);
 
+    void Sort2NeiborsOnEdge( const int iFrom, const int iTo);
+
     _ConvexFace* GetConvexFace( const TGeomID faceID )
     {
       map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
@@ -485,9 +604,14 @@ namespace VISCOUS_3D
       iEnd = _endEdgeOnShape[ end ];
     }
 
-    bool GetShapeEdges(const TGeomID shapeID, size_t& edgeEnd, int* iBeg=0, int* iEnd=0 ) const;
+    bool GetShapeEdges(const TGeomID shapeID, size_t& iEdgeEnd, int* iBeg=0, int* iEnd=0 ) const;
 
     void AddShapesToSmooth( const set< TGeomID >& shapeIDs );
+
+    void PrepareEdgesToSmoothOnFace( _LayerEdge**       edgeBeg,
+                                     _LayerEdge**       edgeEnd,
+                                     const TopoDS_Face& face,
+                                     bool               substituteSrcNodes );
   };
   //--------------------------------------------------------------------------------
   /*!
@@ -552,6 +676,9 @@ namespace VISCOUS_3D
     // does it's job
     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
                                   const TopoDS_Shape& shape);
+    // check validity of hypotheses
+    SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh&         mesh,
+                                           const TopoDS_Shape& shape );
 
     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
     void RestoreListeners();
@@ -562,7 +689,11 @@ namespace VISCOUS_3D
   private:
 
     bool findSolidsWithLayers();
-    bool findFacesWithLayers();
+    bool findFacesWithLayers(const bool onlyWith=false);
+    void getIgnoreFaces(const TopoDS_Shape&             solid,
+                        const StdMeshers_ViscousLayers* hyp,
+                        const TopoDS_Shape&             hypShape,
+                        set<TGeomID>&                   ignoreFaces);
     bool makeLayer(_SolidData& data);
     bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
                      SMESH_MesherHelper& helper, _SolidData& data);
@@ -571,19 +702,20 @@ namespace VISCOUS_3D
                          SMESH_MesherHelper&  helper,
                          bool&                isOK,
                          bool                 shiftInside=false);
-    gp_XYZ getWeigthedNormal( const SMDS_MeshNode*         n,
-                              std::pair< TGeomID, gp_XYZ > fId2Normal[],
-                              const int                    nbFaces );
+    bool getFaceNormalAtSingularity(const gp_XY&        uv,
+                                    const TopoDS_Face&  face,
+                                    SMESH_MesherHelper& helper,
+                                    gp_Dir&             normal );
+    gp_XYZ getWeigthedNormal( const SMDS_MeshNode*             n,
+                              std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
+                              int                              nbFaces );
     bool findNeiborsOnEdge(const _LayerEdge*     edge,
                            const SMDS_MeshNode*& n1,
                            const SMDS_MeshNode*& n2,
                            _SolidData&           data);
-    void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
-                       const set<TGeomID>& ingnoreShapes,
-                       const _SolidData*   dataToCheckOri = 0,
-                       const bool          toSort = false);
     void findSimplexTestEdges( _SolidData&                    data,
                                vector< vector<_LayerEdge*> >& edgesByGeom);
+    void computeGeomSize( _SolidData& data );
     bool sortEdges( _SolidData&                    data,
                     vector< vector<_LayerEdge*> >& edgesByGeom);
     void limitStepSizeByCurvature( _SolidData&  data );
@@ -608,6 +740,7 @@ namespace VISCOUS_3D
     bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
                               SMESH_MesherHelper& helper,
                               const SMESHDS_SubMesh* faceSubMesh );
+    void restoreNoShrink( _LayerEdge& edge ) const;
     void fixBadFaces(const TopoDS_Face&          F,
                      SMESH_MesherHelper&         helper,
                      const bool                  is2D,
@@ -616,7 +749,7 @@ namespace VISCOUS_3D
     bool addBoundaryElements();
 
     bool error( const string& text, int solidID=-1 );
-    SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
+    SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
 
     // debug
     void makeGroupOfLE();
@@ -659,7 +792,8 @@ namespace VISCOUS_3D
     virtual SMDSAbs_ElementType  GetType() const              { return SMDSAbs_Face; }
     virtual vtkIdType GetVtkType() const                      { return -1; }
     virtual SMDSAbs_EntityType   GetEntityType() const        { return SMDSEntity_Last; }
-    virtual SMDSAbs_GeometryType GetGeomType() const          { return SMDSGeom_TRIANGLE; }
+    virtual SMDSAbs_GeometryType GetGeomType() const
+    { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
     virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
     { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
   };
@@ -717,6 +851,7 @@ namespace VISCOUS_3D
       return _surface->Value( uv.X(), uv.Y() ).XYZ();
     }
   };
+
 } // namespace VISCOUS_3D
 
 
@@ -776,6 +911,14 @@ StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
           return SMESH_ProxyMesh::Ptr();
       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
+
+      if ( pm->_warning && !pm->_warning->IsOK() )
+      {
+        SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
+        SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
+        if ( !smError || smError->IsOK() )
+          smError = pm->_warning;
+      }
     }
     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
   }
@@ -817,11 +960,32 @@ bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
 {
   // TODO
   return false;
+} // --------------------------------------------------------------------------------
+SMESH_ComputeErrorPtr
+StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh&                          theMesh,
+                                          const TopoDS_Shape&                  theShape,
+                                          SMESH_Hypothesis::Hypothesis_Status& theStatus)
+{
+  VISCOUS_3D::_ViscousBuilder bulder;
+  SMESH_ComputeErrorPtr err = bulder.CheckHypotheses( theMesh, theShape );
+  if ( err && !err->IsOK() )
+    theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
+  else
+    theStatus = SMESH_Hypothesis::HYP_OK;
+
+  return err;
+}
+// --------------------------------------------------------------------------------
+bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
+{
+  bool isIn =
+    ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
+  return IsToIgnoreShapes() ? !isIn : isIn;
 }
 // END StdMeshers_ViscousLayers hypothesis
 //================================================================================
 
-namespace
+namespace VISCOUS_3D
 {
   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
   {
@@ -842,22 +1006,32 @@ namespace
     gp_Vec dir;
     double f,l; gp_Pnt p;
     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
+    if ( c.IsNull() ) return gp_XYZ( 1e100, 1e100, 1e100 );
     double u = helper.GetNodeU( E, atNode );
     c->D1( u, p, dir );
     return dir.XYZ();
   }
   //--------------------------------------------------------------------------------
+  gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
+                     const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
+                     double* cosin=0);
+  //--------------------------------------------------------------------------------
   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
   {
+    double f,l;
+    Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
+    if ( c.IsNull() )
+    {
+      TopoDS_Vertex v = helper.IthVertex( 0, fromE );
+      return getFaceDir( F, v, node, helper, ok );
+    }
     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
     gp_Pnt p; gp_Vec du, dv, norm;
     surface->D1( uv.X(),uv.Y(), p, du,dv );
     norm = du ^ dv;
 
-    double f,l;
-    Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
     double u = helper.GetNodeU( fromE, node, 0, &ok );
     c->D1( u, p, du );
     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
@@ -881,7 +1055,7 @@ namespace
   //--------------------------------------------------------------------------------
   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
-                     bool& ok, double* cosin=0)
+                     bool& ok, double* cosin)
   {
     TopoDS_Face faceFrw = F;
     faceFrw.Orientation( TopAbs_FORWARD );
@@ -897,12 +1071,12 @@ namespace
         if ( SMESH_Algo::isDegenerated( e )) continue;
         TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
         if ( VV[1].IsSame( fromV )) {
+          nbEdges += edges[ 0 ].IsNull();
           edges[ 0 ] = e;
-          nbEdges++;
         }
         else if ( VV[0].IsSame( fromV )) {
+          nbEdges += edges[ 1 ].IsNull();
           edges[ 1 ] = e;
-          nbEdges++;
         }
       }
     }
@@ -922,7 +1096,7 @@ namespace
 
       // get angle between the 2 edges
       gp_Vec faceNormal;
-      double angle = helper.GetAngle( edges[0], edges[1], faceFrw, &faceNormal );
+      double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
       if ( Abs( angle ) < 5 * M_PI/180 )
       {
         dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
@@ -940,7 +1114,7 @@ namespace
     }
     else if ( nbEdges == 1 )
     {
-      dir = getFaceDir( faceFrw, edges[0], node, helper, ok );
+      dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
       if ( cosin ) *cosin = 1.;
     }
     else
@@ -950,14 +1124,56 @@ namespace
 
     return dir;
   }
+
+  //================================================================================
+  /*!
+   * \brief Finds concave VERTEXes of a FACE
+   */
+  //================================================================================
+
+  bool getConcaveVertices( const TopoDS_Face&  F,
+                           SMESH_MesherHelper& helper,
+                           set< TGeomID >*     vertices = 0)
+  {
+    // check angles at VERTEXes
+    TError error;
+    TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
+    for ( size_t iW = 0; iW < wires.size(); ++iW )
+    {
+      const int nbEdges = wires[iW]->NbEdges();
+      if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
+        continue;
+      for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
+      {
+        if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
+        int iE2 = ( iE1 + 1 ) % nbEdges;
+        while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
+          iE2 = ( iE2 + 1 ) % nbEdges;
+        TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
+        double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
+                                        wires[iW]->Edge( iE2 ), F, V );
+        if ( angle < -5. * M_PI / 180. )
+        {
+          if ( !vertices )
+            return true;
+          vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
+        }
+      }
+    }
+    return vertices ? !vertices->empty() : false;
+  }
+
   //================================================================================
   /*!
    * \brief Returns true if a FACE is bound by a concave EDGE
    */
   //================================================================================
 
-  bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
+  bool isConcave( const TopoDS_Face&  F,
+                  SMESH_MesherHelper& helper,
+                  set< TGeomID >*     vertices = 0 )
   {
+    bool isConcv = false;
     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
     //   return true;
     gp_Vec2d drv1, drv2;
@@ -986,49 +1202,130 @@ namespace
       if ( !isConvex )
       {
         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
-        return true;
+        isConcv = true;
+        if ( vertices )
+          break;
+        else
+          return true;
       }
     }
+
     // check angles at VERTEXes
-    TError error;
-    TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
-    for ( size_t iW = 0; iW < wires.size(); ++iW )
-    {
-      const int nbEdges = wires[iW]->NbEdges();
-      if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
-        continue;
-      for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
+    if ( getConcaveVertices( F, helper, vertices ))
+      isConcv = true;
+
+    return isConcv;
+  }
+
+  //================================================================================
+  /*!
+   * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
+   *  \param [in] face - the mesh face to treat
+   *  \param [in] nodeOnEdge - a node on the EDGE
+   *  \param [out] faceSize - the computed distance
+   *  \return bool - true if faceSize computed
+   */
+  //================================================================================
+
+  bool getDistFromEdge( const SMDS_MeshElement* face,
+                        const SMDS_MeshNode*    nodeOnEdge,
+                        double &                faceSize )
+  {
+    faceSize = Precision::Infinite();
+    bool done = false;
+
+    int nbN  = face->NbCornerNodes();
+    int iOnE = face->GetNodeIndex( nodeOnEdge );
+    int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
+                     SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
+    const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
+                                      face->GetNode( iNext[1] ) };
+    gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
+    double segLen = -1.;
+    // look for two neighbor not in-FACE nodes of face
+    for ( int i = 0; i < 2; ++i )
+    {
+      if ( nNext[i]->GetPosition()->GetDim() != 2 &&
+           nNext[i]->GetID() < nodeOnEdge->GetID() )
       {
-        if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
-        int iE2 = ( iE1 + 1 ) % nbEdges;
-        while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
-          iE2 = ( iE2 + 1 ) % nbEdges;
-        double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
-                                        wires[iW]->Edge( iE2 ), F );
-        if ( angle < -5. * M_PI / 180. )
-          return true;
+        // look for an in-FACE node
+        for ( int iN = 0; iN < nbN; ++iN )
+        {
+          if ( iN == iOnE || iN == iNext[i] )
+            continue;
+          SMESH_TNodeXYZ pInFace = face->GetNode( iN );
+          gp_XYZ v = pInFace - segEnd;
+          if ( segLen < 0 )
+          {
+            segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
+            segLen = segVec.Modulus();
+          }
+          double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
+          faceSize = Min( faceSize, distToSeg );
+          done = true;
+        }
+        segLen = -1;
       }
     }
-    return false;
+    return done;
+  }
+  //================================================================================
+  /*!
+   * \brief Return direction of axis or revolution of a surface
+   */
+  //================================================================================
+
+  bool getRovolutionAxis( const Adaptor3d_Surface& surface,
+                          gp_Dir &                 axis )
+  {
+    switch ( surface.GetType() ) {
+    case GeomAbs_Cone:
+    {
+      gp_Cone cone = surface.Cone();
+      axis = cone.Axis().Direction();
+      break;
+    }
+    case GeomAbs_Sphere:
+    {
+      gp_Sphere sphere = surface.Sphere();
+      axis = sphere.Position().Direction();
+      break;
+    }
+    case GeomAbs_SurfaceOfRevolution:
+    {
+      axis = surface.AxeOfRevolution().Direction();
+      break;
+    }
+    //case GeomAbs_SurfaceOfExtrusion:
+    case GeomAbs_OffsetSurface:
+    {
+      Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
+      return getRovolutionAxis( base->Surface(), axis );
+    }
+    default: return false;
+    }
+    return true;
   }
+
   //--------------------------------------------------------------------------------
   // DEBUG. Dump intermediate node positions into a python script
   // HOWTO use: run python commands written in a console to see
   //  construction steps of viscous layers
 #ifdef __myDEBUG
   ofstream* py;
-  int       theNbFunc;
+  int       theNbPyFunc;
   struct PyDump {
-    PyDump() {
+    PyDump(SMESH_Mesh& m) {
+      int tag = 3 + m.GetId();
       const char* fname = "/tmp/viscous.py";
       cout << "execfile('"<<fname<<"')"<<endl;
       py = new ofstream(fname);
       *py << "import SMESH" << endl
           << "from salome.smesh import smeshBuilder" << endl
           << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
-          << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
+          << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
-      theNbFunc = 0;
+      theNbPyFunc = 0;
     }
     void Finish() {
       if (py) {
@@ -1039,16 +1336,17 @@ namespace
       }
       delete py; py=0;
     }
-    ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbFunc << endl; }
+    ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
   };
 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
+#define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
   void _dumpFunction(const string& fun, int ln)
-  { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbFunc; }
-  void _dumpMove(const SMDS_MeshNode* n, int ln)
+  { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
+  void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
-               << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
+               << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
   void _dumpCmd(const string& txt, int ln)
   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
   void dumpFunctionEnd()
@@ -1059,9 +1357,10 @@ namespace
       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
 #define debugMsg( txt ) { cout << txt << " (line: " << __LINE__ << ")" << endl; }
 #else
-  struct PyDump { void Finish() {} };
+  struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} };
 #define dumpFunction(f) f
 #define dumpMove(n)
+#define dumpMoveComm(n,txt)
 #define dumpCmd(txt)
 #define dumpFunctionEnd()
 #define dumpChangeNodes(f)
@@ -1091,19 +1390,36 @@ _ViscousBuilder::_ViscousBuilder()
 
 bool _ViscousBuilder::error(const string& text, int solidId )
 {
+  const string prefix = string("Viscous layers builder: ");
   _error->myName    = COMPERR_ALGO_FAILED;
-  _error->myComment = string("Viscous layers builder: ") + text;
+  _error->myComment = prefix + text;
   if ( _mesh )
   {
     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
     if ( !sm && !_sdVec.empty() )
-      sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
+      sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
     {
       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
       if ( smError && smError->myAlgo )
         _error->myAlgo = smError->myAlgo;
       smError = _error;
+      sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
+    }
+    // set KO to all solids
+    for ( size_t i = 0; i < _sdVec.size(); ++i )
+    {
+      if ( _sdVec[i]._index == solidId )
+        continue;
+      sm = _mesh->GetSubMesh( _sdVec[i]._solid );
+      if ( !sm->IsEmpty() )
+        continue;
+      SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
+      if ( !smError || smError->IsOK() )
+      {
+        smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
+        sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
+      }
     }
   }
   makeGroupOfLE(); // debug
@@ -1183,7 +1499,7 @@ SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
     return SMESH_ComputeErrorPtr(); // everything already computed
 
-  PyDump debugDump;
+  PyDump debugDump( theMesh );
 
   // TODO: ignore already computed SOLIDs 
   if ( !findSolidsWithLayers())
@@ -1217,6 +1533,34 @@ SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
   return _error;
 }
 
+//================================================================================
+/*!
+ * \brief Check validity of hypotheses
+ */
+//================================================================================
+
+SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh&         mesh,
+                                                        const TopoDS_Shape& shape )
+{
+  _mesh = & mesh;
+
+  if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
+    return SMESH_ComputeErrorPtr(); // everything already computed
+
+
+  findSolidsWithLayers();
+  bool ok = findFacesWithLayers();
+
+  // remove _MeshOfSolid's of _SolidData's
+  for ( size_t i = 0; i < _sdVec.size(); ++i )
+    _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
+
+  if ( !ok )
+    return _error;
+
+  return SMESH_ComputeErrorPtr();
+}
+
 //================================================================================
 /*!
  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
@@ -1240,22 +1584,28 @@ bool _ViscousBuilder::findSolidsWithLayers()
     // TODO: check if algo is hidden
     const list <const SMESHDS_Hypothesis *> & allHyps =
       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
+    _SolidData* soData = 0;
     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
     const StdMeshers_ViscousLayers* viscHyp = 0;
-    for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
-      viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
-    if ( viscHyp )
-    {
-      TopoDS_Shape hypShape;
-      filter.Init( filter.Is( viscHyp ));
-      _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
+    for ( ; hyp != allHyps.end(); ++hyp )
+      if ( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp ))
+      {
+        TopoDS_Shape hypShape;
+        filter.Init( filter.Is( viscHyp ));
+        _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
 
-      _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
-                                                                allSolids(i),
-                                                                /*toCreate=*/true);
-      _sdVec.push_back( _SolidData( allSolids(i), viscHyp, hypShape, proxyMesh ));
-      _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
-    }
+        if ( !soData )
+        {
+          _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
+                                                                    allSolids(i),
+                                                                    /*toCreate=*/true);
+          _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
+          soData = & _sdVec.back();
+          soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
+        }
+        soData->_hyps.push_back( viscHyp );
+        soData->_hypShapes.push_back( hypShape );
+      }
   }
   if ( _sdVec.empty() )
     return error
@@ -1270,7 +1620,7 @@ bool _ViscousBuilder::findSolidsWithLayers()
  */
 //================================================================================
 
-bool _ViscousBuilder::findFacesWithLayers()
+bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
 {
   SMESH_MesherHelper helper( *_mesh );
   TopExp_Explorer exp;
@@ -1281,53 +1631,97 @@ bool _ViscousBuilder::findFacesWithLayers()
   {
     solids.Add( _sdVec[i]._solid );
 
-    vector<TGeomID> ids = _sdVec[i]._hyp->GetBndShapes();
-    if ( _sdVec[i]._hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
+    // get faces to ignore defined by each hyp
+    typedef const StdMeshers_ViscousLayers* THyp;
+    typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
+    list< TFacesOfHyp > ignoreFacesOfHyps;
+    list< THyp >::iterator              hyp = _sdVec[i]._hyps.begin();
+    list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
+    for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
     {
-      for ( size_t ii = 0; ii < ids.size(); ++ii )
-      {
-        const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
-        if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
-          _sdVec[i]._ignoreFaceIds.insert( ids[ii] );
-      }
+      ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
+      getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
     }
-    else // FACEs with layers are given
+
+    // fill _SolidData::_face2hyp and check compatibility of hypotheses
+    const int nbHyps = _sdVec[i]._hyps.size();
+    if ( nbHyps > 1 )
     {
-      exp.Init( _sdVec[i]._solid, TopAbs_FACE );
-      for ( ; exp.More(); exp.Next() )
+      // check if two hypotheses define different parameters for the same FACE
+      list< TFacesOfHyp >::iterator igFacesOfHyp;
+      for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
       {
-        TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
-        if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
-          _sdVec[i]._ignoreFaceIds.insert( faceInd );
+        const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
+        THyp hyp = 0;
+        igFacesOfHyp = ignoreFacesOfHyps.begin();
+        for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
+          if ( ! igFacesOfHyp->first.count( faceID ))
+          {
+            if ( hyp )
+              return error(SMESH_Comment("Several hypotheses define "
+                                         "Viscous Layers on the face #") << faceID );
+            hyp = igFacesOfHyp->second;
+          }
+        if ( hyp )
+          _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
+        else
+          _sdVec[i]._ignoreFaceIds.insert( faceID );
       }
-    }
-
-    // ignore internal FACEs if inlets and outlets are specified
-    {
-      TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
-      if ( _sdVec[i]._hyp->IsToIgnoreShapes() )
-        TopExp::MapShapesAndAncestors( _sdVec[i]._hypShape,
-                                       TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
 
-      exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
-      for ( ; exp.More(); exp.Next() )
+      // check if two hypotheses define different number of viscous layers for
+      // adjacent faces of a solid
+      set< int > nbLayersSet;
+      igFacesOfHyp = ignoreFacesOfHyps.begin();
+      for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
       {
-        const TopoDS_Face& face = TopoDS::Face( exp.Current() );
-        if ( helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
-          continue;
-
-        const TGeomID faceInd = getMeshDS()->ShapeToIndex( face );
-        if ( _sdVec[i]._hyp->IsToIgnoreShapes() )
+        nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
+      }
+      if ( nbLayersSet.size() > 1 )
+      {
+        for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
         {
-          int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
-          if ( nbSolids > 1 )
-            _sdVec[i]._ignoreFaceIds.insert( faceInd );
+          PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
+          THyp hyp1 = 0, hyp2 = 0;
+          while( const TopoDS_Shape* face = fIt->next() )
+          {
+            const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
+            map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
+            if ( f2h != _sdVec[i]._face2hyp.end() )
+            {
+              ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
+            }
+          }
+          if ( hyp1 && hyp2 &&
+               hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
+          {
+            return error("Two hypotheses define different number of "
+                         "viscous layers on adjacent faces");
+          }
         }
+      }
+    } // if ( nbHyps > 1 )
+    else
+    {
+      _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
+    }
+  } // loop on _sdVec
 
-        if ( helper.IsReversedSubMesh( face ))
-        {
-          _sdVec[i]._reversedFaceIds.insert( faceInd );
-        }
+  if ( onlyWith ) // is called to check hypotheses compatibility only
+    return true;
+
+  // fill _SolidData::_reversedFaceIds
+  for ( size_t i = 0; i < _sdVec.size(); ++i )
+  {
+    exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
+    for ( ; exp.More(); exp.Next() )
+    {
+      const TopoDS_Face& face = TopoDS::Face( exp.Current() );
+      const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
+      if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
+          helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
+          helper.IsReversedSubMesh( face ))
+      {
+        _sdVec[i]._reversedFaceIds.insert( faceID );
       }
     }
   }
@@ -1359,6 +1753,7 @@ bool _ViscousBuilder::findFacesWithLayers()
         continue; // nothing interesting
       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
       // check presence of layers on fWOL within an adjacent SOLID
+      bool collision = false;
       PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
       while ( const TopoDS_Shape* solid = sIt->next() )
         if ( !solid->IsSame( _sdVec[i]._solid ))
@@ -1367,8 +1762,9 @@ bool _ViscousBuilder::findFacesWithLayers()
           int  iFace = getMeshDS()->ShapeToIndex( fWOL );
           if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
           {
-            _sdVec[i]._noShrinkFaces.insert( iFace );
-            fWOL.Nullify();
+            //_sdVec[i]._noShrinkShapes.insert( iFace );
+            //fWOL.Nullify();
+            collision = true;
           }
         }
       // add edge to maps
@@ -1376,6 +1772,12 @@ bool _ViscousBuilder::findFacesWithLayers()
       {
         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
+        if ( collision )
+        {
+          // _shrinkShape2Shape will be used to temporary inflate _LayerEdge's based
+          // on the edge but shrink won't be performed
+          _sdVec[i]._noShrinkShapes.insert( edgeInd );
+        }
       }
     }
   }
@@ -1384,59 +1786,75 @@ bool _ViscousBuilder::findFacesWithLayers()
   set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
   for ( size_t i = 0; i < _sdVec.size(); ++i )
   {
-    TopTools_MapOfShape noShrinkVertices;
     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
     {
       const TopoDS_Shape& fWOL = e2f->second;
-      TGeomID           edgeID = e2f->first;
+      const TGeomID     edgeID = e2f->first;
       bool notShrinkFace = false;
       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
-      while ( soIt->more())
+      while ( soIt->more() )
       {
         const TopoDS_Shape* solid = soIt->next();
         if ( _sdVec[i]._solid.IsSame( *solid )) continue;
         SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
         if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
         notShrinkFace = true;
-        for ( size_t j = 0; j < _sdVec.size(); ++j )
+        size_t iSolid = 0;
+        for ( ; iSolid < _sdVec.size(); ++iSolid )
         {
-          if ( _sdVec[j]._solid.IsSame( *solid ) )
-            if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
+          if ( _sdVec[iSolid]._solid.IsSame( *solid ) ) {
+            if ( _sdVec[iSolid]._shrinkShape2Shape.count( edgeID ))
               notShrinkFace = false;
+            break;
+          }
         }
-      }
-      if ( notShrinkFace )
-      {
-        _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
-        for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
-          noShrinkVertices.Add( vExp.Current() );
-      }
-    }
-    // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
-    // to the found not shrinked fWOL's
-    e2f = _sdVec[i]._shrinkShape2Shape.begin();
-    for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
-    {
-      TGeomID edgeID = e2f->first;
-      TopoDS_Vertex VV[2];
-      TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
-      if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
-      {
-        _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( e2f->second ));
-        _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
-      }
-      else
-      {
-        e2f++;
-      }
-    }
-  }
-
-  // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
-
-  for ( size_t i = 0; i < _sdVec.size(); ++i )
-  {
+        if ( notShrinkFace )
+        {
+          _sdVec[i]._noShrinkShapes.insert( edgeID );
+
+          // add VERTEXes of the edge in _noShrinkShapes
+          TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
+          for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
+            _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( vIt.Value() ));
+
+          // check if there is a collision with to-shrink-from EDGEs in iSolid
+          if ( iSolid == _sdVec.size() )
+            continue; // no VL in the solid
+          shapes.Clear();
+          TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
+          for ( int iE = 1; iE <= shapes.Extent(); ++iE )
+          {
+            const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
+            const TGeomID    eID = getMeshDS()->ShapeToIndex( E );
+            if ( eID == edgeID ||
+                 !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
+                 _sdVec[i]._noShrinkShapes.count( eID ))
+              continue;
+            for ( int is1st = 0; is1st < 2; ++is1st )
+            {
+              TopoDS_Vertex V = helper.IthVertex( is1st, E );
+              if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
+              {
+                // _sdVec[i]._noShrinkShapes.insert( eID );
+                // V = helper.IthVertex( !is1st, E );
+                // _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( V ));
+                //iE = 0; // re-start the loop on EDGEs of fWOL
+                return error("No way to make a conformal mesh with "
+                             "the given set of faces with layers", _sdVec[i]._index);
+              }
+            }
+          }
+        }
+
+      } // while ( soIt->more() )
+    } // loop on _sdVec[i]._shrinkShape2Shape
+  } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
+
+  // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
+
+  for ( size_t i = 0; i < _sdVec.size(); ++i )
+  {
     shapes.Clear();
     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
@@ -1453,8 +1871,8 @@ bool _ViscousBuilder::findFacesWithLayers()
         {
           totalNbFaces++;
           const int fID = getMeshDS()->ShapeToIndex( *f );
-          if ( _sdVec[i]._ignoreFaceIds.count ( fID ) &&
-               !_sdVec[i]._noShrinkFaces.count( fID ))
+          if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&&
+               !_sdVec[i]._noShrinkShapes.count( fID )*/)
             facesWOL.push_back( *f );
         }
       }
@@ -1522,6 +1940,60 @@ bool _ViscousBuilder::findFacesWithLayers()
   return true;
 }
 
+//================================================================================
+/*!
+ * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
+ */
+//================================================================================
+
+void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape&             solid,
+                                     const StdMeshers_ViscousLayers* hyp,
+                                     const TopoDS_Shape&             hypShape,
+                                     set<TGeomID>&                   ignoreFaceIds)
+{
+  TopExp_Explorer exp;
+
+  vector<TGeomID> ids = hyp->GetBndShapes();
+  if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
+  {
+    for ( size_t ii = 0; ii < ids.size(); ++ii )
+    {
+      const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
+      if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
+        ignoreFaceIds.insert( ids[ii] );
+    }
+  }
+  else // FACEs with layers are given
+  {
+    exp.Init( solid, TopAbs_FACE );
+    for ( ; exp.More(); exp.Next() )
+    {
+      TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
+      if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
+        ignoreFaceIds.insert( faceInd );
+    }
+  }
+
+  // ignore internal FACEs if inlets and outlets are specified
+  if ( hyp->IsToIgnoreShapes() )
+  {
+    TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
+    TopExp::MapShapesAndAncestors( hypShape,
+                                   TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
+
+    for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
+    {
+      const TopoDS_Face& face = TopoDS::Face( exp.Current() );
+      if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
+        continue;
+
+      int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
+      if ( nbSolids > 1 )
+        ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
+    }
+  }
+}
+
 //================================================================================
 /*!
  * \brief Create the inner surface of the viscous layer and prepare data for infation
@@ -1532,18 +2004,19 @@ bool _ViscousBuilder::makeLayer(_SolidData& data)
 {
   // get all sub-shapes to make layers on
   set<TGeomID> subIds, faceIds;
-  subIds = data._noShrinkFaces;
+  subIds = data._noShrinkShapes;
   TopExp_Explorer exp( data._solid, TopAbs_FACE );
   for ( ; exp.More(); exp.Next() )
+  {
+    SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
+    if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
     {
-      SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
-      if ( ! data._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
-        faceIds.insert( fSubM->GetId() );
-      SMESH_subMeshIteratorPtr subIt =
-        fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
+      faceIds.insert( fSubM->GetId() );
+      SMESH_subMeshIteratorPtr subIt = fSubM->getDependsOnIterator(/*includeSelf=*/true);
       while ( subIt->more() )
         subIds.insert( subIt->next()->GetId() );
     }
+  }
 
   // make a map to find new nodes on sub-shapes shared with other SOLID
   map< TGeomID, TNode2Edge* >::iterator s2ne;
@@ -1566,14 +2039,14 @@ bool _ViscousBuilder::makeLayer(_SolidData& data)
 
   // Create temporary faces and _LayerEdge's
 
-  dumpFunction(SMESH_Comment("makeLayers_")<<data._index); 
+  dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
 
   data._stepSize = Precision::Infinite();
   data._stepSizeNodes[0] = 0;
 
   SMESH_MesherHelper helper( *_mesh );
   helper.SetSubShape( data._solid );
-  helper.SetElementsOnShape(true);
+  helper.SetElementsOnShape( true );
 
   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
   TNode2Edge::iterator n2e2;
@@ -1595,28 +2068,51 @@ bool _ViscousBuilder::makeLayer(_SolidData& data)
     while ( eIt->more() )
     {
       const SMDS_MeshElement* face = eIt->next();
+      double          faceMaxCosin = -1;
+      _LayerEdge*     maxCosinEdge = 0;
+      int             nbDegenNodes = 0;
+
       newNodes.resize( face->NbCornerNodes() );
-      double faceMaxCosin = -1;
-      _LayerEdge* maxCosinEdge = 0;
-      for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
+      for ( size_t i = 0 ; i < newNodes.size(); ++i )
       {
-        const SMDS_MeshNode* n = face->GetNode(i);
+        const SMDS_MeshNode* n = face->GetNode( i );
+        const int      shapeID = n->getshapeId();
+        const bool onDegenShap = helper.IsDegenShape( shapeID );
+        const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
+        if ( onDegenShap )
+        {
+          if ( onDegenEdge )
+          {
+            // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
+            const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
+            TopoDS_Vertex       V = helper.IthVertex( 0, TopoDS::Edge( E ));
+            if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
+              n = vN;
+              nbDegenNodes++;
+            }
+          }
+          else
+          {
+            nbDegenNodes++;
+          }
+        }
         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
         if ( !(*n2e).second )
         {
           // add a _LayerEdge
           _LayerEdge* edge = new _LayerEdge();
-          n2e->second = edge;
           edge->_nodes.push_back( n );
-          const int shapeID = n->getshapeId();
+          n2e->second = edge;
           edgesByGeom[ shapeID ].push_back( edge );
+          const bool noShrink = data._noShrinkShapes.count( shapeID );
 
           SMESH_TNodeXYZ xyz( n );
 
           // set edge data or find already refined _LayerEdge and get data from it
-          if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
-               ( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() &&
-               ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
+          if (( !noShrink                                                     ) &&
+              ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE        ) &&
+              (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
+              (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end()     ))
           {
             _LayerEdge* foundEdge = (*n2e2).second;
             gp_XYZ        lastPos = edge->Copy( *foundEdge, helper );
@@ -1627,7 +2123,10 @@ bool _ViscousBuilder::makeLayer(_SolidData& data)
           }
           else
           {
-            edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
+            if ( !noShrink )
+            {
+              edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
+            }
             if ( !setEdgeData( *edge, subIds, helper, data ))
               return false;
           }
@@ -1640,7 +2139,13 @@ bool _ViscousBuilder::makeLayer(_SolidData& data)
           }
         }
         newNodes[ i ] = n2e->second->_nodes.back();
+
+        if ( onDegenEdge )
+          data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
       }
+      if ( newNodes.size() - nbDegenNodes < 2 )
+        continue;
+
       // create a temporary face
       const SMDS_MeshElement* newFace =
         new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId() );
@@ -1649,6 +2154,7 @@ bool _ViscousBuilder::makeLayer(_SolidData& data)
       // compute inflation step size by min size of element on a convex surface
       if ( faceMaxCosin > theMinSmoothCosin )
         limitStepSize( data, face, maxCosinEdge );
+
     } // loop on 2D elements on a FACE
   } // loop on FACEs of a SOLID
 
@@ -1663,30 +2169,73 @@ bool _ViscousBuilder::makeLayer(_SolidData& data)
   // limit data._stepSize depending on surface curvature and fill data._convexFaces
   limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
 
-  // Set target nodes into _Simplex and _2NearEdges of _LayerEdge's
+  // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
   TNode2Edge::iterator n2e;
+  const SMDS_MeshNode* nn[2];
   for ( size_t i = 0; i < data._edges.size(); ++i )
   {
-    if ( data._edges[i]->IsOnEdge())
+    _LayerEdge* edge = data._edges[i];
+    if ( edge->IsOnEdge() )
+    {
+      // get neighbor nodes
+      bool hasData = ( edge->_2neibors->_edges[0] );
+      if ( hasData ) // _LayerEdge is a copy of another one
+      {
+        nn[0] = edge->_2neibors->srcNode(0);
+        nn[1] = edge->_2neibors->srcNode(1);
+      }
+      else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], data ))
+      {
+        return false;
+      }
+      // set neighbor _LayerEdge's
       for ( int j = 0; j < 2; ++j )
       {
-        if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
-          break; // _LayerEdge is shared by two _SolidData's
-        const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
-        if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
+        if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
           return error("_LayerEdge not found by src node", data._index);
-        n = (*n2e).second->_nodes.back();
-        data._edges[i]->_2neibors->_edges[j] = n2e->second;
+        edge->_2neibors->_edges[j] = n2e->second;
       }
-    //else
-    for ( size_t j = 0; j < data._edges[i]->_simplices.size(); ++j )
+      if ( !hasData )
+        edge->SetDataByNeighbors( nn[0], nn[1], helper);
+    }
+
+    for ( size_t j = 0; j < edge->_simplices.size(); ++j )
     {
-      _Simplex& s = data._edges[i]->_simplices[j];
+      _Simplex& s = edge->_simplices[j];
       s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
       s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
     }
+
+    // For an _LayerEdge on a degenerated EDGE, copy some data from
+    // a corresponding _LayerEdge on a VERTEX
+    // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
+    if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
+    {
+      // Generally we should not get here
+      const TopoDS_Shape& E = getMeshDS()->IndexToShape( edge->_nodes[0]->getshapeId() );
+      if ( E.ShapeType() != TopAbs_EDGE )
+        continue;
+      TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( E ));
+      const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
+      if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
+        continue;
+      const _LayerEdge* vEdge = n2e->second;
+      edge->_normal    = vEdge->_normal;
+      edge->_lenFactor = vEdge->_lenFactor;
+      edge->_cosin     = vEdge->_cosin;
+    }
   }
 
+  // fix _LayerEdge::_2neibors on EDGEs to smooth
+  map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
+  for ( ; e2c != data._edge2curve.end(); ++e2c )
+    if ( !e2c->second.IsNull() )
+    {
+      size_t iEdgeEnd; int iBeg, iEnd;
+      if ( data.GetShapeEdges( e2c->first, iEdgeEnd, &iBeg, &iEnd ))
+        data.Sort2NeiborsOnEdge( iBeg, iEnd );
+    }
+
   dumpFunctionEnd();
   return true;
 }
@@ -1755,7 +2304,6 @@ void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
 {
   const int nbTestPnt = 5; // on a FACE sub-shape
-  const double minCurvature = 0.9 / data._hyp->GetTotalThickness();
 
   BRepLProp_SLProps surfProp( 2, 1e-6 );
   SMESH_MesherHelper helper( *_mesh );
@@ -1766,6 +2314,10 @@ void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
   for ( ; face.More(); face.Next() )
   {
     const TopoDS_Face& F = TopoDS::Face( face.Current() );
+    SMESH_subMesh *   sm = _mesh->GetSubMesh( F );
+    const TGeomID faceID = sm->GetId();
+    if ( data._ignoreFaceIds.count( faceID )) continue;
+
     BRepAdaptor_Surface surface( F, false );
     surfProp.SetSurface( surface );
 
@@ -1773,9 +2325,6 @@ void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
     int iBeg, iEnd;
 
     _ConvexFace cnvFace;
-    SMESH_subMesh *            sm = _mesh->GetSubMesh( F );
-    const TGeomID          faceID = sm->GetId();
-    if ( data._ignoreFaceIds.count( faceID )) continue;
     const double        oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
     while ( smIt->more() )
@@ -1789,9 +2338,11 @@ void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
       else
         continue;
       // check concavity and curvature and limit data._stepSize
+      const double minCurvature =
+        1. / ( data._hypOnShape[ edgesEnd ].GetTotalThickness() * ( 1+theThickToIntersection ));
       int nbLEdges = iEnd - iBeg;
-      int step = Max( 1, nbLEdges / nbTestPnt );
-      for ( ; iBeg < iEnd; iBeg += step )
+      int iStep    = Max( 1, nbLEdges / nbTestPnt );
+      for ( ; iBeg < iEnd; iBeg += iStep )
       {
         gp_XY uv = helper.GetNodeUV( F, data._edges[ iBeg ]->_nodes[0] );
         surfProp.SetParameters( uv.X(), uv.Y() );
@@ -1859,7 +2410,7 @@ void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
           const SMDS_MeshNode* srcNode = ledge->_nodes[0];
           if ( !usedNodes.insert( srcNode ).second ) continue;
 
-          getSimplices( srcNode, ledge->_simplices, data._ignoreFaceIds, &data );
+          _Simplex::GetSimplices( srcNode, ledge->_simplices, data._ignoreFaceIds, &data );
           for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
           {
             usedNodes.insert( ledge->_simplices[i]._nPrev );
@@ -1881,92 +2432,150 @@ void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
 bool _ViscousBuilder::sortEdges( _SolidData&                    data,
                                  vector< vector<_LayerEdge*> >& edgesByGeom)
 {
+  // define allowed thickness
+  computeGeomSize( data ); // compute data._geomSize
+
+  data._maxThickness = 0;
+  data._minThickness = 1e100;
+  list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
+  for ( ; hyp != data._hyps.end(); ++hyp )
+  {
+    data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
+    data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
+  }
+  const double tgtThick = /*Min( 0.5 * data._geomSize, */data._maxThickness;
+
   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
-  // boundry inclined at a sharp angle to the shape
+  // boundry inclined to the shape at a sharp angle
 
   list< TGeomID > shapesToSmooth;
-  
+  TopTools_MapOfShape edgesOfSmooFaces;
+
   SMESH_MesherHelper helper( *_mesh );
   bool ok = true;
 
-  for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
+  for ( int isEdge = 0; isEdge < 2; ++isEdge ) // loop on [ FACEs, EDGEs ]
   {
-    vector<_LayerEdge*>& eS = edgesByGeom[iS];
-    if ( eS.empty() ) continue;
-    const TopoDS_Shape& S = getMeshDS()->IndexToShape( iS );
-    bool needSmooth = false;
-    switch ( S.ShapeType() )
+    const int dim = isEdge ? 1 : 2;
+
+    for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
     {
-    case TopAbs_EDGE: {
-
-      bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
-      for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
-      {
-        TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
-        vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
-        if ( eV.empty() ) continue;
-        // double cosin = eV[0]->_cosin;
-        // bool badCosin =
-        //   ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
-        // if ( badCosin )
-        // {
-        //   gp_Vec dir1, dir2;
-        //   if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
-        //     dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
-        //   else
-        //     dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
-        //                        eV[0]->_nodes[0], helper, ok);
-        //   dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
-        //   double angle = dir1.Angle( dir2 );
-        //   cosin = cos( angle );
-        // }
-        gp_Vec eDir = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
-        double angle = eDir.Angle( eV[0]->_normal );
-        double cosin = Cos( angle );
-        needSmooth = ( cosin > theMinSmoothCosin );
-      }
-      break;
-    }
-    case TopAbs_FACE: {
+      vector<_LayerEdge*>& eS = edgesByGeom[iS];
+      if ( eS.empty() ) continue;
+      if ( eS[0]->_nodes[0]->GetPosition()->GetDim() != dim ) continue;
 
-      for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
+      const TopoDS_Shape& S = getMeshDS()->IndexToShape( iS );
+      bool needSmooth = false;
+      switch ( S.ShapeType() )
       {
-        TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
-        vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
-        if ( eE.empty() ) continue;
-        if ( eE[0]->_sWOL.IsNull() )
+      case TopAbs_EDGE: {
+
+        const TopoDS_Edge& E = TopoDS::Edge( S );
+        if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
+          break;
+
+        TopoDS_Face F;
+        if ( !eS[0]->_sWOL.IsNull() && eS[0]->_sWOL.ShapeType() == TopAbs_FACE )
+          F = TopoDS::Face( eS[0]->_sWOL );
+
+        for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
         {
-          for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
-            needSmooth = ( eE[i]->_cosin > theMinSmoothCosin );
+          TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
+          vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
+          if ( eV.empty() ) continue;
+          gp_Vec  eDir = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
+          double angle = eDir.Angle( eV[0]->_normal );
+          double cosin = Cos( angle );
+          double cosinAbs = Abs( cosin );
+          if ( cosinAbs > theMinSmoothCosin )
+          {
+            // always smooth analytic EDGEs
+            needSmooth = ! data.CurveForSmooth( E, 0, eS.size(), F, helper, &eS ).IsNull();
+
+            // compare tgtThick with the length of an end segment
+            SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
+            while ( eIt->more() && !needSmooth )
+            {
+              const SMDS_MeshElement* endSeg = eIt->next();
+              if ( endSeg->getshapeId() == iS )
+              {
+                double segLen =
+                  SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
+                needSmooth = needSmoothing( cosinAbs, tgtThick, segLen );
+              }
+            }
+          }
         }
-        else
+        break;
+      }
+      case TopAbs_FACE: {
+
+        for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
         {
-          const TopoDS_Face& F1 = TopoDS::Face( S );
-          const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
-          const TopoDS_Edge& E  = TopoDS::Edge( eExp.Current() );
-          for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
+          TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
+          vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
+          if ( eE.empty() ) continue;
+          // TopLoc_Location loc;
+          // Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( S ), loc );
+          // bool isPlane = GeomLib_IsPlanarSurface( surface ).IsPlanar();
+          //if ( eE[0]->_sWOL.IsNull() )
           {
-            gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
-            gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
-            double angle = dir1.Angle( dir2 );
-            double cosin = cos( angle );
-            needSmooth = ( cosin > theMinSmoothCosin );
+            double faceSize;
+            for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
+              if ( eE[i]->_cosin > theMinSmoothCosin )
+              {
+                SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
+                while ( fIt->more() && !needSmooth )
+                {
+                  const SMDS_MeshElement* face = fIt->next();
+                  if ( getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
+                    needSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
+                }
+              }
           }
+          // else
+          // {
+          //   const TopoDS_Face& F1 = TopoDS::Face( S );
+          //   const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
+          //   const TopoDS_Edge& E  = TopoDS::Edge( eExp.Current() );
+          //   for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
+          //   {
+          //     gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
+          //     gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
+          //     double angle = dir1.Angle(  );
+          //     double cosin = cos( angle );
+          //     needSmooth = ( cosin > theMinSmoothCosin );
+          //   }
+          // }
+        }
+        if ( needSmooth )
+          for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More(); eExp.Next() )
+            edgesOfSmooFaces.Add( eExp.Current() );
+
+        break;
+      }
+      case TopAbs_VERTEX:
+        continue;
+      default:;
+      }
+
+      if ( needSmooth )
+      {
+        if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
+        else                                shapesToSmooth.push_back ( iS );
+
+        // preparation for smoothing
+        if ( S.ShapeType() == TopAbs_FACE )
+        {
+          data.PrepareEdgesToSmoothOnFace( & eS[0],
+                                           & eS[0] + eS.size(),
+                                           TopoDS::Face( S ),
+                                           /*substituteSrcNodes=*/false);
         }
       }
-      break;
-    }
-    case TopAbs_VERTEX:
-      continue;
-    default:;
-    }
-    if ( needSmooth )
-    {
-      if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
-      else                                shapesToSmooth.push_back ( iS );
-    }
 
-  } // loop on edgesByGeom
+    } // loop on edgesByGeom
+  } //  // loop on [ FACEs, EDGEs ]
 
   data._edges.reserve( data._n2eMap.size() );
   data._endEdgeOnShape.clear();
@@ -1994,6 +2603,45 @@ bool _ViscousBuilder::sortEdges( _SolidData&                    data,
     //eVec.clear();
   }
 
+  // compute average StdMeshers_ViscousLayers parameters for each shape
+
+  data._hypOnShape.clear();
+  if ( data._hyps.size() == 1 )
+  {
+    data._hypOnShape.resize( data._endEdgeOnShape.size(), AverageHyp( data._hyps.back() ));
+  }
+  else
+  {
+    data._hypOnShape.resize( data._endEdgeOnShape.size() );
+    map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
+    for ( size_t i = 0; i < data._endEdgeOnShape.size(); ++i )
+    {
+      int       iEnd = data._endEdgeOnShape[i];
+      _LayerEdge* LE = data._edges[ iEnd-1 ];
+      TGeomID iShape = LE->_nodes[0]->getshapeId();
+      const TopoDS_Shape& S = getMeshDS()->IndexToShape( iShape );
+      if ( S.ShapeType() == TopAbs_FACE )
+      {
+        if (( f2hyp = data._face2hyp.find( iShape )) != data._face2hyp.end() )
+        {
+          data._hypOnShape[ i ].Add( f2hyp->second );
+        }
+      }
+      else
+      {
+        PShapeIteratorPtr fIt = SMESH_MesherHelper::GetAncestors( S, *_mesh, TopAbs_FACE );
+        while ( const TopoDS_Shape* face = fIt->next() )
+        {
+          TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
+          if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
+          {
+            data._hypOnShape[ i ].Add( f2hyp->second );
+          }
+        }
+      }
+    }
+  }
+
   return ok;
 }
 
@@ -2012,7 +2660,7 @@ bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
   SMESH_MeshEditor editor(_mesh);
 
   const SMDS_MeshNode* node = edge._nodes[0]; // source node
-  SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
+  const SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
 
   edge._len       = 0;
   edge._2neibors  = 0;
@@ -2026,13 +2674,41 @@ bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
   edge._normal.SetCoord(0,0,0);
 
   int totalNbFaces = 0;
+  TopoDS_Face F;
+  std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
   gp_Vec geomNorm;
   bool normOK = true;
 
+  // get geom FACEs the node lies on
+  {
+    set<TGeomID> faceIds;
+    if  ( posType == SMDS_TOP_FACE )
+    {
+      faceIds.insert( node->getshapeId() );
+    }
+    else
+    {
+      SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
+      while ( fIt->more() )
+        faceIds.insert( editor.FindShape(fIt->next()));
+    }
+    set<TGeomID>::iterator id = faceIds.begin();
+    for ( ; id != faceIds.end(); ++id )
+    {
+      const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
+      if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
+        continue;
+      F = TopoDS::Face( s );
+      face2Norm[ totalNbFaces ].first = F;
+      totalNbFaces++;
+    }
+  }
+
   const TGeomID shapeInd = node->getshapeId();
   map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
   const bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
 
+  // find _normal
   if ( onShrinkShape ) // one of faces the node is on has no layers
   {
     TopoDS_Shape vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
@@ -2056,54 +2732,35 @@ bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
   }
   else // layers are on all faces of SOLID the node is on
   {
-    // find indices of geom faces the node lies on
-    set<TGeomID> faceIds;
-    if  ( posType == SMDS_TOP_FACE )
-    {
-      faceIds.insert( node->getshapeId() );
-    }
-    else
-    {
-      SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
-      while ( fIt->more() )
-        faceIds.insert( editor.FindShape(fIt->next()));
-    }
-
-    set<TGeomID>::iterator id = faceIds.begin();
-    TopoDS_Face F;
-    std::pair< TGeomID, gp_XYZ > id2Norm[20];
-    for ( ; id != faceIds.end(); ++id )
+    int nbOkNorms = 0;
+    for ( int iF = 0; iF < totalNbFaces; ++iF )
     {
-      const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
-      if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
-        continue;
-      F = TopoDS::Face( s );
+      F = TopoDS::Face( face2Norm[ iF ].first );
       geomNorm = getFaceNormal( node, F, helper, normOK );
       if ( !normOK ) continue;
+      nbOkNorms++;
 
       if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
         geomNorm.Reverse();
-      id2Norm[ totalNbFaces ].first  = *id;
-      id2Norm[ totalNbFaces ].second = geomNorm.XYZ();
-      totalNbFaces++;
+      face2Norm[ iF ].second = geomNorm.XYZ();
       edge._normal += geomNorm.XYZ();
     }
-    if ( totalNbFaces == 0 )
+    if ( nbOkNorms == 0 )
       return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
 
-    if ( normOK && edge._normal.Modulus() < 1e-3 && totalNbFaces > 1 )
+    if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
     {
       // opposite normals, re-get normals at shifted positions (IPAL 52426)
       edge._normal.SetCoord( 0,0,0 );
-      for ( int i = 0; i < totalNbFaces; ++i )
+      for ( int iF = 0; iF < totalNbFaces; ++iF )
       {
-        const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( id2Norm[i].first ));
+        const TopoDS_Face& F = face2Norm[iF].first;
         geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
           geomNorm.Reverse();
         if ( normOK )
-          id2Norm[ i ].second = geomNorm.XYZ();
-        edge._normal += id2Norm[ i ].second;
+          face2Norm[ iF ].second = geomNorm.XYZ();
+        edge._normal += face2Norm[ iF ].second;
       }
     }
 
@@ -2113,34 +2770,46 @@ bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
     }
     else
     {
-      edge._normal = getWeigthedNormal( node, id2Norm, totalNbFaces );
+      edge._normal = getWeigthedNormal( node, face2Norm, totalNbFaces );
     }
+  }
 
-    switch ( posType )
-    {
-    case SMDS_TOP_FACE:
-      edge._cosin = 0; break;
-
-    case SMDS_TOP_EDGE: {
-      TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
-      gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
-      double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
-      edge._cosin = cos( angle );
-      //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
-      break;
-    }
-    case SMDS_TOP_VERTEX: {
-      TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
-      gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
-      double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
-      edge._cosin = cos( angle );
-      //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
-      break;
-    }
-    default:
-      return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
-    }
-  } // case _sWOL.IsNull()
+  // set _cosin
+  switch ( posType )
+  {
+  case SMDS_TOP_FACE: {
+    edge._cosin = 0;
+    break;
+  }
+  case SMDS_TOP_EDGE: {
+    TopoDS_Edge E    = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
+    gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
+    double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
+    edge._cosin      = Cos( angle );
+    //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
+    break;
+  }
+  case SMDS_TOP_VERTEX: {
+    TopoDS_Vertex V  = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
+    gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
+    double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
+    edge._cosin      = Cos( angle );
+    if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
+      for ( int iF = totalNbFaces-2; iF >=0; --iF )
+      {
+        F = face2Norm[ iF ].first;
+        inFaceDir = getFaceDir( F, V, node, helper, normOK );
+        if ( normOK ) {
+          double angle = inFaceDir.Angle( edge._normal );
+          edge._cosin = Max( edge._cosin, Cos( angle ));
+        }
+      }
+    //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
+    break;
+  }
+  default:
+    return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
+  }
 
   double normSize = edge._normal.SquareModulus();
   if ( normSize < numeric_limits<double>::min() )
@@ -2164,14 +2833,16 @@ bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
     if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
     {
       double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
-      edge._pos.push_back( gp_XYZ( u, 0, 0));
-      getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
+      edge._pos.push_back( gp_XYZ( u, 0, 0 ));
+      if ( edge._nodes.size() > 1 )
+        getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
     }
     else // TopAbs_FACE
     {
       gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
-      getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
+      if ( edge._nodes.size() > 1 )
+        getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
     }
   }
   else
@@ -2180,17 +2851,7 @@ bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
 
     if ( posType == SMDS_TOP_FACE )
     {
-      getSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
-      double avgNormProj = 0, avgLen = 0;
-      for ( size_t i = 0; i < edge._simplices.size(); ++i )
-      {
-        gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
-        avgNormProj += edge._normal * vec;
-        avgLen += vec.Modulus();
-      }
-      avgNormProj /= edge._simplices.size();
-      avgLen /= edge._simplices.size();
-      edge._curvature = _Curvature::New( avgNormProj, avgLen );
+      _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
     }
   }
 
@@ -2201,14 +2862,14 @@ bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
   {
     edge._2neibors = new _2NearEdges;
     // target node instead of source ones will be set later
-    if ( ! findNeiborsOnEdge( &edge,
-                              edge._2neibors->_nodes[0],
-                              edge._2neibors->_nodes[1],
-                              data))
-      return false;
-    edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
-                             edge._2neibors->_nodes[1],
-                             helper);
+    // if ( ! findNeiborsOnEdge( &edge,
+    //                           edge._2neibors->_nodes[0],
+    //                           edge._2neibors->_nodes[1],
+    //                           data))
+    //   return false;
+    // edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
+    //                          edge._2neibors->_nodes[1],
+    //                          helper);
   }
 
   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
@@ -2283,12 +2944,39 @@ gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
   isOK = false;
 
   Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
-  if ( GeomLib::NormEstim( surface, uv, 1e-10, normal ) < 3 )
+
+  if ( !shiftInside &&
+       helper.IsDegenShape( node->getshapeId() ) &&
+       getFaceNormalAtSingularity( uv, face, helper, normal ))
   {
-    normal;
     isOK = true;
+    return normal.XYZ();
   }
-  else // hard singularity
+
+  int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
+  enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
+
+  if ( pointKind == IMPOSSIBLE &&
+       node->GetPosition()->GetDim() == 2 ) // node inside the FACE
+  {
+    // probably NormEstim() failed due to a too high tolerance
+    pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
+    isOK = ( pointKind < IMPOSSIBLE );
+  }
+  if ( pointKind < IMPOSSIBLE )
+  {
+    if ( pointKind != REGULAR &&
+         !shiftInside &&
+         node->GetPosition()->GetDim() < 2 ) // FACE boundary
+    {
+      gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
+      if ( normShift * normal.XYZ() < 0. )
+        normal = normShift;
+    }
+    isOK = true;
+  }
+
+  if ( !isOK ) // hard singularity, to call with shiftInside=true ?
   {
     const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
 
@@ -2301,7 +2989,9 @@ gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
         isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
         if ( isOK )
         {
-          if ( helper.IsReversedSubMesh( face ))
+          TopoDS_Face ff = face;
+          ff.Orientation( TopAbs_FORWARD );
+          if ( helper.IsReversedSubMesh( ff ))
             normal.Reverse();
           break;
         }
@@ -2311,6 +3001,55 @@ gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
   return normal.XYZ();
 }
 
+//================================================================================
+/*!
+ * \brief Try to get normal at a singularity of a surface basing on it's nature
+ */
+//================================================================================
+
+bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY&        uv,
+                                                  const TopoDS_Face&  face,
+                                                  SMESH_MesherHelper& helper,
+                                                  gp_Dir&             normal )
+{
+  BRepAdaptor_Surface surface( face );
+  gp_Dir axis;
+  if ( !getRovolutionAxis( surface, axis ))
+    return false;
+
+  double f,l, d, du, dv;
+  f = surface.FirstUParameter();
+  l = surface.LastUParameter();
+  d = ( uv.X() - f ) / ( l - f );
+  du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
+  f = surface.FirstVParameter();
+  l = surface.LastVParameter();
+  d = ( uv.Y() - f ) / ( l - f );
+  dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
+
+  gp_Dir refDir;
+  gp_Pnt2d testUV = uv;
+  enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
+  double tol = 1e-5;
+  Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
+  for ( int iLoop = 0; true ; ++iLoop )
+  {
+    testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
+    if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
+      break;
+    if ( iLoop > 20 )
+      return false;
+    tol /= 10.;
+  }
+
+  if ( axis * refDir < 0. )
+    axis.Reverse();
+
+  normal = axis;
+
+  return true;
+}
+
 //================================================================================
 /*!
  * \brief Return a normal at a node weighted with angles taken by FACEs
@@ -2321,23 +3060,40 @@ gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
  */
 //================================================================================
 
-gp_XYZ _ViscousBuilder::getWeigthedNormal( const SMDS_MeshNode*         n,
-                                           std::pair< TGeomID, gp_XYZ > fId2Normal[],
-                                           const int                    nbFaces )
+gp_XYZ _ViscousBuilder::getWeigthedNormal( const SMDS_MeshNode*             n,
+                                           std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
+                                           int                              nbFaces )
 {
   gp_XYZ resNorm(0,0,0);
   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( n, getMeshDS() );
   if ( V.ShapeType() != TopAbs_VERTEX )
   {
     for ( int i = 0; i < nbFaces; ++i )
-      resNorm += fId2Normal[i].second / nbFaces ;
+      resNorm += fId2Normal[i].second;
+    return resNorm;
+  }
+
+  // exclude equal normals
+  //int nbUniqNorms = nbFaces;
+  for ( int i = 0; i < nbFaces; ++i )
+    for ( int j = i+1; j < nbFaces; ++j )
+      if ( fId2Normal[i].second.IsEqual( fId2Normal[j].second, 0.1 ))
+      {
+        fId2Normal[i].second.SetCoord( 0,0,0 );
+        //--nbUniqNorms;
+        break;
+      }
+  //if ( nbUniqNorms < 3 )
+  {
+    for ( int i = 0; i < nbFaces; ++i )
+      resNorm += fId2Normal[i].second;
     return resNorm;
   }
 
   double angles[30];
   for ( int i = 0; i < nbFaces; ++i )
   {
-    const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( fId2Normal[i].first ));
+    const TopoDS_Face& F = fId2Normal[i].first;
 
     // look for two EDGEs shared by F and other FACEs within fId2Normal
     TopoDS_Edge ee[2];
@@ -2351,7 +3107,7 @@ gp_XYZ _ViscousBuilder::getWeigthedNormal( const SMDS_MeshNode*         n,
       for ( int j = 0; j < nbFaces && !isSharedEdge; ++j )
       {
         if ( i == j ) continue;
-        const TopoDS_Shape& otherF = getMeshDS()->IndexToShape( fId2Normal[j].first );
+        const TopoDS_Shape& otherF = fId2Normal[j].first;
         isSharedEdge = SMESH_MesherHelper::IsSubShape( *E, otherF );
       }
       if ( !isSharedEdge )
@@ -2371,12 +3127,10 @@ gp_XYZ _ViscousBuilder::getWeigthedNormal( const SMDS_MeshNode*         n,
     }
     else
     {
-      TopoDS_Vertex v10 = SMESH_MesherHelper::IthVertex( 1, ee[ 0 ]);
-      TopoDS_Vertex v01 = SMESH_MesherHelper::IthVertex( 0, ee[ 1 ]);
-      if ( !v10.IsSame( v01 ))
+      if ( !V.IsSame( SMESH_MesherHelper::IthVertex( 0, ee[ 1 ] )))
         std::swap( ee[0], ee[1] );
     }
-    angles[i] = SMESH_MesherHelper::GetAngle( ee[0], ee[1], F );
+    angles[i] = SMESH_MesherHelper::GetAngle( ee[0], ee[1], F, TopoDS::Vertex( V ));
   }
 
   // compute a weighted normal
@@ -2404,11 +3158,10 @@ bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
                                         _SolidData&           data)
 {
   const SMDS_MeshNode* node = edge->_nodes[0];
-  const int shapeInd = node->getshapeId();
-  SMESHDS_SubMesh* edgeSM = 0;
+  const int        shapeInd = node->getshapeId();
+  SMESHDS_SubMesh*   edgeSM = 0;
   if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
   {
-    
     edgeSM = getMeshDS()->MeshElements( shapeInd );
     if ( !edgeSM || edgeSM->NbElements() == 0 )
       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
@@ -2456,11 +3209,11 @@ void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
 
   // Set _curvature
 
-  double sumLen = vec1.Modulus() + vec2.Modulus();
+  double      sumLen = vec1.Modulus() + vec2.Modulus();
   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
-  double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
+  double      avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
   if ( _curvature ) delete _curvature;
   _curvature = _Curvature::New( avgNormProj, avgLen );
   // if ( _curvature )
@@ -2474,10 +3227,13 @@ void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
   if ( _sWOL.IsNull() )
   {
     TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
-    gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
+    TopoDS_Edge  E = TopoDS::Edge( S );
+    // if ( SMESH_Algo::isDegenerated( E ))
+    //   return;
+    gp_XYZ dirE    = getEdgeDir( E, _nodes[0], helper );
     gp_XYZ plnNorm = dirE ^ _normal;
-    double proj0 = plnNorm * vec1;
-    double proj1 = plnNorm * vec2;
+    double proj0   = plnNorm * vec1;
+    double proj1   = plnNorm * vec2;
     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
     {
       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
@@ -2545,11 +3301,11 @@ void _LayerEdge::SetCosin( double cosin )
  */
 //================================================================================
 
-void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
-                                    vector<_Simplex>&    simplices,
-                                    const set<TGeomID>&  ingnoreShapes,
-                                    const _SolidData*    dataToCheckOri,
-                                    const bool           toSort)
+void _Simplex::GetSimplices( const SMDS_MeshNode* node,
+                             vector<_Simplex>&    simplices,
+                             const set<TGeomID>&  ingnoreShapes,
+                             const _SolidData*    dataToCheckOri,
+                             const bool           toSort)
 {
   simplices.clear();
   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
@@ -2569,23 +3325,32 @@ void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
   }
 
   if ( toSort )
+    SortSimplices( simplices );
+}
+
+//================================================================================
+/*!
+ * \brief Set neighbor simplices side by side
+ */
+//================================================================================
+
+void _Simplex::SortSimplices(vector<_Simplex>& simplices)
+{
+  vector<_Simplex> sortedSimplices( simplices.size() );
+  sortedSimplices[0] = simplices[0];
+  int nbFound = 0;
+  for ( size_t i = 1; i < simplices.size(); ++i )
   {
-    vector<_Simplex> sortedSimplices( simplices.size() );
-    sortedSimplices[0] = simplices[0];
-    int nbFound = 0;
-    for ( size_t i = 1; i < simplices.size(); ++i )
-    {
-      for ( size_t j = 1; j < simplices.size(); ++j )
-        if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
-        {
-          sortedSimplices[i] = simplices[j];
-          nbFound++;
-          break;
-        }
-    }
-    if ( nbFound == simplices.size() - 1 )
-      simplices.swap( sortedSimplices );
+    for ( size_t j = 1; j < simplices.size(); ++j )
+      if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
+      {
+        sortedSimplices[i] = simplices[j];
+        nbFound++;
+        break;
+      }
   }
+  if ( nbFound == simplices.size() - 1 )
+    simplices.swap( sortedSimplices );
 }
 
 //================================================================================
@@ -2623,11 +3388,13 @@ void _ViscousBuilder::makeGroupOfLE()
     dumpFunctionEnd();
 
     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
+    dumpCmd( "faceId1 = mesh.NbElements()" );
     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
     for ( ; fExp.More(); fExp.Next() )
     {
       if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
       {
+        if ( sm->NbElements() == 0 ) continue;
         SMDS_ElemIteratorPtr fIt = sm->GetElements();
         while ( fIt->more())
         {
@@ -2639,11 +3406,40 @@ void _ViscousBuilder::makeGroupOfLE()
         }
       }
     }
+    dumpCmd( "faceId2 = mesh.NbElements()" );
+    dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
+             << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
+             << "'%s-%s' % (faceId1+1, faceId2))");
     dumpFunctionEnd();
   }
 #endif
 }
 
+//================================================================================
+/*!
+ * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
+ */
+//================================================================================
+
+void _ViscousBuilder::computeGeomSize( _SolidData& data )
+{
+  data._geomSize = Precision::Infinite();
+  double intersecDist;
+  auto_ptr<SMESH_ElementSearcher> searcher
+    ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
+                                           data._proxyMesh->GetFaces( data._solid )) );
+
+  TNode2Edge::iterator n2e = data._n2eMap.begin(), n2eEnd = data._n2eMap.end();
+  for ( ; n2e != n2eEnd; ++n2e )
+  {
+    _LayerEdge* edge = n2e->second;
+    if ( edge->IsOnEdge() ) continue;
+    edge->FindIntersection( *searcher, intersecDist, data._epsilon );
+    if ( data._geomSize > intersecDist && intersecDist > 0 )
+      data._geomSize = intersecDist;
+  }
+}
+
 //================================================================================
 /*!
  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
@@ -2656,46 +3452,42 @@ bool _ViscousBuilder::inflate(_SolidData& data)
 
   // Limit inflation step size by geometry size found by itersecting
   // normals of _LayerEdge's with mesh faces
-  double geomSize = Precision::Infinite(), intersecDist;
-  auto_ptr<SMESH_ElementSearcher> searcher
-    ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
-                                           data._proxyMesh->GetFaces( data._solid )) );
-  for ( size_t i = 0; i < data._edges.size(); ++i )
-  {
-    if ( data._edges[i]->IsOnEdge() ) continue;
-    data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
-    if ( geomSize > intersecDist && intersecDist > 0 )
-      geomSize = intersecDist;
-  }
-  if ( data._stepSize > 0.3 * geomSize )
-    limitStepSize( data, 0.3 * geomSize );
+  if ( data._stepSize > 0.3 * data._geomSize )
+    limitStepSize( data, 0.3 * data._geomSize );
 
-  const double tgtThick = data._hyp->GetTotalThickness();
-  if ( data._stepSize > tgtThick )
-    limitStepSize( data, tgtThick );
+  const double tgtThick = data._maxThickness;
+  if ( data._stepSize > data._minThickness )
+    limitStepSize( data, data._minThickness );
 
   if ( data._stepSize < 1. )
     data._epsilon = data._stepSize * 1e-7;
 
-  debugMsg( "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize );
+  debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
+
+  const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
 
   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
   int nbSteps = 0, nbRepeats = 0;
-  while ( 1.01 * avgThick < tgtThick )
+  int iBeg, iEnd, iS;
+  while ( avgThick < 0.99 )
   {
     // new target length
     curThick += data._stepSize;
     if ( curThick > tgtThick )
     {
-      curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
+      curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
       nbRepeats++;
     }
 
     // Elongate _LayerEdge's
     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
-    for ( size_t i = 0; i < data._edges.size(); ++i )
+    for ( iBeg = 0, iS = 0; iS < data._endEdgeOnShape.size(); ++iS )
     {
-      data._edges[i]->SetNewLength( curThick, helper );
+      const double shapeCurThick = Min( curThick, data._hypOnShape[ iS ].GetTotalThickness() );
+      for ( iEnd = data._endEdgeOnShape[ iS ]; iBeg < iEnd; ++iBeg )
+      {
+        data._edges[iBeg]->SetNewLength( shapeCurThick, helper );
+      }
     }
     dumpFunctionEnd();
 
@@ -2707,6 +3499,10 @@ bool _ViscousBuilder::inflate(_SolidData& data)
     {
       if ( nbSteps > 0 )
       {
+#ifdef __NOT_INVALIDATE_BAD_SMOOTH
+        debugMsg("NOT INVALIDATED STEP!");
+        return error("Smoothing failed", data._index);
+#endif
         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
         for ( size_t i = 0; i < data._edges.size(); ++i )
         {
@@ -2720,16 +3516,22 @@ bool _ViscousBuilder::inflate(_SolidData& data)
 
     // Evaluate achieved thickness
     avgThick = 0;
-    for ( size_t i = 0; i < data._edges.size(); ++i )
-      avgThick += data._edges[i]->_len;
+    for ( iBeg = 0, iS = 0; iS < data._endEdgeOnShape.size(); ++iS )
+    {
+      const double shapeTgtThick = data._hypOnShape[ iS ].GetTotalThickness();
+      for ( iEnd = data._endEdgeOnShape[ iS ]; iBeg < iEnd; ++iBeg )
+      {
+        avgThick += Min( 1., data._edges[iBeg]->_len / shapeTgtThick );
+      }
+    }
     avgThick /= data._edges.size();
-    debugMsg( "-- Thickness " << avgThick << " reached" );
+    debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
 
-    if ( distToIntersection < avgThick*1.5 )
+    if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
     {
       debugMsg( "-- Stop inflation since "
                 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
-                << avgThick << " ) * 1.5" );
+                << tgtThick * avgThick << " ) * " << safeFactor );
       break;
     }
     // new step size
@@ -2738,22 +3540,36 @@ bool _ViscousBuilder::inflate(_SolidData& data)
       data._stepSize = data._stepSizeCoeff *
         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
 
-  } // while ( 1.01 * avgThick < tgtThick )
+  } // while ( avgThick < 0.99 )
 
   if (nbSteps == 0 )
     return error("failed at the very first inflation step", data._index);
 
-  if ( 1.01 * avgThick < tgtThick )
-    if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( data._index ))
+  if ( avgThick < 0.99 )
+  {
+    if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
     {
-      SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
-      if ( !smError || smError->IsOK() )
-        smError.reset
-          ( new SMESH_ComputeError (COMPERR_WARNING,
-                                    SMESH_Comment("Thickness ") << tgtThick <<
-                                    " of viscous layers not reached,"
-                                    " average reached thickness is " << avgThick ));
+      data._proxyMesh->_warning.reset
+        ( new SMESH_ComputeError (COMPERR_WARNING,
+                                  SMESH_Comment("Thickness ") << tgtThick <<
+                                  " of viscous layers not reached,"
+                                  " average reached thickness is " << avgThick*tgtThick));
     }
+  }
+
+  // Restore position of src nodes moved by infaltion on _noShrinkShapes
+  dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
+  for ( iEnd = iS = 0; iS < data._endEdgeOnShape.size(); ++iS )
+  {
+    iBeg = iEnd;
+    iEnd = data._endEdgeOnShape[ iS ];
+    if ( data._edges[ iBeg ]->_nodes.size() == 1 )
+      for ( ; iBeg < iEnd; ++iBeg )
+      {
+        restoreNoShrink( *data._edges[ iBeg ] );
+      }
+  }
+  dumpFunctionEnd();
 
   return true;
 }
@@ -2772,6 +3588,7 @@ bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
     return true; // no shapes needing smoothing
 
   bool moved, improved;
+  vector< _LayerEdge* > badSmooEdges;
 
   SMESH_MesherHelper helper(*_mesh);
   Handle(Geom_Surface) surface;
@@ -2783,6 +3600,18 @@ bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
     iBeg = iEnd;
     iEnd = data._endEdgeOnShape[ iS ];
 
+    // need to smooth this shape?
+    bool toSmooth = ( data._hyps.front() == data._hyps.back() );
+    for ( int i = iBeg; i < iEnd && !toSmooth; ++i )
+      toSmooth = ( data._edges[ iBeg ]->NbSteps() >= nbSteps+1 );
+    if ( !toSmooth )
+    {
+      if ( iS+1 == data._nbShapesToSmooth )
+        data._nbShapesToSmooth--;
+      continue; // target length reached some steps before
+    }
+
+    // prepare data
     if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
          data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
     {
@@ -2796,7 +3625,9 @@ bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
     {
       F.Nullify(); surface.Nullify();
     }
-    TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
+    const TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
+
+    // perform smoothing
 
     if ( data._edges[ iBeg ]->IsOnEdge() )
     { 
@@ -2822,37 +3653,65 @@ bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
     else
     {
       // smooth on FACE's
-      int step = 0, stepLimit = 5, badNb = 0; moved = true;
-      while (( ++step <= stepLimit && moved ) || improved )
+
+      const bool isConcaveFace = data._concaveFaces.count( sInd );
+
+      int step = 0, stepLimit = 5, badNb = 0;
+      while (( ++step <= stepLimit ) || improved )
       {
         dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
                      <<"_InfStep"<<nbSteps<<"_"<<step); // debug
         int oldBadNb = badNb;
-        badNb = 0;
-        moved = false;
-        if ( step % 2 )
-          for ( int i = iBeg; i < iEnd; ++i )
-            moved |= data._edges[i]->Smooth(badNb);
-        else
-          for ( int i = iEnd-1; i >= iBeg; --i )
-            moved |= data._edges[i]->Smooth(badNb);
+        badSmooEdges.clear();
+
+        if ( step % 2 ) {
+          for ( int i = iBeg; i < iEnd; ++i ) // iterate forward
+            if ( data._edges[i]->Smooth( step, isConcaveFace, false ))
+              badSmooEdges.push_back( data._edges[i] );
+        }
+        else {
+          for ( int i = iEnd-1; i >= iBeg; --i ) // iterate backward
+            if ( data._edges[i]->Smooth( step, isConcaveFace, false ))
+              badSmooEdges.push_back( data._edges[i] );
+        }
+        badNb = badSmooEdges.size();
         improved = ( badNb < oldBadNb );
 
+        if ( !badSmooEdges.empty() && step >= stepLimit / 2 )
+        {
+          // look for the best smooth of _LayerEdge's neighboring badSmooEdges
+          vector<_Simplex> simplices;
+          for ( size_t i = 0; i < badSmooEdges.size(); ++i )
+          {
+            _LayerEdge* ledge = badSmooEdges[i];
+            _Simplex::GetSimplices( ledge->_nodes[0], simplices, data._ignoreFaceIds );
+            for ( size_t iS = 0; iS < simplices.size(); ++iS )
+            {
+              TNode2Edge::iterator n2e = data._n2eMap.find( simplices[iS]._nNext );
+              if ( n2e != data._n2eMap.end()) {
+                _LayerEdge* ledge2 = n2e->second;
+                if ( ledge2->_nodes[0]->getshapeId() == sInd )
+                  ledge2->Smooth( step, isConcaveFace, /*findBest=*/true );
+              }
+            }
+          }
+        }
         // issue 22576 -- no bad faces but still there are intersections to fix
-        if ( improved && badNb == 0 )
-          stepLimit = step + 3;
+        // if ( improved && badNb == 0 )
+        //   stepLimit = step + 3;
 
         dumpFunctionEnd();
       }
       if ( badNb > 0 )
       {
 #ifdef __myDEBUG
+        double vol = 0;
         for ( int i = iBeg; i < iEnd; ++i )
         {
           _LayerEdge* edge = data._edges[i];
           SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
           for ( size_t j = 0; j < edge->_simplices.size(); ++j )
-            if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
+            if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ, vol ))
             {
               cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
                    << " "<< edge->_simplices[j]._nPrev->GetID()
@@ -2905,6 +3764,11 @@ bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
         if ( convFace->_subIdToEdgeEnd.count ( data._edges[i]->_nodes[0]->getshapeId() ))
           continue;
 
+      // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
+      // ( avoid limiting the thickness on the case of issue 22576)
+      if ( intFace->getshapeId() == data._edges[i]->_nodes[0]->getshapeId() )
+        continue;
+
       distToIntersection = dist;
       iLE = i;
       closestFace = intFace;
@@ -2934,9 +3798,9 @@ bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge&    E,
                                                const int             iFrom,
                                                const int             iTo,
-                                               Handle(Geom_Surface)& surface,
                                                const TopoDS_Face&    F,
-                                               SMESH_MesherHelper&   helper)
+                                               SMESH_MesherHelper&   helper,
+                                               vector<_LayerEdge* >* edges)
 {
   TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
 
@@ -2944,6 +3808,9 @@ Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge&    E,
 
   if ( i2curve == _edge2curve.end() )
   {
+    if ( edges )
+      _edges.swap( *edges );
+
     // sort _LayerEdge's by position on the EDGE
     SortOnEdge( E, iFrom, iTo, helper );
 
@@ -2974,11 +3841,21 @@ Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge&    E,
           bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
         gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
 
-        SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
-        SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
-        const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
+        gp_Pnt p0, p1;
+        if ( iTo-iFrom > 1 ) {
+          p0 = SMESH_TNodeXYZ( _edges[iFrom]->_nodes[0] );
+          p1 = SMESH_TNodeXYZ( _edges[iFrom+1]->_nodes[0] );
+        }
+        else {
+          p0 = curve->Value( f );
+          p1 = curve->Value( l );
+        }
+        const double lineTol = 1e-2 * p0.Distance( p1 );
         for ( int i = 0; i < 3 && !isLine; ++i )
           isLine = ( size.Coord( i+1 ) <= lineTol );
+
+        if ( isLine )
+          line = new Geom_Line( gp::OX() ); // only type does matter
       }
       if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
       {
@@ -3025,6 +3902,9 @@ Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge&    E,
       }
     }
 
+    if ( edges )
+      _edges.swap( *edges );
+
     Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
     if ( isLine )
       res = line;
@@ -3056,12 +3936,22 @@ void _SolidData::SortOnEdge( const TopoDS_Edge&  E,
   for ( int i = iFrom; i < iTo; ++i, ++u2e )
     _edges[i] = u2e->second;
 
-  // set _2neibors according to the new order
+  Sort2NeiborsOnEdge( iFrom, iTo );
+}
+
+//================================================================================
+/*!
+ * \brief Set _2neibors according to the order of _LayerEdge on EDGE
+ */
+//================================================================================
+
+void _SolidData::Sort2NeiborsOnEdge( const int iFrom, const int iTo)
+{
   for ( int i = iFrom; i < iTo-1; ++i )
-    if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
+    if ( _edges[i]->_2neibors->tgtNode(1) != _edges[i+1]->_nodes.back() )
       _edges[i]->_2neibors->reverse();
-  if ( u2edge.size() > 1 &&
-       _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
+  if ( iTo - iFrom > 1 &&
+       _edges[iTo-1]->_2neibors->tgtNode(0) != _edges[iTo-2]->_nodes.back() )
     _edges[iTo-1]->_2neibors->reverse();
 }
 
@@ -3072,14 +3962,14 @@ void _SolidData::SortOnEdge( const TopoDS_Edge&  E,
 //================================================================================
 
 bool _SolidData::GetShapeEdges(const TGeomID shapeID,
-                               size_t &      edgesEnd,
+                               size_t &      iEdgesEnd,
                                int*          iBeg,
                                int*          iEnd ) const
 {
   int beg = 0, end = 0;
-  for ( edgesEnd = 0; edgesEnd < _endEdgeOnShape.size(); ++edgesEnd )
+  for ( iEdgesEnd = 0; iEdgesEnd < _endEdgeOnShape.size(); ++iEdgesEnd )
   {
-    end = _endEdgeOnShape[ edgesEnd ];
+    end = _endEdgeOnShape[ iEdgesEnd ];
     TGeomID sID = _edges[ beg ]->_nodes[0]->getshapeId();
     if ( sID == shapeID )
     {
@@ -3092,6 +3982,53 @@ bool _SolidData::GetShapeEdges(const TGeomID shapeID,
   return false;
 }
 
+//================================================================================
+/*!
+ * \brief Prepare data of the _LayerEdge for smoothing on FACE
+ */
+//================================================================================
+
+void _SolidData::PrepareEdgesToSmoothOnFace( _LayerEdge**       edgeBeg,
+                                             _LayerEdge**       edgeEnd,
+                                             const TopoDS_Face& face,
+                                             bool               substituteSrcNodes )
+{
+  set< TGeomID > vertices;
+  SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
+  if ( isConcave( face, helper, &vertices ))
+    _concaveFaces.insert( (*edgeBeg)->_nodes[0]->getshapeId() );
+
+  for ( _LayerEdge** edge = edgeBeg; edge != edgeEnd; ++edge )
+    (*edge)->_smooFunction = 0;
+
+  for ( ; edgeBeg != edgeEnd; ++edgeBeg )
+  {
+    _LayerEdge* edge = *edgeBeg;
+    _Simplex::GetSimplices
+      ( edge->_nodes[0], edge->_simplices, _ignoreFaceIds, this, /*sort=*/true );
+
+    edge->ChooseSmooFunction( vertices, _n2eMap );
+
+    double avgNormProj = 0, avgLen = 0;
+    for ( size_t i = 0; i < edge->_simplices.size(); ++i )
+    {
+      _Simplex& s = edge->_simplices[i];
+
+      gp_XYZ  vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
+      avgNormProj += edge->_normal * vec;
+      avgLen      += vec.Modulus();
+      if ( substituteSrcNodes )
+      {
+        s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
+        s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
+      }
+    }
+    avgNormProj /= edge->_simplices.size();
+    avgLen      /= edge->_simplices.size();
+    edge->_curvature = _Curvature::New( avgNormProj, avgLen );
+  }
+}
+
 //================================================================================
 /*!
  * \brief Add faces for smoothing
@@ -3128,10 +4065,25 @@ void _SolidData::AddShapesToSmooth( const set< TGeomID >& faceIDs )
   int iBeg, iEnd;
   for ( size_t i = _nbShapesToSmooth; i <= lastSmooth; ++i )
   {
-    vector< _LayerEdge* > & edgesVec = iEnds.count(i) ? smoothLE : nonSmoothLE;
+    bool toSmooth = iEnds.count(i);
+    vector< _LayerEdge* > & edgesVec = toSmooth ? smoothLE : nonSmoothLE;
     iBeg = i ? _endEdgeOnShape[ i-1 ] : 0;
     iEnd = _endEdgeOnShape[ i ];
-    edgesVec.insert( edgesVec.end(), _edges.begin() + iBeg, _edges.begin() + iEnd ); 
+    edgesVec.insert( edgesVec.end(), _edges.begin() + iBeg, _edges.begin() + iEnd );
+
+    // preparation for smoothing on FACE
+    if ( toSmooth && _edges[iBeg]->_nodes[0]->GetPosition()->GetDim() == 2 )
+    {
+      TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( _edges[iBeg]->_nodes[0],
+                                                              _proxyMesh->GetMeshDS() );
+      if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
+      {
+        PrepareEdgesToSmoothOnFace( &_edges[ iBeg ],
+                                    &_edges[ iEnd ],
+                                    TopoDS::Face( S ),
+                                    /*substituteSrcNodes=*/true );
+      }
+    }
   }
 
   iBeg = _nbShapesToSmooth ? _endEdgeOnShape[ _nbShapesToSmooth-1 ] : 0;
@@ -3168,7 +4120,7 @@ bool _ViscousBuilder::smoothAnalyticEdge( _SolidData&           data,
                                              helper.GetMeshDS());
   TopoDS_Edge E = TopoDS::Edge( S );
 
-  Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
+  Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, F, helper );
   if ( curve.IsNull() ) return false;
 
   // compute a relative length of segments
@@ -3187,8 +4139,8 @@ bool _ViscousBuilder::smoothAnalyticEdge( _SolidData&           data,
   {
     if ( F.IsNull() ) // 3D
     {
-      SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
-      SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
+      SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->tgtNode(0));
+      SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->tgtNode(1));
       for ( int i = iFrom; i < iTo; ++i )
       {
         double r = len[i-iFrom] / len.back();
@@ -3201,10 +4153,12 @@ bool _ViscousBuilder::smoothAnalyticEdge( _SolidData&           data,
     }
     else
     {
-      gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
-      gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
-      if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
-           data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
+      // gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->tgtNode(0));
+      // gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->tgtNode(1));
+      gp_XY uv0 = data._edges[iFrom]->_2neibors->_edges[0]->LastUV( F );
+      gp_XY uv1 = data._edges[iTo-1]->_2neibors->_edges[1]->LastUV( F );
+      if ( data._edges[iFrom]->_2neibors->tgtNode(0) ==
+           data._edges[iTo-1]->_2neibors->tgtNode(1) ) // closed edge
       {
         int iPeriodic = helper.GetPeriodicIndex();
         if ( iPeriodic == 1 || iPeriodic == 2 )
@@ -3241,8 +4195,8 @@ bool _ViscousBuilder::smoothAnalyticEdge( _SolidData&           data,
 
     if ( F.IsNull() ) // 3D
     {
-      if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
-           data._edges[iTo-1]->_2neibors->_nodes[1] )
+      if ( data._edges[iFrom]->_2neibors->tgtNode(0) ==
+           data._edges[iTo-1]->_2neibors->tgtNode(1) )
         return true; // closed EDGE - nothing to do
 
       return false; // TODO ???
@@ -3251,9 +4205,12 @@ bool _ViscousBuilder::smoothAnalyticEdge( _SolidData&           data,
     {
       const gp_XY center( center3D.X(), center3D.Y() );
 
-      gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
-      gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
-      gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
+      gp_XY uv0 = data._edges[iFrom]->_2neibors->_edges[0]->LastUV( F );
+      gp_XY uvM = data._edges[iFrom]->LastUV( F );
+      gp_XY uv1 = data._edges[iTo-1]->_2neibors->_edges[1]->LastUV( F );
+      // gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->tgtNode(0));
+      // gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
+      // gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->tgtNode(1));
       gp_Vec2d vec0( center, uv0 );
       gp_Vec2d vecM( center, uvM );
       gp_Vec2d vec1( center, uv1 );
@@ -3317,7 +4274,7 @@ bool _ViscousBuilder::updateNormals( _SolidData&         data,
       const SMDS_MeshNode* tgt1 = edge->_nodes.back();
       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
       {
-        const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
+        const SMDS_MeshNode* tgt2 = edge->_2neibors->tgtNode(j);
         pair< set< SMESH_TLink >::iterator, bool > link_isnew =
           extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
         if ( !link_isnew.second )
@@ -3529,8 +4486,8 @@ bool _ViscousBuilder::updateNormals( _SolidData&         data,
       edge1->SetNewLength( data._stepSize, helper );
       if ( edge1->IsOnEdge() )
       {
-        const SMDS_MeshNode * n1 = edge1->_2neibors->_edges[0]->_nodes[0];
-        const SMDS_MeshNode * n2 = edge1->_2neibors->_edges[1]->_nodes[0];
+        const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
+        const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
         edge1->SetDataByNeighbors( n1, n2, helper );
       }
 
@@ -3984,12 +4941,13 @@ bool _ConvexFace::GetCenterOfCurvature( _LayerEdge*         ledge,
 
 bool _ConvexFace::CheckPrisms() const
 {
+  double vol = 0;
   for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
   {
     const _LayerEdge* edge = _simplexTestEdges[i];
     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
-      if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
+      if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ, vol ))
       {
         debugMsg( "Bad simplex of _simplexTestEdges ("
                   << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
@@ -4161,10 +5119,11 @@ gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
   gp_XYZ orig = _pos.back();
   gp_XYZ dir;
   int iPrev = _pos.size() - 2;
+  const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
   while ( iPrev >= 0 )
   {
     dir = orig - _pos[iPrev];
-    if ( dir.SquareModulus() > 1e-100 )
+    if ( dir.SquareModulus() > tol*tol )
       break;
     else
       iPrev--;
@@ -4205,6 +5164,31 @@ gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
   return segDir;
 }
 
+//================================================================================
+/*!
+ * \brief Return the last position of the target node on a FACE. 
+ *  \param [in] F - the FACE this _LayerEdge is inflated along
+ *  \return gp_XY - result UV
+ */
+//================================================================================
+
+gp_XY _LayerEdge::LastUV( const TopoDS_Face& F ) const
+{
+  if ( F.IsSame( _sWOL )) // F is my FACE
+    return gp_XY( _pos.back().X(), _pos.back().Y() );
+
+  if ( _sWOL.IsNull() || _sWOL.ShapeType() != TopAbs_EDGE ) // wrong call
+    return gp_XY( 1e100, 1e100 );
+
+  // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
+  double f, l, u = _pos.back().X();
+  Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(_sWOL), F, f,l);
+  if ( !C2d.IsNull() && f <= u && u <= l )
+    return C2d->Value( u ).XY();
+
+  return gp_XY( 1e100, 1e100 );
+}
+
 //================================================================================
 /*!
  * \brief Test intersection of the last segment with a given triangle
@@ -4222,15 +5206,15 @@ bool _LayerEdge::SegTriaInter( const gp_Ax1&        lastSegment,
 {
   //const double EPSILON = 1e-6;
 
-  gp_XYZ orig = lastSegment.Location().XYZ();
-  gp_XYZ dir  = lastSegment.Direction().XYZ();
+  const gp_Pnt& orig = lastSegment.Location();
+  const gp_Dir& dir  = lastSegment.Direction();
 
   SMESH_TNodeXYZ vert0( n0 );
   SMESH_TNodeXYZ vert1( n1 );
   SMESH_TNodeXYZ vert2( n2 );
 
   /* calculate distance from vert0 to ray origin */
-  gp_XYZ tvec = orig - vert0;
+  gp_XYZ tvec = orig.XYZ() - vert0;
 
   //if ( tvec * dir > EPSILON )
     // intersected face is at back side of the temporary face this _LayerEdge belongs to
@@ -4240,17 +5224,16 @@ bool _LayerEdge::SegTriaInter( const gp_Ax1&        lastSegment,
   gp_XYZ edge2 = vert2 - vert0;
 
   /* begin calculating determinant - also used to calculate U parameter */
-  gp_XYZ pvec = dir ^ edge2;
+  gp_XYZ pvec = dir.XYZ() ^ edge2;
 
   /* if determinant is near zero, ray lies in plane of triangle */
   double det = edge1 * pvec;
 
   if (det > -EPSILON && det < EPSILON)
     return false;
-  double inv_det = 1.0 / det;
 
   /* calculate U parameter and test bounds */
-  double u = ( tvec * pvec ) * inv_det;
+  double u = ( tvec * pvec ) det;
   //if (u < 0.0 || u > 1.0)
   if (u < -EPSILON || u > 1.0 + EPSILON)
     return false;
@@ -4258,147 +5241,641 @@ bool _LayerEdge::SegTriaInter( const gp_Ax1&        lastSegment,
   /* prepare to test V parameter */
   gp_XYZ qvec = tvec ^ edge1;
 
-  /* calculate V parameter and test bounds */
-  double v = (dir * qvec) * inv_det;
-  //if ( v < 0.0 || u + v > 1.0 )
-  if ( v < -EPSILON || u + v > 1.0 + EPSILON)
-    return false;
+  /* calculate V parameter and test bounds */
+  double v = (dir.XYZ() * qvec) / det;
+  //if ( v < 0.0 || u + v > 1.0 )
+  if ( v < -EPSILON || u + v > 1.0 + EPSILON)
+    return false;
+
+  /* calculate t, ray intersects triangle */
+  t = (edge2 * qvec) / det;
+
+  //return true;
+  return t > 0.;
+}
+
+//================================================================================
+/*!
+ * \brief Perform smooth of _LayerEdge's based on EDGE's
+ *  \retval bool - true if node has been moved
+ */
+//================================================================================
+
+bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
+                              const TopoDS_Face&    F,
+                              SMESH_MesherHelper&   helper)
+{
+  ASSERT( IsOnEdge() );
+
+  SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
+  SMESH_TNodeXYZ oldPos( tgtNode );
+  double dist01, distNewOld;
+  
+  SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
+  SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
+  dist01 = p0.Distance( _2neibors->tgtNode(1) );
+
+  gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
+  double lenDelta = 0;
+  if ( _curvature )
+  {
+    //lenDelta = _curvature->lenDelta( _len );
+    lenDelta = _curvature->lenDeltaByDist( dist01 );
+    newPos.ChangeCoord() += _normal * lenDelta;
+  }
+
+  distNewOld = newPos.Distance( oldPos );
+
+  if ( F.IsNull() )
+  {
+    if ( _2neibors->_plnNorm )
+    {
+      // put newPos on the plane defined by source node and _plnNorm
+      gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
+      double new2srcProj = (*_2neibors->_plnNorm) * new2src;
+      newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
+    }
+    tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
+    _pos.back() = newPos.XYZ();
+  }
+  else
+  {
+    tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
+    gp_XY uv( Precision::Infinite(), 0 );
+    helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
+    _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
+
+    newPos = surface->Value( uv.X(), uv.Y() );
+    tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
+  }
+
+  // commented for IPAL0052478
+  // if ( _curvature && lenDelta < 0 )
+  // {
+  //   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
+  //   _len -= prevPos.Distance( oldPos );
+  //   _len += prevPos.Distance( newPos );
+  // }
+  bool moved = distNewOld > dist01/50;
+  //if ( moved )
+  dumpMove( tgtNode ); // debug
+
+  return moved;
+}
+
+//================================================================================
+/*!
+ * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
+ *  \retval bool - true if _tgtNode has been moved
+ */
+//================================================================================
+
+int _LayerEdge::Smooth(const int step, const bool isConcaveFace, const bool findBest )
+{
+  if ( _simplices.size() < 2 )
+    return 0; // _LayerEdge inflated along EDGE or FACE
+
+  const gp_XYZ& curPos ( _pos.back() );
+  const gp_XYZ& prevPos( _pos[ _pos.size()-2 ]);
+
+  // quality metrics (orientation) of tetras around _tgtNode
+  int nbOkBefore = 0;
+  double vol, minVolBefore = 1e100;
+  for ( size_t i = 0; i < _simplices.size(); ++i )
+  {
+    nbOkBefore += _simplices[i].IsForward( _nodes[0], &curPos, vol );
+    minVolBefore = Min( minVolBefore, vol );
+  }
+  int nbBad = _simplices.size() - nbOkBefore;
+
+  // compute new position for the last _pos using different _funs
+  gp_XYZ newPos;
+  for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
+  {
+    if ( iFun < 0 )
+      newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
+    else if ( _funs[ iFun ] == _smooFunction )
+      continue; // _smooFunction again
+    else if ( step > 0 )
+      newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
+    else
+      break; // let "easy" functions improve elements around distorted ones
+
+    if ( _curvature )
+    {
+      double delta  = _curvature->lenDelta( _len );
+      if ( delta > 0 )
+        newPos += _normal * delta;
+      else
+      {
+        double segLen = _normal * ( newPos - prevPos );
+        if ( segLen + delta > 0 )
+          newPos += _normal * delta;
+      }
+      // double segLenChange = _normal * ( curPos - newPos );
+      // newPos += 0.5 * _normal * segLenChange;
+    }
+
+    int nbOkAfter = 0;
+    double minVolAfter = 1e100;
+    for ( size_t i = 0; i < _simplices.size(); ++i )
+    {
+      nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos, vol );
+      minVolAfter = Min( minVolAfter, vol );
+    }
+    // get worse?
+    if ( nbOkAfter < nbOkBefore )
+      continue;
+    if (( isConcaveFace || findBest ) &&
+        ( nbOkAfter == nbOkBefore ) &&
+        //( iFun > -1 || nbOkAfter < _simplices.size() ) &&
+        ( minVolAfter <= minVolBefore ))
+      continue;
+
+    SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
+
+    // commented for IPAL0052478
+    // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
+    // _len += prevPos.Distance(newPos);
+
+    n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
+    _pos.back() = newPos;
+    dumpMoveComm( n, _funNames[ iFun < 0 ? smooFunID() : iFun ]);
+
+    nbBad = _simplices.size() - nbOkAfter;
+
+    if ( iFun > -1 )
+    {
+      //_smooFunction = _funs[ iFun ];
+      // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
+      // << "\t nbBad: " << _simplices.size() - nbOkAfter
+      // << " minVol: " << minVolAfter
+      // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
+      // << endl;
+      minVolBefore = minVolAfter;
+      nbOkBefore = nbOkAfter;
+      continue; // look for a better function
+    }
+
+    if ( !findBest )
+      break;
+
+  } // loop on smoothing functions
+
+  return nbBad;
+}
+
+//================================================================================
+/*!
+ * \brief Chooses a smoothing technic giving a position most close to an initial one.
+ *        For a correct result, _simplices must contain nodes lying on geometry.
+ */
+//================================================================================
+
+void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
+                                     const TNode2Edge&     n2eMap)
+{
+  if ( _smooFunction ) return;
+
+  // use smoothNefPolygon() near concaveVertices
+  if ( !concaveVertices.empty() )
+  {
+    for ( size_t i = 0; i < _simplices.size(); ++i )
+    {
+      if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
+      {
+        _smooFunction = _funs[ FUN_NEFPOLY ];
+
+        // set FUN_CENTROIDAL to neighbor edges
+        TNode2Edge::const_iterator n2e;
+        for ( i = 0; i < _simplices.size(); ++i )
+        {
+          if (( _simplices[i]._nPrev->GetPosition()->GetDim() == 2 ) &&
+              (( n2e = n2eMap.find( _simplices[i]._nPrev )) != n2eMap.end() ))
+          {
+            n2e->second->_smooFunction = _funs[ FUN_CENTROIDAL ];
+          }
+        }
+        return;
+      }
+    }
+    //}
+
+    // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
+    // where the nodes are smoothed too far along a sphere thus creating
+    // inverted _simplices
+    double dist[theNbSmooFuns];
+    //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
+    double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
+
+    double minDist = Precision::Infinite();
+    gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
+    for ( int i = 0; i < FUN_NEFPOLY; ++i )
+    {
+      gp_Pnt newP = (this->*_funs[i])();
+      dist[i] = p.SquareDistance( newP );
+      if ( dist[i]*coef[i] < minDist )
+      {
+        _smooFunction = _funs[i];
+        minDist = dist[i]*coef[i];
+      }
+    }
+  }
+  else
+  {
+    _smooFunction = _funs[ FUN_LAPLACIAN ];
+  }
+  // int minDim = 3;
+  // for ( size_t i = 0; i < _simplices.size(); ++i )
+  //   minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
+  // if ( minDim == 0 )
+  //   _smooFunction = _funs[ FUN_CENTROIDAL ];
+  // else if ( minDim == 1 )
+  //   _smooFunction = _funs[ FUN_CENTROIDAL ];
+
+
+  // int iMin;
+  // for ( int i = 0; i < FUN_NB; ++i )
+  // {
+  //   //cout << dist[i] << " ";
+  //   if ( _smooFunction == _funs[i] ) {
+  //     iMin = i;
+  //     //debugMsg( fNames[i] );
+  //     break;
+  //   }
+  // }
+  // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
+}
+
+//================================================================================
+/*!
+ * \brief Returns a name of _SmooFunction
+ */
+//================================================================================
+
+int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
+{
+  if ( !fun )
+    fun = _smooFunction;
+  for ( int i = 0; i < theNbSmooFuns; ++i )
+    if ( fun == _funs[i] )
+      return i;
+
+  return theNbSmooFuns;
+}
+
+//================================================================================
+/*!
+ * \brief Computes a new node position using Laplacian smoothing
+ */
+//================================================================================
+
+gp_XYZ _LayerEdge::smoothLaplacian()
+{
+  gp_XYZ newPos (0,0,0);
+  for ( size_t i = 0; i < _simplices.size(); ++i )
+    newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
+  newPos /= _simplices.size();
+
+  return newPos;
+}
+
+//================================================================================
+/*!
+ * \brief Computes a new node position using angular-based smoothing
+ */
+//================================================================================
+
+gp_XYZ _LayerEdge::smoothAngular()
+{
+  vector< gp_Vec > edgeDir;  edgeDir. reserve( _simplices.size() + 1);
+  vector< double > edgeSize; edgeSize.reserve( _simplices.size() );
+  vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
+
+  gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
+  gp_XYZ pN( 0,0,0 );
+  for ( size_t i = 0; i < _simplices.size(); ++i )
+  {
+    gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
+    edgeDir.push_back( p - pPrev );
+    edgeSize.push_back( edgeDir.back().Magnitude() );
+    //double edgeSize = edgeDir.back().Magnitude();
+    if ( edgeSize.back() < numeric_limits<double>::min() )
+    {
+      edgeDir.pop_back();
+      edgeSize.pop_back();
+    }
+    else
+    {
+      edgeDir.back() /= edgeSize.back();
+      points.push_back( p );
+      pN += p;
+    }
+    pPrev = p;
+  }
+  edgeDir.push_back ( edgeDir[0] );
+  edgeSize.push_back( edgeSize[0] );
+  pN /= points.size();
+
+  gp_XYZ newPos(0,0,0);
+  //gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
+  double sumSize = 0;
+  for ( size_t i = 0; i < points.size(); ++i )
+  {
+    gp_Vec toN( pN - points[i]);
+    double toNLen = toN.Magnitude();
+    if ( toNLen < numeric_limits<double>::min() )
+    {
+      newPos += pN;
+      continue;
+    }
+    gp_Vec bisec = edgeDir[i] + edgeDir[i+1];
+    double bisecLen = bisec.SquareMagnitude();
+    if ( bisecLen < numeric_limits<double>::min() )
+    {
+      gp_Vec norm = edgeDir[i] ^ toN;
+      bisec = norm ^ edgeDir[i];
+      bisecLen = bisec.SquareMagnitude();
+    }
+    bisecLen = Sqrt( bisecLen );
+    bisec /= bisecLen;
 
-  /* calculate t, ray intersects triangle */
-  t = (edge2 * qvec) * inv_det;
+#if 1
+    //bisecLen = 1.;
+    gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
+    sumSize += bisecLen;
+#else
+    gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
+    sumSize += ( edgeSize[i] + edgeSize[i+1] );
+#endif
+    newPos += pNew;
+  }
+  newPos /= sumSize;
 
-  //return true;
-  return t > 0.;
+  return newPos;
 }
 
 //================================================================================
 /*!
- * \brief Perform smooth of _LayerEdge's based on EDGE's
- *  \retval bool - true if node has been moved
+ * \brief Computes a new node position using weigthed node positions
  */
 //================================================================================
 
-bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
-                              const TopoDS_Face&    F,
-                              SMESH_MesherHelper&   helper)
+gp_XYZ _LayerEdge::smoothLengthWeighted()
 {
-  ASSERT( IsOnEdge() );
-
-  SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
-  SMESH_TNodeXYZ oldPos( tgtNode );
-  double dist01, distNewOld;
-  
-  SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
-  SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
-  dist01 = p0.Distance( _2neibors->_nodes[1] );
-
-  gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
-  double lenDelta = 0;
-  if ( _curvature )
-  {
-    //lenDelta = _curvature->lenDelta( _len );
-    lenDelta = _curvature->lenDeltaByDist( dist01 );
-    newPos.ChangeCoord() += _normal * lenDelta;
-  }
-
-  distNewOld = newPos.Distance( oldPos );
+  vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
+  vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
 
-  if ( F.IsNull() )
+  gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
+  for ( size_t i = 0; i < _simplices.size(); ++i )
   {
-    if ( _2neibors->_plnNorm )
+    gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
+    edgeSize.push_back( ( p - pPrev ).Modulus() );
+    if ( edgeSize.back() < numeric_limits<double>::min() )
     {
-      // put newPos on the plane defined by source node and _plnNorm
-      gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
-      double new2srcProj = (*_2neibors->_plnNorm) * new2src;
-      newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
+      edgeSize.pop_back();
     }
-    tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
-    _pos.back() = newPos.XYZ();
+    else
+    {
+      points.push_back( p );
+    }
+    pPrev = p;
   }
-  else
-  {
-    tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
-    gp_XY uv( Precision::Infinite(), 0 );
-    helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
-    _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
+  edgeSize.push_back( edgeSize[0] );
 
-    newPos = surface->Value( uv.X(), uv.Y() );
-    tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
+  gp_XYZ newPos(0,0,0);
+  double sumSize = 0;
+  for ( size_t i = 0; i < points.size(); ++i )
+  {
+    newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
+    sumSize += edgeSize[i] + edgeSize[i+1];
   }
+  newPos /= sumSize;
+  return newPos;
+}
 
-  if ( _curvature && lenDelta < 0 )
+//================================================================================
+/*!
+ * \brief Computes a new node position using angular-based smoothing
+ */
+//================================================================================
+
+gp_XYZ _LayerEdge::smoothCentroidal()
+{
+  gp_XYZ newPos(0,0,0);
+  gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
+  double sumSize = 0;
+  for ( size_t i = 0; i < _simplices.size(); ++i )
   {
-    gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
-    _len -= prevPos.Distance( oldPos );
-    _len += prevPos.Distance( newPos );
+    gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
+    gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
+    gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
+    double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
+
+    sumSize += size;
+    newPos += gc * size;
   }
-  bool moved = distNewOld > dist01/50;
-  //if ( moved )
-  dumpMove( tgtNode ); // debug
+  newPos /= sumSize;
 
-  return moved;
+  return newPos;
 }
 
 //================================================================================
 /*!
- * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
- *  \retval bool - true if _tgtNode has been moved
+ * \brief Computes a new node position located inside a Nef polygon
  */
 //================================================================================
 
-bool _LayerEdge::Smooth(int& badNb)
+gp_XYZ _LayerEdge::smoothNefPolygon()
 {
-  if ( _simplices.size() < 2 )
-    return false; // _LayerEdge inflated along EDGE or FACE
+  gp_XYZ newPos(0,0,0);
 
-  // compute new position for the last _pos
-  gp_XYZ newPos (0,0,0);
-  for ( size_t i = 0; i < _simplices.size(); ++i )
-    newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
-  newPos /= _simplices.size();
+  // get a plane to seach a solution on
 
-  const gp_XYZ& curPos ( _pos.back() );
-  const gp_Pnt  prevPos( _pos[ _pos.size()-2 ]);
-  if ( _curvature )
+  vector< gp_XYZ > vecs( _simplices.size() + 1 );
+  size_t i;
+  const double tol = numeric_limits<double>::min();
+  gp_XYZ center(0,0,0);
+  for ( i = 0; i < _simplices.size(); ++i )
   {
-    double delta  = _curvature->lenDelta( _len );
-    if ( delta > 0 )
-      newPos += _normal * delta;
-    else
-    {
-      double segLen = _normal * ( newPos - prevPos.XYZ() );
-      if ( segLen + delta > 0 )
-        newPos += _normal * delta;
-    }
-    // double segLenChange = _normal * ( curPos - newPos );
-    // newPos += 0.5 * _normal * segLenChange;
+    vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
+                SMESH_TNodeXYZ( _simplices[i]._nPrev ));
+    center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
   }
+  vecs.back() = vecs[0];
+  center /= _simplices.size();
 
-  // count quality metrics (orientation) of tetras around _tgtNode
-  int nbOkBefore = 0;
-  for ( size_t i = 0; i < _simplices.size(); ++i )
-    nbOkBefore += _simplices[i].IsForward( _nodes[0], &curPos );
+  gp_XYZ zAxis(0,0,0);
+  for ( i = 0; i < _simplices.size(); ++i )
+    zAxis += vecs[i] ^ vecs[i+1];
 
-  int nbOkAfter = 0;
+  gp_XYZ yAxis;
+  for ( i = 0; i < _simplices.size(); ++i )
+  {
+    yAxis = vecs[i];
+    if ( yAxis.SquareModulus() > tol )
+      break;
+  }
+  gp_XYZ xAxis = yAxis ^ zAxis;
+  // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
+  // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
+  //                             p0.Distance( _simplices[2]._nPrev ));
+  // gp_XYZ center = smoothLaplacian();
+  // gp_XYZ xAxis, yAxis, zAxis;
+  // for ( i = 0; i < _simplices.size(); ++i )
+  // {
+  //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
+  //   if ( xAxis.SquareModulus() > tol*tol )
+  //     break;
+  // }
+  // for ( i = 1; i < _simplices.size(); ++i )
+  // {
+  //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
+  //   zAxis = xAxis ^ yAxis;
+  //   if ( zAxis.SquareModulus() > tol*tol )
+  //     break;
+  // }
+  // if ( i == _simplices.size() ) return newPos;
+
+  yAxis = zAxis ^ xAxis;
+  xAxis /= xAxis.Modulus();
+  yAxis /= yAxis.Modulus();
+
+  // get half-planes of _simplices
+
+  vector< _halfPlane > halfPlns( _simplices.size() );
+  int nbHP = 0;
   for ( size_t i = 0; i < _simplices.size(); ++i )
-    nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
+  {
+    gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
+    gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
+    gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
+    gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
+    gp_XY  vec12 = p2 - p1;
+    double dist12 = vec12.Modulus();
+    if ( dist12 < tol )
+      continue;
+    vec12 /= dist12;
+    halfPlns[ nbHP ]._pos = p1;
+    halfPlns[ nbHP ]._dir = vec12;
+    halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
+    ++nbHP;
+  }
 
-  if ( nbOkAfter < nbOkBefore )
-    return false;
+  // intersect boundaries of half-planes, define state of intersection points
+  // in relation to all half-planes and calculate internal point of a 2D polygon
 
-  SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
+  double sumLen = 0;
+  gp_XY newPos2D (0,0);
 
-  _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
-  _len += prevPos.Distance(newPos);
+  enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
+  typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
+  TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
 
-  n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
-  _pos.back() = newPos;
+  vector< vector< TIntPntState > > allIntPnts( nbHP );
+  for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
+  {
+    vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
+    if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
 
-  badNb += _simplices.size() - nbOkAfter;
+    int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
+    int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
 
-  dumpMove( n );
+    int nbNotOut = 0;
+    const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
 
-  return true;
+    for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
+    {
+      if ( iHP1 == iHP2 ) continue;
+
+      TIntPntState & ips1 = intPnts1[ iHP2 ];
+      if ( ips1.second == UNDEF )
+      {
+        // find an intersection point of boundaries of iHP1 and iHP2
+
+        if ( iHP2 == iPrev ) // intersection with neighbors is known
+          ips1.first = halfPlns[ iHP1 ]._pos;
+        else if ( iHP2 == iNext )
+          ips1.first = halfPlns[ iHP2 ]._pos;
+        else if ( !halfPlns[ iHP1 ].FindInterestion( halfPlns[ iHP2 ], ips1.first ))
+          ips1.second = NO_INT;
+
+        // classify the found intersection point
+        if ( ips1.second != NO_INT )
+        {
+          ips1.second = NOT_OUT;
+          for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
+            if ( i != iHP1 && i != iHP2 &&
+                 halfPlns[ i ].IsOut( ips1.first, tol ))
+              ips1.second = IS_OUT;
+        }
+        vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
+        if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
+        TIntPntState & ips2 = intPnts2[ iHP1 ];
+        ips2 = ips1;
+      }
+      if ( ips1.second == NOT_OUT )
+      {
+        ++nbNotOut;
+        segEnds[ bool(segEnds[0]) ] = & ips1.first;
+      }
+    }
+
+    // find a NOT_OUT segment of boundary which is located between
+    // two NOT_OUT int points
+
+    if ( nbNotOut < 2 )
+      continue; // no such a segment
+
+    if ( nbNotOut > 2 )
+    {
+      // sort points along the boundary
+      map< double, TIntPntState* > ipsByParam;
+      for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
+      {
+        TIntPntState & ips1 = intPnts1[ iHP2 ];
+        if ( ips1.second != NO_INT )
+        {
+          gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
+          double param = op * halfPlns[ iHP1 ]._dir;
+          ipsByParam.insert( make_pair( param, & ips1 ));
+        }
+      }
+      // look for two neighboring NOT_OUT points
+      nbNotOut = 0;
+      map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
+      for ( ; u2ips != ipsByParam.end(); ++u2ips )
+      {
+        TIntPntState & ips1 = *(u2ips->second);
+        if ( ips1.second == NOT_OUT )
+          segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
+        else if ( nbNotOut >= 2 )
+          break;
+        else
+          nbNotOut = 0;
+      }
+    }
+
+    if ( nbNotOut >= 2 )
+    {
+      double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
+      sumLen += len;
+
+      newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
+    }
+  }
+
+  if ( sumLen > 0 )
+  {
+    newPos2D /= sumLen;
+    newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
+  }
+  else
+  {
+    newPos = center;
+  }
+
+  return newPos;
 }
 
 //================================================================================
@@ -4411,7 +5888,7 @@ void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
 {
   if ( _len - len > -1e-6 )
   {
-    _pos.push_back( _pos.back() );
+    //_pos.push_back( _pos.back() );
     return;
   }
 
@@ -4430,17 +5907,23 @@ void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
       double u = Precision::Infinite(); // to force projection w/o distance check
       helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
       _pos.back().SetCoord( u, 0, 0 );
-      SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
-      pos->SetUParameter( u );
+      if ( _nodes.size() > 1 )
+      {
+        SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
+        pos->SetUParameter( u );
+      }
     }
     else //  TopAbs_FACE
     {
       gp_XY uv( Precision::Infinite(), 0 );
       helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
-      SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
-      pos->SetUParameter( uv.X() );
-      pos->SetVParameter( uv.Y() );
+      if ( _nodes.size() > 1 )
+      {
+        SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
+        pos->SetUParameter( uv.X() );
+        pos->SetVParameter( uv.Y() );
+      }
     }
     n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
   }
@@ -4513,10 +5996,22 @@ bool _ViscousBuilder::refine(_SolidData& data)
   TNode2Edge* n2eMap = 0;
   TNode2Edge::iterator n2e;
 
+  // Create intermediate nodes on each _LayerEdge
+
+  int iS = 0, iEnd = data._endEdgeOnShape[ iS ];
+
   for ( size_t i = 0; i < data._edges.size(); ++i )
   {
     _LayerEdge& edge = *data._edges[i];
 
+    if ( edge._nodes.size() < 2 )
+      continue; // on _noShrinkShapes
+
+    // get parameters of layers for the edge
+    if ( i == iEnd )
+      iEnd = data._endEdgeOnShape[ ++iS ];
+    const AverageHyp& hyp = data._hypOnShape[ iS ];
+
     // get accumulated length of segments
     vector< double > segLen( edge._pos.size() );
     segLen[0] = 0.0;
@@ -4527,7 +6022,7 @@ bool _ViscousBuilder::refine(_SolidData& data)
     const SMDS_MeshNode* tgtNode = edge._nodes.back();
     if ( edge._nodes.size() == 2 )
     {
-      edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
+      edge._nodes.resize( hyp.GetNumberLayers() + 1, 0 );
       edge._nodes[1] = 0;
       edge._nodes.back() = tgtNode;
     }
@@ -4555,28 +6050,29 @@ bool _ViscousBuilder::refine(_SolidData& data)
       n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : n2eMap = s2ne->second;
       prevBaseId = baseShapeId;
     }
+    _LayerEdge* edgeOnSameNode = 0;
     if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
     {
-      _LayerEdge*  foundEdge = n2e->second;
-      const gp_XYZ& foundPos = foundEdge->_pos.back();
-      SMDS_PositionPtr lastPos = tgtNode->GetPosition();
+      edgeOnSameNode = n2e->second;
+      const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
+      SMDS_PositionPtr  lastPos = tgtNode->GetPosition();
       if ( isOnEdge )
       {
         SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
-        epos->SetUParameter( foundPos.X() );
+        epos->SetUParameter( otherTgtPos.X() );
       }
       else
       {
         SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
-        fpos->SetUParameter( foundPos.X() );
-        fpos->SetVParameter( foundPos.Y() );
+        fpos->SetUParameter( otherTgtPos.X() );
+        fpos->SetVParameter( otherTgtPos.Y() );
       }
     }
     // calculate height of the first layer
     double h0;
     const double T = segLen.back(); //data._hyp.GetTotalThickness();
-    const double f = data._hyp->GetStretchFactor();
-    const int    N = data._hyp->GetNumberLayers();
+    const double f = hyp.GetStretchFactor();
+    const int    N = hyp.GetNumberLayers();
     const double fPowN = pow( f, N );
     if ( fPowN - 1 <= numeric_limits<double>::min() )
       h0 = T / N;
@@ -4601,7 +6097,7 @@ bool _ViscousBuilder::refine(_SolidData& data)
       double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
       gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
 
-      SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
+      SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
       if ( !edge._sWOL.IsNull() )
       {
         // compute XYZ by parameters <pos>
@@ -4659,8 +6155,20 @@ bool _ViscousBuilder::refine(_SolidData& data)
         }
         node->setXYZ( pos.X(), pos.Y(), pos.Z() );
       }
+    } // loop on edge._nodes
+
+    if ( !edge._sWOL.IsNull() ) // prepare for shrink()
+    {
+      if ( isOnEdge )
+        edge._pos.back().SetCoord( u, 0,0);
+      else
+        edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
+
+      if ( edgeOnSameNode )
+        edgeOnSameNode->_pos.back() = edge._pos.back();
     }
-  }
+
+  } // loop on data._edges to create nodes
 
   if ( !getMeshDS()->IsEmbeddedMode() )
     // Log node movement
@@ -4671,50 +6179,154 @@ bool _ViscousBuilder::refine(_SolidData& data)
       getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
     }
 
-  // TODO: make quadratic prisms and polyhedrons(?)
+  // Create volumes
 
   helper.SetElementsOnShape(true);
 
+  vector< vector<const SMDS_MeshNode*>* > nnVec;
+  set< vector<const SMDS_MeshNode*>* >    nnSet;
+  set< int > degenEdgeInd;
+  vector<const SMDS_MeshElement*> degenVols;
+
   TopExp_Explorer exp( data._solid, TopAbs_FACE );
   for ( ; exp.More(); exp.Next() )
   {
-    if ( data._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
+    const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
+    if ( data._ignoreFaceIds.count( faceID ))
       continue;
-    SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
-    SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
-    vector< vector<const SMDS_MeshNode*>* > nnVec;
+    const bool isReversedFace = data._reversedFaceIds.count( faceID );
+    SMESHDS_SubMesh*    fSubM = getMeshDS()->MeshElements( exp.Current() );
+    SMDS_ElemIteratorPtr  fIt = fSubM->GetElements();
     while ( fIt->more() )
     {
       const SMDS_MeshElement* face = fIt->next();
-      int nbNodes = face->NbCornerNodes();
+      const int            nbNodes = face->NbCornerNodes();
       nnVec.resize( nbNodes );
-      SMDS_ElemIteratorPtr nIt = face->nodesIterator();
+      nnSet.clear();
+      degenEdgeInd.clear();
+      int nbZ = 0;
+      SMDS_NodeIteratorPtr nIt = face->nodeIterator();
       for ( int iN = 0; iN < nbNodes; ++iN )
       {
-        const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
-        nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
+        const SMDS_MeshNode* n = nIt->next();
+        const int i = isReversedFace ? nbNodes-1-iN : iN;
+        nnVec[ i ] = & data._n2eMap[ n ]->_nodes;
+        if ( nnVec[ i ]->size() < 2 )
+          degenEdgeInd.insert( iN );
+        else
+          nbZ = nnVec[ i ]->size();
+
+        if ( helper.HasDegeneratedEdges() )
+          nnSet.insert( nnVec[ i ]);
       }
+      if ( nbZ == 0 )
+        continue;
+      if ( 0 < nnSet.size() && nnSet.size() < 3 )
+        continue;
 
-      int nbZ = nnVec[0]->size();
       switch ( nbNodes )
       {
       case 3:
-        for ( int iZ = 1; iZ < nbZ; ++iZ )
-          helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
-                            (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
+        switch ( degenEdgeInd.size() )
+        {
+        case 0: // PENTA
+        {
+          for ( int iZ = 1; iZ < nbZ; ++iZ )
+            helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
+                              (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
+          break;
+        }
+        case 1: // PYRAM
+        {
+          int i2 = *degenEdgeInd.begin();
+          int i0 = helper.WrapIndex( i2 - 1, nbNodes );
+          int i1 = helper.WrapIndex( i2 + 1, nbNodes );
+          for ( int iZ = 1; iZ < nbZ; ++iZ )
+            helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
+                              (*nnVec[i1])[iZ],   (*nnVec[i0])[iZ],   (*nnVec[i2])[0]);
+          break;
+        }
+        case 2: // TETRA
+        {
+          int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
+          for ( int iZ = 1; iZ < nbZ; ++iZ )
+            helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
+                              (*nnVec[i3])[iZ]);
+          break;
+        }
+        }
         break;
+
       case 4:
-        for ( int iZ = 1; iZ < nbZ; ++iZ )
-          helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
-                            (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
-                            (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
-                            (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
+        switch ( degenEdgeInd.size() )
+        {
+        case 0: // HEX
+        {
+          for ( int iZ = 1; iZ < nbZ; ++iZ )
+            helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
+                              (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
+                              (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
+                              (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
+          break;
+        }
+        case 2: // PENTA?
+        {
+          int i2 = *degenEdgeInd.begin();
+          int i3 = *degenEdgeInd.rbegin();
+          bool ok = ( i3 - i2 == 1 );
+          if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
+          int i0 = helper.WrapIndex( i3 + 1, nbNodes );
+          int i1 = helper.WrapIndex( i0 + 1, nbNodes );
+          for ( int iZ = 1; iZ < nbZ; ++iZ )
+          {
+            const SMDS_MeshElement* vol =
+              helper.AddVolume( (*nnVec[i3])[0], (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
+                                (*nnVec[i2])[0], (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
+            if ( !ok && vol )
+              degenVols.push_back( vol );
+          }
+          break;
+        }
+        case 3: // degen HEX
+        {
+          const SMDS_MeshNode* nn[8];
+          for ( int iZ = 1; iZ < nbZ; ++iZ )
+          {
+            const SMDS_MeshElement* vol =
+              helper.AddVolume( nnVec[0]->size() > 1 ? (*nnVec[0])[iZ-1] : (*nnVec[0])[0],
+                                nnVec[1]->size() > 1 ? (*nnVec[1])[iZ-1] : (*nnVec[1])[0],
+                                nnVec[2]->size() > 1 ? (*nnVec[2])[iZ-1] : (*nnVec[2])[0],
+                                nnVec[3]->size() > 1 ? (*nnVec[3])[iZ-1] : (*nnVec[3])[0],
+                                nnVec[0]->size() > 1 ? (*nnVec[0])[iZ]   : (*nnVec[0])[0],
+                                nnVec[1]->size() > 1 ? (*nnVec[1])[iZ]   : (*nnVec[1])[0],
+                                nnVec[2]->size() > 1 ? (*nnVec[2])[iZ]   : (*nnVec[2])[0],
+                                nnVec[3]->size() > 1 ? (*nnVec[3])[iZ]   : (*nnVec[3])[0]);
+            degenVols.push_back( vol );
+          }
+        }
         break;
+        }
+        break;
+
       default:
         return error("Not supported type of element", data._index);
-      }
+
+      } // switch ( nbNodes )
+    } // while ( fIt->more() )
+  } // loop on FACEs
+
+  if ( !degenVols.empty() )
+  {
+    SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
+    if ( !err || err->IsOK() )
+    {
+      err.reset( new SMESH_ComputeError( COMPERR_WARNING,
+                                         "Degenerated volumes created" ));
+      err->myBadElements.insert( err->myBadElements.end(),
+                                 degenVols.begin(),degenVols.end() );
     }
   }
+
   return true;
 }
 
@@ -4760,20 +6372,19 @@ bool _ViscousBuilder::shrink()
 
   // EDGE's to shrink
   map< TGeomID, _Shrinker1D > e2shrMap;
+  vector< _LayerEdge* > lEdges;
 
   // loop on FACES to srink mesh on
   map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
   for ( ; f2sd != f2sdMap.end(); ++f2sd )
   {
-    _SolidData&     data = *f2sd->second;
-    TNode2Edge&   n2eMap = data._n2eMap;
-    const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
-
-    Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
-
+    _SolidData&      data = *f2sd->second;
+    const TopoDS_Face&  F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
 
+    Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
+
     helper.SetSubShape(F);
 
     // ===========================
@@ -4799,7 +6410,7 @@ bool _ViscousBuilder::shrink()
     if ( !smoothNodes.empty() )
     {
       vector<_Simplex> simplices;
-      getSimplices( smoothNodes[0], simplices, ignoreShapes );
+      _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
@@ -4808,23 +6419,30 @@ bool _ViscousBuilder::shrink()
     }
 
     // Find _LayerEdge's inflated along F
-    vector< _LayerEdge* > lEdges;
+    lEdges.clear();
     {
-      SMESH_subMeshIteratorPtr subIt =
-        sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
+      set< TGeomID > subIDs;
+      SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false);
       while ( subIt->more() )
+        subIDs.insert( subIt->next()->GetId() );
+
+      int iBeg, iEnd = 0;
+      for ( int iS = 0; iS < data._endEdgeOnShape.size() && !subIDs.empty(); ++iS )
       {
-        SMESH_subMesh*     sub = subIt->next();
-        SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
-        if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
-          continue;
-        SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
-        while ( nIt->more() )
-        {
-          _LayerEdge* edge = n2eMap[ nIt->next() ];
-          lEdges.push_back( edge );
-          prepareEdgeToShrink( *edge, F, helper, smDS );
-        }
+        iBeg = iEnd;
+        iEnd = data._endEdgeOnShape[ iS ];
+        TGeomID shapeID = data._edges[ iBeg ]->_nodes[0]->getshapeId();
+        set< TGeomID >::iterator idIt = subIDs.find( shapeID );
+        if ( idIt == subIDs.end() ||
+             data._edges[ iBeg ]->_sWOL.IsNull() ) continue;
+        subIDs.erase( idIt );
+
+        if ( !data._noShrinkShapes.count( shapeID ))
+          for ( ; iBeg < iEnd; ++iBeg )
+          {
+            lEdges.push_back( data._edges[ iBeg ] );
+            prepareEdgeToShrink( *data._edges[ iBeg ], F, helper, smDS );
+          }
       }
     }
 
@@ -4833,6 +6451,7 @@ bool _ViscousBuilder::shrink()
     while ( fIt->more() )
       if ( const SMDS_MeshElement* f = fIt->next() )
         dumpChangeNodes( f );
+    dumpFunctionEnd();
 
     // Replace source nodes by target nodes in mesh faces to shrink
     dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
@@ -4858,6 +6477,7 @@ bool _ViscousBuilder::shrink()
         dumpChangeNodes( f );
       }
     }
+    dumpFunctionEnd();
 
     // find out if a FACE is concave
     const bool isConcaveFace = isConcave( F, helper );
@@ -4872,11 +6492,12 @@ bool _ViscousBuilder::shrink()
         const SMDS_MeshNode* n = smoothNodes[i];
         nodesToSmooth[ i ]._node = n;
         // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
-        getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, sortSimplices );
+        _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
         // fix up incorrect uv of nodes on the FACE
         helper.GetNodeUV( F, n, 0, &isOkUV);
         dumpMove( n );
       }
+      dumpFunctionEnd();
     }
     //if ( nodesToSmooth.empty() ) continue;
 
@@ -4897,7 +6518,7 @@ bool _ViscousBuilder::shrink()
           // srinked while srinking another FACE
           srinker.RestoreParams();
         }
-        getSimplices( /*tgtNode=*/edge->_nodes.back(), edge->_simplices, ignoreShapes );
+        _Simplex::GetSimplices( /*tgtNode=*/edge->_nodes.back(), edge->_simplices, ignoreShapes );
       }
     }
 
@@ -4987,10 +6608,10 @@ bool _ViscousBuilder::shrink()
           n = usedNodes.find( nodesToSmooth[ i ]._node );
           if ( n != usedNodes.end())
           {
-            getSimplices( nodesToSmooth[ i ]._node,
-                          nodesToSmooth[ i ]._simplices,
-                          ignoreShapes, NULL,
-                          /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
+            _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
+                                    nodesToSmooth[ i ]._simplices,
+                                    ignoreShapes, NULL,
+                                    /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
             usedNodes.erase( n );
           }
         }
@@ -4999,9 +6620,9 @@ bool _ViscousBuilder::shrink()
           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
           if ( n != usedNodes.end())
           {
-            getSimplices( lEdges[i]->_nodes.back(),
-                          lEdges[i]->_simplices,
-                          ignoreShapes );
+            _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
+                                    lEdges[i]->_simplices,
+                                    ignoreShapes );
             usedNodes.erase( n );
           }
         }
@@ -5081,12 +6702,10 @@ bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
   const SMDS_MeshNode* srcNode = edge._nodes[0];
   const SMDS_MeshNode* tgtNode = edge._nodes.back();
 
-  edge._pos.clear();
-
   if ( edge._sWOL.ShapeType() == TopAbs_FACE )
   {
-    gp_XY srcUV = helper.GetNodeUV( F, srcNode );
-    gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
+    gp_XY srcUV( edge._pos[0].X(), edge._pos[0].Y() );//helper.GetNodeUV( F, srcNode );
+    gp_XY tgtUV = edge.LastUV( F );                   //helper.GetNodeUV( F, tgtNode );
     gp_Vec2d uvDir( srcUV, tgtUV );
     double uvLen = uvDir.Magnitude();
     uvDir /= uvLen;
@@ -5103,7 +6722,7 @@ bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
   }
   else // _sWOL is TopAbs_EDGE
   {
-    TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
+    const TopoDS_Edge&    E = TopoDS::Edge( edge._sWOL );
     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
     if ( !edgeSM || edgeSM->NbElements() == 0 )
       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
@@ -5122,7 +6741,9 @@ bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
 
     double uSrc = helper.GetNodeU( E, srcNode, n2 );
     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
-    double u2   = helper.GetNodeU( E, n2,      srcNode );
+    double u2   = helper.GetNodeU( E, n2, srcNode );
+
+    edge._pos.clear();
 
     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
     {
@@ -5137,13 +6758,56 @@ bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
     edge._simplices.resize( 1 );
     edge._simplices[0]._nPrev = n2;
 
-    // set UV of source node to target node
+    // set U of source node to the target node
     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
     pos->SetUParameter( uSrc );
   }
   return true;
 }
 
+//================================================================================
+/*!
+ * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
+ */
+//================================================================================
+
+void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
+{
+  if ( edge._nodes.size() == 1 )
+  {
+    edge._pos.clear();
+    edge._len = 0;
+
+    const SMDS_MeshNode* srcNode = edge._nodes[0];
+    TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
+    if ( S.IsNull() ) return;
+
+    gp_Pnt p;
+
+    switch ( S.ShapeType() )
+    {
+    case TopAbs_EDGE:
+    {
+      double f,l;
+      TopLoc_Location loc;
+      Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
+      if ( curve.IsNull() ) return;
+      SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
+      p = curve->Value( ePos->GetUParameter() );
+      break;
+    }
+    case TopAbs_VERTEX:
+    {
+      p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
+      break;
+    }
+    default: return;
+    }
+    getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
+    dumpMove( srcNode );
+  }
+}
+
 //================================================================================
 /*!
  * \brief Try to fix triangles with high aspect ratio by swaping diagonals
@@ -5360,11 +7024,11 @@ bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
   }
   else // _sWOL is TopAbs_EDGE
   {
-    TopoDS_Edge E = TopoDS::Edge( _sWOL );
-    const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
+    const TopoDS_Edge&      E = TopoDS::Edge( _sWOL );
+    const SMDS_MeshNode*   n2 = _simplices[0]._nPrev;
     SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
 
-    const double u2 = helper.GetNodeU( E, n2, tgtNode );
+    const double u2     = helper.GetNodeU( E, n2, tgtNode );
     const double uSrc   = _pos[0].Coord( U_SRC );
     const double lenTgt = _pos[0].Coord( LEN_TGT );
 
@@ -5525,7 +7189,7 @@ gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
   edgeSize.back() = edgeSize.front();
 
   gp_XY  newPos(0,0);
-  int    nbEdges = 0;
+  //int    nbEdges = 0;
   double sumSize = 0;
   for ( size_t i = 1; i < edgeDir.size(); ++i )
   {
@@ -5551,7 +7215,7 @@ gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
       distToN = -distToN;
 
     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
-    ++nbEdges;
+    //++nbEdges;
     sumSize += edgeSize[i1] + edgeSize[i];
   }
   newPos /= /*nbEdges * */sumSize;
@@ -5771,6 +7435,8 @@ bool _ViscousBuilder::addBoundaryElements()
 {
   SMESH_MesherHelper helper( *_mesh );
 
+  vector< const SMDS_MeshNode* > faceNodes;
+
   for ( size_t i = 0; i < _sdVec.size(); ++i )
   {
     _SolidData& data = _sdVec[i];
@@ -5779,6 +7445,8 @@ bool _ViscousBuilder::addBoundaryElements()
     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
     {
       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
+      if ( data._noShrinkShapes.count( getMeshDS()->ShapeToIndex( E )))
+        continue;
 
       // Get _LayerEdge's based on E
 
@@ -5811,8 +7479,13 @@ bool _ViscousBuilder::addBoundaryElements()
         if ( nbSharedPyram > 1 )
           continue; // not free border of the pyramid
 
-        if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
-                                    ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
+        faceNodes.clear();
+        faceNodes.push_back( ledges[0]->_nodes[0] );
+        faceNodes.push_back( ledges[1]->_nodes[0] );
+        if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
+        if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
+
+        if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
           continue; // faces already created
       }
       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
@@ -5862,12 +7535,33 @@ bool _ViscousBuilder::addBoundaryElements()
       {
         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
-        if ( isOnFace )
-          for ( size_t z = 1; z < nn1.size(); ++z )
-            sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
+        if ( nn1.size() == nn2.size() )
+        {
+          if ( isOnFace )
+            for ( size_t z = 1; z < nn1.size(); ++z )
+              sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
+          else
+            for ( size_t z = 1; z < nn1.size(); ++z )
+              sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
+        }
+        else if ( nn1.size() == 1 )
+        {
+          if ( isOnFace )
+            for ( size_t z = 1; z < nn2.size(); ++z )
+              sm->AddElement( getMeshDS()->AddFace( nn1[0], nn2[z-1], nn2[z] ));
+          else
+            for ( size_t z = 1; z < nn2.size(); ++z )
+              sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
+        }
         else
-          for ( size_t z = 1; z < nn1.size(); ++z )
-            sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));
+        {
+          if ( isOnFace )
+            for ( size_t z = 1; z < nn1.size(); ++z )
+              sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[0], nn1[z] ));
+          else
+            for ( size_t z = 1; z < nn1.size(); ++z )
+              sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
+        }
       }
 
       // Make edges
@@ -5877,7 +7571,7 @@ bool _ViscousBuilder::addBoundaryElements()
         if ( !edge->_sWOL.IsNull() && edge->_sWOL.ShapeType() == TopAbs_EDGE )
         {
           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
-          if ( nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
+          if ( nn.size() < 2 || nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
             continue;
           helper.SetSubShape( edge->_sWOL );
           helper.SetElementsOnShape( true );