Salome HOME
Regression of BelongToGeom on Debian-6
[modules/smesh.git] / src / StdMeshers / StdMeshers_ViscousLayers.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // File      : StdMeshers_ViscousLayers.cxx
21 // Created   : Wed Dec  1 15:15:34 2010
22 // Author    : Edward AGAPOV (eap)
23
24 #include "StdMeshers_ViscousLayers.hxx"
25
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "SMESHDS_Mesh.hxx"
34 #include "SMESH_Algo.hxx"
35 #include "SMESH_ComputeError.hxx"
36 #include "SMESH_ControlsDef.hxx"
37 #include "SMESH_Gen.hxx"
38 #include "SMESH_Group.hxx"
39 #include "SMESH_HypoFilter.hxx"
40 #include "SMESH_Mesh.hxx"
41 #include "SMESH_MeshAlgos.hxx"
42 #include "SMESH_MesherHelper.hxx"
43 #include "SMESH_ProxyMesh.hxx"
44 #include "SMESH_subMesh.hxx"
45 #include "SMESH_subMeshEventListener.hxx"
46 #include "StdMeshers_FaceSide.hxx"
47 #include "StdMeshers_ViscousLayers2D.hxx"
48
49 #include <Adaptor3d_HSurface.hxx>
50 #include <BRepAdaptor_Curve.hxx>
51 #include <BRepAdaptor_Curve2d.hxx>
52 #include <BRepAdaptor_Surface.hxx>
53 //#include <BRepLProp_CLProps.hxx>
54 #include <BRepLProp_SLProps.hxx>
55 #include <BRepOffsetAPI_MakeOffsetShape.hxx>
56 #include <BRep_Tool.hxx>
57 #include <Bnd_B2d.hxx>
58 #include <Bnd_B3d.hxx>
59 #include <ElCLib.hxx>
60 #include <GCPnts_AbscissaPoint.hxx>
61 #include <GCPnts_TangentialDeflection.hxx>
62 #include <Geom2d_Circle.hxx>
63 #include <Geom2d_Line.hxx>
64 #include <Geom2d_TrimmedCurve.hxx>
65 #include <GeomAdaptor_Curve.hxx>
66 #include <GeomLib.hxx>
67 #include <Geom_Circle.hxx>
68 #include <Geom_Curve.hxx>
69 #include <Geom_Line.hxx>
70 #include <Geom_TrimmedCurve.hxx>
71 #include <Precision.hxx>
72 #include <Standard_ErrorHandler.hxx>
73 #include <Standard_Failure.hxx>
74 #include <TColStd_Array1OfReal.hxx>
75 #include <TopExp.hxx>
76 #include <TopExp_Explorer.hxx>
77 #include <TopTools_IndexedMapOfShape.hxx>
78 #include <TopTools_ListOfShape.hxx>
79 #include <TopTools_MapIteratorOfMapOfShape.hxx>
80 #include <TopTools_MapOfShape.hxx>
81 #include <TopoDS.hxx>
82 #include <TopoDS_Edge.hxx>
83 #include <TopoDS_Face.hxx>
84 #include <TopoDS_Vertex.hxx>
85 #include <gp_Ax1.hxx>
86 #include <gp_Cone.hxx>
87 #include <gp_Sphere.hxx>
88 #include <gp_Vec.hxx>
89 #include <gp_XY.hxx>
90
91 #include <cmath>
92 #include <limits>
93 #include <list>
94 #include <queue>
95 #include <string>
96
97 #ifdef _DEBUG_
98 //#define __myDEBUG
99 //#define __NOT_INVALIDATE_BAD_SMOOTH
100 #endif
101
102 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
103 #define BLOCK_INFLATION // of individual _LayerEdge's
104 #define OLD_NEF_POLYGON
105
106 using namespace std;
107
108 //================================================================================
109 namespace VISCOUS_3D
110 {
111   typedef int TGeomID;
112
113   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
114
115   const double theMinSmoothCosin = 0.1;
116   const double theSmoothThickToElemSizeRatio = 0.3;
117   const double theMinSmoothTriaAngle = 30;
118   const double theMinSmoothQuadAngle = 45;
119
120   // what part of thickness is allowed till intersection
121   // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
122   const double theThickToIntersection = 1.5;
123
124   bool needSmoothing( double cosin, double tgtThick, double elemSize )
125   {
126     return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
127   }
128   double getSmoothingThickness( double cosin, double elemSize )
129   {
130     return theSmoothThickToElemSizeRatio * elemSize / cosin;
131   }
132
133   /*!
134    * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
135    * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
136    */
137   struct _MeshOfSolid : public SMESH_ProxyMesh,
138                         public SMESH_subMeshEventListenerData
139   {
140     bool                  _n2nMapComputed;
141     SMESH_ComputeErrorPtr _warning;
142
143     _MeshOfSolid( SMESH_Mesh* mesh)
144       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
145     {
146       SMESH_ProxyMesh::setMesh( *mesh );
147     }
148
149     // returns submesh for a geom face
150     SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
151     {
152       TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
153       return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
154     }
155     void setNode2Node(const SMDS_MeshNode*                 srcNode,
156                       const SMDS_MeshNode*                 proxyNode,
157                       const SMESH_ProxyMesh::SubMesh* subMesh)
158     {
159       SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
160     }
161   };
162   //--------------------------------------------------------------------------------
163   /*!
164    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
165    * It is used to clear an inferior dim sub-meshes modified by viscous layers
166    */
167   class _ShrinkShapeListener : SMESH_subMeshEventListener
168   {
169     _ShrinkShapeListener()
170       : SMESH_subMeshEventListener(/*isDeletable=*/false,
171                                    "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
172   public:
173     static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
174     virtual void ProcessEvent(const int                       event,
175                               const int                       eventType,
176                               SMESH_subMesh*                  solidSM,
177                               SMESH_subMeshEventListenerData* data,
178                               const SMESH_Hypothesis*         hyp)
179     {
180       if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
181       {
182         SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
183       }
184     }
185   };
186   //--------------------------------------------------------------------------------
187   /*!
188    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
189    * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
190    * delete the data as soon as it has been used
191    */
192   class _ViscousListener : SMESH_subMeshEventListener
193   {
194     _ViscousListener():
195       SMESH_subMeshEventListener(/*isDeletable=*/false,
196                                  "StdMeshers_ViscousLayers::_ViscousListener") {}
197     static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
198   public:
199     virtual void ProcessEvent(const int                       event,
200                               const int                       eventType,
201                               SMESH_subMesh*                  subMesh,
202                               SMESH_subMeshEventListenerData* data,
203                               const SMESH_Hypothesis*         hyp)
204     {
205       if (( SMESH_subMesh::COMPUTE_EVENT       == eventType ) &&
206           ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
207             SMESH_subMesh::SUBMESH_COMPUTED    != event ))
208       {
209         // delete SMESH_ProxyMesh containing temporary faces
210         subMesh->DeleteEventListener( this );
211       }
212     }
213     // Finds or creates proxy mesh of the solid
214     static _MeshOfSolid* GetSolidMesh(SMESH_Mesh*         mesh,
215                                       const TopoDS_Shape& solid,
216                                       bool                toCreate=false)
217     {
218       if ( !mesh ) return 0;
219       SMESH_subMesh* sm = mesh->GetSubMesh(solid);
220       _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
221       if ( !data && toCreate )
222       {
223         data = new _MeshOfSolid(mesh);
224         data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
225         sm->SetEventListener( Get(), data, sm );
226       }
227       return data;
228     }
229     // Removes proxy mesh of the solid
230     static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
231     {
232       mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
233     }
234   };
235   
236   //================================================================================
237   /*!
238    * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
239    * the main shape when sub-mesh of the main shape is cleared,
240    * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
241    * is cleared
242    */
243   //================================================================================
244
245   void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
246   {
247     SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
248     SMESH_subMeshEventListenerData* data =
249       mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
250     if ( data )
251     {
252       if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
253            data->mySubMeshes.end())
254         data->mySubMeshes.push_back( sub );
255     }
256     else
257     {
258       data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
259       sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
260     }
261   }
262   struct _SolidData;
263   //--------------------------------------------------------------------------------
264   /*!
265    * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
266    * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
267    * The class is used to check validity of face or volumes around a smoothed node;
268    * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
269    */
270   struct _Simplex
271   {
272     const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
273     const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
274     _Simplex(const SMDS_MeshNode* nPrev=0,
275              const SMDS_MeshNode* nNext=0,
276              const SMDS_MeshNode* nOpp=0)
277       : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
278     bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
279     {
280       const double M[3][3] =
281         {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
282          { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
283          { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
284       vol = ( + M[0][0] * M[1][1] * M[2][2]
285               + M[0][1] * M[1][2] * M[2][0]
286               + M[0][2] * M[1][0] * M[2][1]
287               - M[0][0] * M[1][2] * M[2][1]
288               - M[0][1] * M[1][0] * M[2][2]
289               - M[0][2] * M[1][1] * M[2][0]);
290       return vol > 1e-100;
291     }
292     bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
293     {
294       SMESH_TNodeXYZ pSrc( nSrc );
295       return IsForward( &pSrc, &pTgt, vol );
296     }
297     bool IsForward(const gp_XY&         tgtUV,
298                    const SMDS_MeshNode* smoothedNode,
299                    const TopoDS_Face&   face,
300                    SMESH_MesherHelper&  helper,
301                    const double         refSign) const
302     {
303       gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
304       gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
305       gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
306       double d = v1 ^ v2;
307       return d*refSign > 1e-100;
308     }
309     bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
310     {
311       SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
312       if ( !_nOpp ) // triangle
313       {
314         gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
315         double tp2 = tp.SquareMagnitude();
316         double pn2 = pn.SquareMagnitude();
317         double nt2 = nt.SquareMagnitude();
318
319         if ( tp2 < pn2 && tp2 < nt2 )
320           minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
321         else if ( pn2 < nt2 )
322           minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
323         else
324           minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
325
326         static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
327                                      Cos( theMinSmoothTriaAngle * M_PI / 180. ));
328         return minAngle < theMaxCos2;
329       }
330       else // quadrangle
331       {
332         SMESH_TNodeXYZ pOpp( _nOpp );
333         gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
334         double tp2 = tp.SquareMagnitude();
335         double po2 = po.SquareMagnitude();
336         double on2 = on.SquareMagnitude();
337         double nt2 = nt.SquareMagnitude();
338         minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
339                             (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
340                         Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
341                             (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
342
343         static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
344                                      Cos( theMinSmoothQuadAngle * M_PI / 180. ));
345         return minAngle < theMaxCos2;
346       }
347     }
348     bool IsNeighbour(const _Simplex& other) const
349     {
350       return _nPrev == other._nNext || _nNext == other._nPrev;
351     }
352     bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
353     static void GetSimplices( const SMDS_MeshNode* node,
354                               vector<_Simplex>&   simplices,
355                               const set<TGeomID>& ingnoreShapes,
356                               const _SolidData*   dataToCheckOri = 0,
357                               const bool          toSort = false);
358     static void SortSimplices(vector<_Simplex>& simplices);
359   };
360   //--------------------------------------------------------------------------------
361   /*!
362    * Structure used to take into account surface curvature while smoothing
363    */
364   struct _Curvature
365   {
366     double   _r; // radius
367     double   _k; // factor to correct node smoothed position
368     double   _h2lenRatio; // avgNormProj / (2*avgDist)
369     gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
370   public:
371     static _Curvature* New( double avgNormProj, double avgDist )
372     {
373       _Curvature* c = 0;
374       if ( fabs( avgNormProj / avgDist ) > 1./200 )
375       {
376         c = new _Curvature;
377         c->_r = avgDist * avgDist / avgNormProj;
378         c->_k = avgDist * avgDist / c->_r / c->_r;
379         //c->_k = avgNormProj / c->_r;
380         c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
381         c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
382
383         c->_uv.SetCoord( 0., 0. );
384       }
385       return c;
386     }
387     double lenDelta(double len) const { return _k * ( _r + len ); }
388     double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
389   };
390   //--------------------------------------------------------------------------------
391
392   struct _2NearEdges;
393   struct _LayerEdge;
394   struct _EdgesOnShape;
395   struct _Smoother1D;
396   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
397
398   //--------------------------------------------------------------------------------
399   /*!
400    * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
401    * and a node of the most internal layer (_nodes.back())
402    */
403   struct _LayerEdge
404   {
405     typedef gp_XYZ (_LayerEdge::*PSmooFun)();
406
407     vector< const SMDS_MeshNode*> _nodes;
408
409     gp_XYZ              _normal;    // to boundary of solid
410     vector<gp_XYZ>      _pos;       // points computed during inflation
411     double              _len;       // length achived with the last inflation step
412     double              _maxLen;    // maximal possible length
413     double              _cosin;     // of angle (_normal ^ surface)
414     double              _minAngle;  // of _simplices
415     double              _lenFactor; // to compute _len taking _cosin into account
416     int                 _flags;
417
418     // simplices connected to the source node (_nodes[0]);
419     // used for smoothing and quality check of _LayerEdge's based on the FACE
420     vector<_Simplex>    _simplices;
421     vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
422     PSmooFun            _smooFunction; // smoothing function
423     _Curvature*         _curvature;
424     // data for smoothing of _LayerEdge's based on the EDGE
425     _2NearEdges*        _2neibors;
426
427     enum EFlags { TO_SMOOTH       = 1,
428                   MOVED           = 2,   // set by _neibors[i]->SetNewLength()
429                   SMOOTHED        = 4,   // set by this->Smooth()
430                   DIFFICULT       = 8,   // near concave VERTEX
431                   ON_CONCAVE_FACE = 16,
432                   BLOCKED         = 32,  // not to inflate any more
433                   INTERSECTED     = 64,  // close intersection with a face found
434                   NORMAL_UPDATED  = 128,
435                   MARKED          = 256, // local usage
436                   MULTI_NORMAL    = 512, // a normal is invisible by some of surrounding faces
437                   NEAR_BOUNDARY   = 1024,// is near FACE boundary forcing smooth
438                   SMOOTHED_C1     = 2048,// is on _eosC1
439                   DISTORTED       = 4096,// was bad before smoothing
440                   RISKY_SWOL      = 8192 // SWOL is parallel to a source FACE
441     };
442     bool Is   ( EFlags f ) const { return _flags & f; }
443     void Set  ( EFlags f ) { _flags |= f; }
444     void Unset( EFlags f ) { _flags &= ~f; }
445
446     void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
447     bool SetNewLength2d( Handle(Geom_Surface)& surface,
448                          const TopoDS_Face&    F,
449                          _EdgesOnShape&        eos,
450                          SMESH_MesherHelper&   helper );
451     void SetDataByNeighbors( const SMDS_MeshNode* n1,
452                              const SMDS_MeshNode* n2,
453                              const _EdgesOnShape& eos,
454                              SMESH_MesherHelper&  helper);
455     void Block( _SolidData& data );
456     void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
457     void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
458                             const TNode2Edge&     n2eMap);
459     void SmoothPos( const vector< double >& segLen, const double tol );
460     int  Smooth(const int step, const bool isConcaveFace, bool findBest);
461     int  Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
462     int  CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
463     void SmoothWoCheck();
464     bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
465                       const TopoDS_Face&             F,
466                       SMESH_MesherHelper&            helper);
467     void MoveNearConcaVer( const _EdgesOnShape*    eov,
468                            const _EdgesOnShape*    eos,
469                            const int               step,
470                            vector< _LayerEdge* > & badSmooEdges);
471     bool FindIntersection( SMESH_ElementSearcher&   searcher,
472                            double &                 distance,
473                            const double&            epsilon,
474                            _EdgesOnShape&           eos,
475                            const SMDS_MeshElement** face = 0);
476     bool SegTriaInter( const gp_Ax1&        lastSegment,
477                        const gp_XYZ&        p0,
478                        const gp_XYZ&        p1,
479                        const gp_XYZ&        p2,
480                        double&              dist,
481                        const double&        epsilon) const;
482     bool SegTriaInter( const gp_Ax1&        lastSegment,
483                        const SMDS_MeshNode* n0,
484                        const SMDS_MeshNode* n1,
485                        const SMDS_MeshNode* n2,
486                        double&              dist,
487                        const double&        epsilon) const
488     { return SegTriaInter( lastSegment,
489                            SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
490                            dist, epsilon );
491     }
492     const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
493     const gp_XYZ& PrevCheckPos() const { return _pos[ Is( NORMAL_UPDATED ) ? _pos.size()-2 : 0 ]; }
494     gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
495     gp_XY  LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const;
496     bool   IsOnEdge() const { return _2neibors; }
497     gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
498     void   SetCosin( double cosin );
499     void   SetNormal( const gp_XYZ& n ) { _normal = n; }
500     int    NbSteps() const { return _pos.size() - 1; } // nb inlation steps
501     bool   IsNeiborOnEdge( const _LayerEdge* edge ) const;
502     void   SetSmooLen( double len ) { // set _len at which smoothing is needed
503       _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
504     }
505     double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
506
507     gp_XYZ smoothLaplacian();
508     gp_XYZ smoothAngular();
509     gp_XYZ smoothLengthWeighted();
510     gp_XYZ smoothCentroidal();
511     gp_XYZ smoothNefPolygon();
512
513     enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
514     static const int theNbSmooFuns = FUN_NB;
515     static PSmooFun _funs[theNbSmooFuns];
516     static const char* _funNames[theNbSmooFuns+1];
517     int smooFunID( PSmooFun fun=0) const;
518   };
519   _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
520                                                             &_LayerEdge::smoothLengthWeighted,
521                                                             &_LayerEdge::smoothCentroidal,
522                                                             &_LayerEdge::smoothNefPolygon,
523                                                             &_LayerEdge::smoothAngular };
524   const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
525                                                          "LengthWeighted",
526                                                          "Centroidal",
527                                                          "NefPolygon",
528                                                          "Angular",
529                                                          "None"};
530   struct _LayerEdgeCmp
531   {
532     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
533     {
534       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
535       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
536     }
537   };
538   //--------------------------------------------------------------------------------
539   /*!
540    * A 2D half plane used by _LayerEdge::smoothNefPolygon()
541    */
542   struct _halfPlane
543   {
544     gp_XY _pos, _dir, _inNorm;
545     bool IsOut( const gp_XY p, const double tol ) const
546     {
547       return _inNorm * ( p - _pos ) < -tol;
548     }
549     bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
550     {
551       //const double eps = 1e-10;
552       double D = _dir.Crossed( hp._dir );
553       if ( fabs(D) < std::numeric_limits<double>::min())
554         return false;
555       gp_XY vec21 = _pos - hp._pos; 
556       double u = hp._dir.Crossed( vec21 ) / D; 
557       intPnt = _pos + _dir * u;
558       return true;
559     }
560   };
561   //--------------------------------------------------------------------------------
562   /*!
563    * Structure used to smooth a _LayerEdge based on an EDGE.
564    */
565   struct _2NearEdges
566   {
567     double               _wgt  [2]; // weights of _nodes
568     _LayerEdge*          _edges[2];
569
570      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
571     gp_XYZ*              _plnNorm;
572
573     _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
574     const SMDS_MeshNode* tgtNode(bool is2nd) {
575       return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
576     }
577     const SMDS_MeshNode* srcNode(bool is2nd) {
578       return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
579     }
580     void reverse() {
581       std::swap( _wgt  [0], _wgt  [1] );
582       std::swap( _edges[0], _edges[1] );
583     }
584     void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
585       _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
586     }
587     bool include( const _LayerEdge* e ) {
588       return ( _edges[0] == e || _edges[1] == e );
589     }
590   };
591
592
593   //--------------------------------------------------------------------------------
594   /*!
595    * \brief Layers parameters got by averaging several hypotheses
596    */
597   struct AverageHyp
598   {
599     AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
600       :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
601     {
602       Add( hyp );
603     }
604     void Add( const StdMeshers_ViscousLayers* hyp )
605     {
606       if ( hyp )
607       {
608         _nbHyps++;
609         _nbLayers       = hyp->GetNumberLayers();
610         //_thickness     += hyp->GetTotalThickness();
611         _thickness      = Max( _thickness, hyp->GetTotalThickness() );
612         _stretchFactor += hyp->GetStretchFactor();
613         _method         = hyp->GetMethod();
614       }
615     }
616     double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
617     double GetStretchFactor()  const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
618     int    GetNumberLayers()   const { return _nbLayers; }
619     int    GetMethod()         const { return _method; }
620
621     bool   UseSurfaceNormal()  const
622     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
623     bool   ToSmooth()          const
624     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
625     bool   IsOffsetMethod()    const
626     { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
627
628   private:
629     int     _nbLayers, _nbHyps, _method;
630     double  _thickness, _stretchFactor;
631   };
632
633   //--------------------------------------------------------------------------------
634   /*!
635    * \brief _LayerEdge's on a shape and other shape data
636    */
637   struct _EdgesOnShape
638   {
639     vector< _LayerEdge* > _edges;
640
641     TopoDS_Shape          _shape;
642     TGeomID               _shapeID;
643     SMESH_subMesh *       _subMesh;
644     // face or edge w/o layer along or near which _edges are inflated
645     TopoDS_Shape          _sWOL;
646     bool                  _isRegularSWOL; // w/o singularities
647     // averaged StdMeshers_ViscousLayers parameters
648     AverageHyp            _hyp;
649     bool                  _toSmooth;
650     _Smoother1D*          _edgeSmoother;
651     vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
652     vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
653
654     vector< gp_XYZ >         _faceNormals; // if _shape is FACE
655     vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
656
657     Handle(ShapeAnalysis_Surface) _offsetSurf;
658     _LayerEdge*                   _edgeForOffset;
659
660     _SolidData*            _data; // parent SOLID
661
662     TopAbs_ShapeEnum ShapeType() const
663     { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
664     TopAbs_ShapeEnum SWOLType() const
665     { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
666     bool             HasC1( const _EdgesOnShape* other ) const
667     { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
668     bool             GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
669     _SolidData&      GetData() const { return *_data; }
670
671     _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
672   };
673
674   //--------------------------------------------------------------------------------
675   /*!
676    * \brief Convex FACE whose radius of curvature is less than the thickness of 
677    *        layers. It is used to detect distortion of prisms based on a convex
678    *        FACE and to update normals to enable further increasing the thickness
679    */
680   struct _ConvexFace
681   {
682     TopoDS_Face                     _face;
683
684     // edges whose _simplices are used to detect prism distortion
685     vector< _LayerEdge* >           _simplexTestEdges;
686
687     // map a sub-shape to _SolidData::_edgesOnShape
688     map< TGeomID, _EdgesOnShape* >  _subIdToEOS;
689
690     bool                            _normalsFixed;
691
692     bool GetCenterOfCurvature( _LayerEdge*         ledge,
693                                BRepLProp_SLProps&  surfProp,
694                                SMESH_MesherHelper& helper,
695                                gp_Pnt &            center ) const;
696     bool CheckPrisms() const;
697   };
698
699   //--------------------------------------------------------------------------------
700   /*!
701    * \brief Structure holding _LayerEdge's based on EDGEs that will collide
702    *        at inflation up to the full thickness. A detected collision
703    *        is fixed in updateNormals()
704    */
705   struct _CollisionEdges
706   {
707     _LayerEdge*           _edge;
708     vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
709     const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
710     const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
711   };
712
713   //--------------------------------------------------------------------------------
714   /*!
715    * \brief Data of a SOLID
716    */
717   struct _SolidData
718   {
719     typedef const StdMeshers_ViscousLayers* THyp;
720     TopoDS_Shape                    _solid;
721     TGeomID                         _index; // SOLID id
722     _MeshOfSolid*                   _proxyMesh;
723     list< THyp >                    _hyps;
724     list< TopoDS_Shape >            _hypShapes;
725     map< TGeomID, THyp >            _face2hyp; // filled if _hyps.size() > 1
726     set< TGeomID >                  _reversedFaceIds;
727     set< TGeomID >                  _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
728
729     double                          _stepSize, _stepSizeCoeff, _geomSize;
730     const SMDS_MeshNode*            _stepSizeNodes[2];
731
732     TNode2Edge                      _n2eMap; // nodes and _LayerEdge's based on them
733
734     // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
735     map< TGeomID, TNode2Edge* >     _s2neMap;
736     // _LayerEdge's with underlying shapes
737     vector< _EdgesOnShape >         _edgesOnShape;
738
739     // key:   an id of shape (EDGE or VERTEX) shared by a FACE with
740     //        layers and a FACE w/o layers
741     // value: the shape (FACE or EDGE) to shrink mesh on.
742     //       _LayerEdge's basing on nodes on key shape are inflated along the value shape
743     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
744
745     // Convex FACEs whose radius of curvature is less than the thickness of layers
746     map< TGeomID, _ConvexFace >      _convexFaces;
747
748     // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
749     // the adjacent SOLID
750     set< TGeomID >                   _noShrinkShapes;
751
752     int                              _nbShapesToSmooth;
753
754     //map< TGeomID,Handle(Geom_Curve)> _edge2curve;
755
756     vector< _CollisionEdges >        _collisionEdges;
757     set< TGeomID >                   _concaveFaces;
758
759     double                           _maxThickness; // of all _hyps
760     double                           _minThickness; // of all _hyps
761
762     double                           _epsilon; // precision for SegTriaInter()
763
764     SMESH_MesherHelper*              _helper;
765
766     _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
767                _MeshOfSolid*       m=0)
768       :_solid(s), _proxyMesh(m), _helper(0) {}
769     ~_SolidData();
770
771     void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
772     void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
773
774     _ConvexFace* GetConvexFace( const TGeomID faceID ) {
775       map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
776       return id2face == _convexFaces.end() ? 0 : & id2face->second;
777     }
778     _EdgesOnShape* GetShapeEdges(const TGeomID       shapeID );
779     _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
780     _EdgesOnShape* GetShapeEdges(const _LayerEdge*   edge )
781     { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
782
783     SMESH_MesherHelper& GetHelper() const { return *_helper; }
784
785     void UnmarkEdges() {
786       for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
787         for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
788           _edgesOnShape[i]._edges[j]->Unset( _LayerEdge::MARKED );
789     }
790     void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
791                             const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
792
793     void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
794   };
795   //--------------------------------------------------------------------------------
796   /*!
797    * \brief Offset plane used in getNormalByOffset()
798    */
799   struct _OffsetPlane
800   {
801     gp_Pln _plane;
802     int    _faceIndex;
803     int    _faceIndexNext[2];
804     gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
805     bool   _isLineOK[2];
806     _OffsetPlane() {
807       _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
808     }
809     void   ComputeIntersectionLine( _OffsetPlane& pln );
810     gp_XYZ GetCommonPoint(bool& isFound) const;
811     int    NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
812   };
813   //--------------------------------------------------------------------------------
814   /*!
815    * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
816    */
817   struct _CentralCurveOnEdge
818   {
819     bool                  _isDegenerated;
820     vector< gp_Pnt >      _curvaCenters;
821     vector< _LayerEdge* > _ledges;
822     vector< gp_XYZ >      _normals; // new normal for each of _ledges
823     vector< double >      _segLength2;
824
825     TopoDS_Edge           _edge;
826     TopoDS_Face           _adjFace;
827     bool                  _adjFaceToSmooth;
828
829     void Append( const gp_Pnt& center, _LayerEdge* ledge )
830     {
831       if ( _curvaCenters.size() > 0 )
832         _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
833       _curvaCenters.push_back( center );
834       _ledges.push_back( ledge );
835       _normals.push_back( ledge->_normal );
836     }
837     bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
838     void SetShapes( const TopoDS_Edge&  edge,
839                     const _ConvexFace&  convFace,
840                     _SolidData&         data,
841                     SMESH_MesherHelper& helper);
842   };
843   //--------------------------------------------------------------------------------
844   /*!
845    * \brief Data of node on a shrinked FACE
846    */
847   struct _SmoothNode
848   {
849     const SMDS_MeshNode*         _node;
850     vector<_Simplex>             _simplices; // for quality check
851
852     enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
853
854     bool Smooth(int&                  badNb,
855                 Handle(Geom_Surface)& surface,
856                 SMESH_MesherHelper&   helper,
857                 const double          refSign,
858                 SmoothType            how,
859                 bool                  set3D);
860
861     gp_XY computeAngularPos(vector<gp_XY>& uv,
862                             const gp_XY&   uvToFix,
863                             const double   refSign );
864   };
865   //--------------------------------------------------------------------------------
866   /*!
867    * \brief Builder of viscous layers
868    */
869   class _ViscousBuilder
870   {
871   public:
872     _ViscousBuilder();
873     // does it's job
874     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
875                                   const TopoDS_Shape& shape);
876     // check validity of hypotheses
877     SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh&         mesh,
878                                            const TopoDS_Shape& shape );
879
880     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
881     void RestoreListeners();
882
883     // computes SMESH_ProxyMesh::SubMesh::_n2n;
884     bool MakeN2NMap( _MeshOfSolid* pm );
885
886   private:
887
888     bool findSolidsWithLayers();
889     bool findFacesWithLayers(const bool onlyWith=false);
890     void getIgnoreFaces(const TopoDS_Shape&             solid,
891                         const StdMeshers_ViscousLayers* hyp,
892                         const TopoDS_Shape&             hypShape,
893                         set<TGeomID>&                   ignoreFaces);
894     bool makeLayer(_SolidData& data);
895     void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
896     bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
897                       SMESH_MesherHelper& helper, _SolidData& data);
898     gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
899                          const TopoDS_Face&   face,
900                          SMESH_MesherHelper&  helper,
901                          bool&                isOK,
902                          bool                 shiftInside=false);
903     bool getFaceNormalAtSingularity(const gp_XY&        uv,
904                                     const TopoDS_Face&  face,
905                                     SMESH_MesherHelper& helper,
906                                     gp_Dir&             normal );
907     gp_XYZ getWeigthedNormal( const _LayerEdge*                edge );
908     gp_XYZ getNormalByOffset( _LayerEdge*                      edge,
909                               std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
910                               int                              nbFaces );
911     bool findNeiborsOnEdge(const _LayerEdge*     edge,
912                            const SMDS_MeshNode*& n1,
913                            const SMDS_MeshNode*& n2,
914                            _EdgesOnShape&        eos,
915                            _SolidData&           data);
916     void findSimplexTestEdges( _SolidData&                    data,
917                                vector< vector<_LayerEdge*> >& edgesByGeom);
918     void computeGeomSize( _SolidData& data );
919     bool findShapesToSmooth( _SolidData& data);
920     void limitStepSizeByCurvature( _SolidData&  data );
921     void limitStepSize( _SolidData&             data,
922                         const SMDS_MeshElement* face,
923                         const _LayerEdge*       maxCosinEdge );
924     void limitStepSize( _SolidData& data, const double minSize);
925     bool inflate(_SolidData& data);
926     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
927     int  invalidateBadSmooth( _SolidData&               data,
928                               SMESH_MesherHelper&       helper,
929                               vector< _LayerEdge* >&    badSmooEdges,
930                               vector< _EdgesOnShape* >& eosC1,
931                               const int                 infStep );
932     void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
933     void putOnOffsetSurface( _EdgesOnShape& eos, int infStep, int smooStep=0, bool moveAll=false );
934     void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
935     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
936     bool updateNormalsOfConvexFaces( _SolidData&         data,
937                                      SMESH_MesherHelper& helper,
938                                      int                 stepNb );
939     void updateNormalsOfC1Vertices( _SolidData& data );
940     bool updateNormalsOfSmoothed( _SolidData&         data,
941                                   SMESH_MesherHelper& helper,
942                                   const int           nbSteps,
943                                   const double        stepSize );
944     bool isNewNormalOk( _SolidData&   data,
945                         _LayerEdge&   edge,
946                         const gp_XYZ& newNormal);
947     bool refine(_SolidData& data);
948     bool shrink();
949     bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
950                               SMESH_MesherHelper& helper,
951                               const SMESHDS_SubMesh* faceSubMesh );
952     void restoreNoShrink( _LayerEdge& edge ) const;
953     void fixBadFaces(const TopoDS_Face&          F,
954                      SMESH_MesherHelper&         helper,
955                      const bool                  is2D,
956                      const int                   step,
957                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
958     bool addBoundaryElements();
959
960     bool error( const string& text, int solidID=-1 );
961     SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
962
963     // debug
964     void makeGroupOfLE();
965
966     SMESH_Mesh*           _mesh;
967     SMESH_ComputeErrorPtr _error;
968
969     vector< _SolidData >  _sdVec;
970     int                   _tmpFaceID;
971   };
972   //--------------------------------------------------------------------------------
973   /*!
974    * \brief Shrinker of nodes on the EDGE
975    */
976   class _Shrinker1D
977   {
978     TopoDS_Edge                   _geomEdge;
979     vector<double>                _initU;
980     vector<double>                _normPar;
981     vector<const SMDS_MeshNode*>  _nodes;
982     const _LayerEdge*             _edges[2];
983     bool                          _done;
984   public:
985     void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
986     void Compute(bool set3D, SMESH_MesherHelper& helper);
987     void RestoreParams();
988     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
989     const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
990     const SMDS_MeshNode* TgtNode( bool is2nd ) const
991     { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
992     const SMDS_MeshNode* SrcNode( bool is2nd ) const
993     { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
994   };
995   //--------------------------------------------------------------------------------
996   /*!
997    * \brief Smoother of _LayerEdge's on EDGE.
998    */
999   struct _Smoother1D
1000   {
1001     struct OffPnt // point of the offsetted EDGE
1002     {
1003       gp_XYZ      _xyz;    // coord of a point inflated from EDGE w/o smooth
1004       double      _len;    // length reached at previous inflation step
1005       double      _param;  // on EDGE
1006       _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1007       double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1008     };
1009     vector< OffPnt >   _offPoints;
1010     vector< double >   _leParams; // normalized param of _eos._edges on EDGE
1011     Handle(Geom_Curve) _anaCurve; // for analytic smooth
1012     _LayerEdge         _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1013     size_t             _iSeg[2];  // index of segment where extreme tgt node is projected
1014     _EdgesOnShape&     _eos;
1015     double             _curveLen; // length of the EDGE
1016
1017     static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&  E,
1018                                               _EdgesOnShape&      eos,
1019                                               SMESH_MesherHelper& helper);
1020
1021     _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1022                  _EdgesOnShape&     eos )
1023       : _anaCurve( curveForSmooth ), _eos( eos )
1024     {
1025     }
1026     bool Perform(_SolidData&                    data,
1027                  Handle(ShapeAnalysis_Surface)& surface,
1028                  const TopoDS_Face&             F,
1029                  SMESH_MesherHelper&            helper )
1030     {
1031       if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
1032         prepare( data );
1033
1034       if ( isAnalytic() )
1035         return smoothAnalyticEdge( data, surface, F, helper );
1036       else
1037         return smoothComplexEdge ( data, surface, F, helper );
1038     }
1039     void prepare(_SolidData& data );
1040
1041     bool smoothAnalyticEdge( _SolidData&                    data,
1042                              Handle(ShapeAnalysis_Surface)& surface,
1043                              const TopoDS_Face&             F,
1044                              SMESH_MesherHelper&            helper);
1045
1046     bool smoothComplexEdge( _SolidData&                    data,
1047                             Handle(ShapeAnalysis_Surface)& surface,
1048                             const TopoDS_Face&             F,
1049                             SMESH_MesherHelper&            helper);
1050
1051     void setNormalOnV( const bool          is2nd,
1052                        SMESH_MesherHelper& helper);
1053
1054     _LayerEdge* getLEdgeOnV( bool is2nd )
1055     {
1056       return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1057     }
1058     bool isAnalytic() const { return !_anaCurve.IsNull(); }
1059   };
1060   //--------------------------------------------------------------------------------
1061   /*!
1062    * \brief Class of temporary mesh face.
1063    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1064    * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
1065    */
1066   struct _TmpMeshFace : public SMDS_MeshElement
1067   {
1068     vector<const SMDS_MeshNode* > _nn;
1069     _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1070                   int id, int faceID=-1, int idInFace=-1):
1071       SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); setIdInShape(idInFace); }
1072     virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
1073     virtual SMDSAbs_ElementType  GetType() const              { return SMDSAbs_Face; }
1074     virtual vtkIdType GetVtkType() const                      { return -1; }
1075     virtual SMDSAbs_EntityType   GetEntityType() const        { return SMDSEntity_Last; }
1076     virtual SMDSAbs_GeometryType GetGeomType() const
1077     { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
1078     virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
1079     { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
1080   };
1081   //--------------------------------------------------------------------------------
1082   /*!
1083    * \brief Class of temporary mesh face storing _LayerEdge it's based on
1084    */
1085   struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1086   {
1087     _LayerEdge *_le1, *_le2;
1088     _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1089       _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1090     {
1091       _nn[0]=_le1->_nodes[0];
1092       _nn[1]=_le1->_nodes.back();
1093       _nn[2]=_le2->_nodes.back();
1094       _nn[3]=_le2->_nodes[0];
1095     }
1096     gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1097     {
1098       SMESH_TNodeXYZ p0s( _nn[0] );
1099       SMESH_TNodeXYZ p0t( _nn[1] );
1100       SMESH_TNodeXYZ p1t( _nn[2] );
1101       SMESH_TNodeXYZ p1s( _nn[3] );
1102       gp_XYZ  v0 = p0t - p0s;
1103       gp_XYZ  v1 = p1t - p1s;
1104       gp_XYZ v01 = p1s - p0s;
1105       gp_XYZ   n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1106       gp_XYZ   d = v01 ^ n;
1107       d.Normalize();
1108       return d;
1109     }
1110     gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1111     {
1112       _nn[0]=le1->_nodes[0];
1113       _nn[1]=le1->_nodes.back();
1114       _nn[2]=le2->_nodes.back();
1115       _nn[3]=le2->_nodes[0];
1116       return GetDir();
1117     }
1118   };
1119   //--------------------------------------------------------------------------------
1120   /*!
1121    * \brief Retriever of node coordinates either directly or from a surface by node UV.
1122    * \warning Location of a surface is ignored
1123    */
1124   struct _NodeCoordHelper
1125   {
1126     SMESH_MesherHelper&        _helper;
1127     const TopoDS_Face&         _face;
1128     Handle(Geom_Surface)       _surface;
1129     gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1130
1131     _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1132       : _helper( helper ), _face( F )
1133     {
1134       if ( is2D )
1135       {
1136         TopLoc_Location loc;
1137         _surface = BRep_Tool::Surface( _face, loc );
1138       }
1139       if ( _surface.IsNull() )
1140         _fun = & _NodeCoordHelper::direct;
1141       else
1142         _fun = & _NodeCoordHelper::byUV;
1143     }
1144     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1145
1146   private:
1147     gp_XYZ direct(const SMDS_MeshNode* n) const
1148     {
1149       return SMESH_TNodeXYZ( n );
1150     }
1151     gp_XYZ byUV  (const SMDS_MeshNode* n) const
1152     {
1153       gp_XY uv = _helper.GetNodeUV( _face, n );
1154       return _surface->Value( uv.X(), uv.Y() ).XYZ();
1155     }
1156   };
1157
1158   //================================================================================
1159   /*!
1160    * \brief Check angle between vectors 
1161    */
1162   //================================================================================
1163
1164   inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1165   {
1166     double dot = v1 * v2; // cos * |v1| * |v2|
1167     double l1  = v1.SquareMagnitude();
1168     double l2  = v2.SquareMagnitude();
1169     return (( dot * cos >= 0 ) && 
1170             ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1171   }
1172
1173 } // namespace VISCOUS_3D
1174
1175
1176
1177 //================================================================================
1178 // StdMeshers_ViscousLayers hypothesis
1179 //
1180 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
1181   :SMESH_Hypothesis(hypId, studyId, gen),
1182    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1183    _method( SURF_OFFSET_SMOOTH )
1184 {
1185   _name = StdMeshers_ViscousLayers::GetHypType();
1186   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1187 } // --------------------------------------------------------------------------------
1188 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1189 {
1190   if ( faceIds != _shapeIds )
1191     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1192   if ( _isToIgnoreShapes != toIgnore )
1193     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1194 } // --------------------------------------------------------------------------------
1195 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1196 {
1197   if ( thickness != _thickness )
1198     _thickness = thickness, NotifySubMeshesHypothesisModification();
1199 } // --------------------------------------------------------------------------------
1200 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1201 {
1202   if ( _nbLayers != nb )
1203     _nbLayers = nb, NotifySubMeshesHypothesisModification();
1204 } // --------------------------------------------------------------------------------
1205 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1206 {
1207   if ( _stretchFactor != factor )
1208     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1209 } // --------------------------------------------------------------------------------
1210 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1211 {
1212   if ( _method != method )
1213     _method = method, NotifySubMeshesHypothesisModification();
1214 } // --------------------------------------------------------------------------------
1215 SMESH_ProxyMesh::Ptr
1216 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
1217                                   const TopoDS_Shape& theShape,
1218                                   const bool          toMakeN2NMap) const
1219 {
1220   using namespace VISCOUS_3D;
1221   _ViscousBuilder bulder;
1222   SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
1223   if ( err && !err->IsOK() )
1224     return SMESH_ProxyMesh::Ptr();
1225
1226   vector<SMESH_ProxyMesh::Ptr> components;
1227   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1228   for ( ; exp.More(); exp.Next() )
1229   {
1230     if ( _MeshOfSolid* pm =
1231          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1232     {
1233       if ( toMakeN2NMap && !pm->_n2nMapComputed )
1234         if ( !bulder.MakeN2NMap( pm ))
1235           return SMESH_ProxyMesh::Ptr();
1236       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1237       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1238
1239       if ( pm->_warning && !pm->_warning->IsOK() )
1240       {
1241         SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1242         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1243         if ( !smError || smError->IsOK() )
1244           smError = pm->_warning;
1245       }
1246     }
1247     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1248   }
1249   switch ( components.size() )
1250   {
1251   case 0: break;
1252
1253   case 1: return components[0];
1254
1255   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1256   }
1257   return SMESH_ProxyMesh::Ptr();
1258 } // --------------------------------------------------------------------------------
1259 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1260 {
1261   save << " " << _nbLayers
1262        << " " << _thickness
1263        << " " << _stretchFactor
1264        << " " << _shapeIds.size();
1265   for ( size_t i = 0; i < _shapeIds.size(); ++i )
1266     save << " " << _shapeIds[i];
1267   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1268   save << " " << _method;
1269   return save;
1270 } // --------------------------------------------------------------------------------
1271 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1272 {
1273   int nbFaces, faceID, shapeToTreat, method;
1274   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1275   while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1276     _shapeIds.push_back( faceID );
1277   if ( load >> shapeToTreat ) {
1278     _isToIgnoreShapes = !shapeToTreat;
1279     if ( load >> method )
1280       _method = (ExtrusionMethod) method;
1281   }
1282   else {
1283     _isToIgnoreShapes = true; // old behavior
1284   }
1285   return load;
1286 } // --------------------------------------------------------------------------------
1287 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
1288                                                    const TopoDS_Shape& theShape)
1289 {
1290   // TODO
1291   return false;
1292 } // --------------------------------------------------------------------------------
1293 SMESH_ComputeErrorPtr
1294 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh&                          theMesh,
1295                                           const TopoDS_Shape&                  theShape,
1296                                           SMESH_Hypothesis::Hypothesis_Status& theStatus)
1297 {
1298   VISCOUS_3D::_ViscousBuilder bulder;
1299   SMESH_ComputeErrorPtr err = bulder.CheckHypotheses( theMesh, theShape );
1300   if ( err && !err->IsOK() )
1301     theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1302   else
1303     theStatus = SMESH_Hypothesis::HYP_OK;
1304
1305   return err;
1306 }
1307 // --------------------------------------------------------------------------------
1308 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1309 {
1310   bool isIn =
1311     ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1312   return IsToIgnoreShapes() ? !isIn : isIn;
1313 }
1314 // END StdMeshers_ViscousLayers hypothesis
1315 //================================================================================
1316
1317 namespace VISCOUS_3D
1318 {
1319   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1320   {
1321     gp_Vec dir;
1322     double f,l;
1323     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1324     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1325     gp_Pnt p = BRep_Tool::Pnt( fromV );
1326     double distF = p.SquareDistance( c->Value( f ));
1327     double distL = p.SquareDistance( c->Value( l ));
1328     c->D1(( distF < distL ? f : l), p, dir );
1329     if ( distL < distF ) dir.Reverse();
1330     return dir.XYZ();
1331   }
1332   //--------------------------------------------------------------------------------
1333   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1334                      SMESH_MesherHelper& helper)
1335   {
1336     gp_Vec dir;
1337     double f,l; gp_Pnt p;
1338     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1339     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1340     double u = helper.GetNodeU( E, atNode );
1341     c->D1( u, p, dir );
1342     return dir.XYZ();
1343   }
1344   //--------------------------------------------------------------------------------
1345   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1346                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1347                      double* cosin=0);
1348   //--------------------------------------------------------------------------------
1349   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1350                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1351   {
1352     double f,l;
1353     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1354     if ( c.IsNull() )
1355     {
1356       TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1357       return getFaceDir( F, v, node, helper, ok );
1358     }
1359     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1360     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1361     gp_Pnt p; gp_Vec du, dv, norm;
1362     surface->D1( uv.X(),uv.Y(), p, du,dv );
1363     norm = du ^ dv;
1364
1365     double u = helper.GetNodeU( fromE, node, 0, &ok );
1366     c->D1( u, p, du );
1367     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1368     if ( o == TopAbs_REVERSED )
1369       du.Reverse();
1370
1371     gp_Vec dir = norm ^ du;
1372
1373     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1374          helper.IsClosedEdge( fromE ))
1375     {
1376       if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1377       else                        c->D1( f, p, dv );
1378       if ( o == TopAbs_REVERSED )
1379         dv.Reverse();
1380       gp_Vec dir2 = norm ^ dv;
1381       dir = dir.Normalized() + dir2.Normalized();
1382     }
1383     return dir.XYZ();
1384   }
1385   //--------------------------------------------------------------------------------
1386   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1387                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1388                      bool& ok, double* cosin)
1389   {
1390     TopoDS_Face faceFrw = F;
1391     faceFrw.Orientation( TopAbs_FORWARD );
1392     //double f,l; TopLoc_Location loc;
1393     TopoDS_Edge edges[2]; // sharing a vertex
1394     size_t nbEdges = 0;
1395     {
1396       TopoDS_Vertex VV[2];
1397       TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1398       for ( ; exp.More() && nbEdges < 2; exp.Next() )
1399       {
1400         const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1401         if ( SMESH_Algo::isDegenerated( e )) continue;
1402         TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1403         if ( VV[1].IsSame( fromV )) {
1404           nbEdges += edges[ 0 ].IsNull();
1405           edges[ 0 ] = e;
1406         }
1407         else if ( VV[0].IsSame( fromV )) {
1408           nbEdges += edges[ 1 ].IsNull();
1409           edges[ 1 ] = e;
1410         }
1411       }
1412     }
1413     gp_XYZ dir(0,0,0), edgeDir[2];
1414     if ( nbEdges == 2 )
1415     {
1416       // get dirs of edges going fromV
1417       ok = true;
1418       for ( size_t i = 0; i < nbEdges && ok; ++i )
1419       {
1420         edgeDir[i] = getEdgeDir( edges[i], fromV );
1421         double size2 = edgeDir[i].SquareModulus();
1422         if (( ok = size2 > numeric_limits<double>::min() ))
1423           edgeDir[i] /= sqrt( size2 );
1424       }
1425       if ( !ok ) return dir;
1426
1427       // get angle between the 2 edges
1428       gp_Vec faceNormal;
1429       double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1430       if ( Abs( angle ) < 5 * M_PI/180 )
1431       {
1432         dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1433       }
1434       else
1435       {
1436         dir = edgeDir[0] + edgeDir[1];
1437         if ( angle < 0 )
1438           dir.Reverse();
1439       }
1440       if ( cosin ) {
1441         double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1442         *cosin = Cos( angle );
1443       }
1444     }
1445     else if ( nbEdges == 1 )
1446     {
1447       dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1448       if ( cosin ) *cosin = 1.;
1449     }
1450     else
1451     {
1452       ok = false;
1453     }
1454
1455     return dir;
1456   }
1457
1458   //================================================================================
1459   /*!
1460    * \brief Finds concave VERTEXes of a FACE
1461    */
1462   //================================================================================
1463
1464   bool getConcaveVertices( const TopoDS_Face&  F,
1465                            SMESH_MesherHelper& helper,
1466                            set< TGeomID >*     vertices = 0)
1467   {
1468     // check angles at VERTEXes
1469     TError error;
1470     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1471     for ( size_t iW = 0; iW < wires.size(); ++iW )
1472     {
1473       const int nbEdges = wires[iW]->NbEdges();
1474       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1475         continue;
1476       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1477       {
1478         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1479         int iE2 = ( iE1 + 1 ) % nbEdges;
1480         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1481           iE2 = ( iE2 + 1 ) % nbEdges;
1482         TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1483         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1484                                         wires[iW]->Edge( iE2 ), F, V );
1485         if ( angle < -5. * M_PI / 180. )
1486         {
1487           if ( !vertices )
1488             return true;
1489           vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1490         }
1491       }
1492     }
1493     return vertices ? !vertices->empty() : false;
1494   }
1495
1496   //================================================================================
1497   /*!
1498    * \brief Returns true if a FACE is bound by a concave EDGE
1499    */
1500   //================================================================================
1501
1502   bool isConcave( const TopoDS_Face&  F,
1503                   SMESH_MesherHelper& helper,
1504                   set< TGeomID >*     vertices = 0 )
1505   {
1506     bool isConcv = false;
1507     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1508     //   return true;
1509     gp_Vec2d drv1, drv2;
1510     gp_Pnt2d p;
1511     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1512     for ( ; eExp.More(); eExp.Next() )
1513     {
1514       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1515       if ( SMESH_Algo::isDegenerated( E )) continue;
1516       // check if 2D curve is concave
1517       BRepAdaptor_Curve2d curve( E, F );
1518       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1519       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1520       curve.Intervals( intervals, GeomAbs_C2 );
1521       bool isConvex = true;
1522       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1523       {
1524         double u1 = intervals( i );
1525         double u2 = intervals( i+1 );
1526         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1527         double cross = drv1 ^ drv2;
1528         if ( E.Orientation() == TopAbs_REVERSED )
1529           cross = -cross;
1530         isConvex = ( cross > -1e-9 ); // 0.1 );
1531       }
1532       if ( !isConvex )
1533       {
1534         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1535         isConcv = true;
1536         if ( vertices )
1537           break;
1538         else
1539           return true;
1540       }
1541     }
1542
1543     // check angles at VERTEXes
1544     if ( getConcaveVertices( F, helper, vertices ))
1545       isConcv = true;
1546
1547     return isConcv;
1548   }
1549
1550   //================================================================================
1551   /*!
1552    * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1553    *  \param [in] face - the mesh face to treat
1554    *  \param [in] nodeOnEdge - a node on the EDGE
1555    *  \param [out] faceSize - the computed distance
1556    *  \return bool - true if faceSize computed
1557    */
1558   //================================================================================
1559
1560   bool getDistFromEdge( const SMDS_MeshElement* face,
1561                         const SMDS_MeshNode*    nodeOnEdge,
1562                         double &                faceSize )
1563   {
1564     faceSize = Precision::Infinite();
1565     bool done = false;
1566
1567     int nbN  = face->NbCornerNodes();
1568     int iOnE = face->GetNodeIndex( nodeOnEdge );
1569     int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1570                      SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1571     const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1572                                       face->GetNode( iNext[1] ) };
1573     gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1574     double segLen = -1.;
1575     // look for two neighbor not in-FACE nodes of face
1576     for ( int i = 0; i < 2; ++i )
1577     {
1578       if ( nNext[i]->GetPosition()->GetDim() != 2 &&
1579            nNext[i]->GetID() < nodeOnEdge->GetID() )
1580       {
1581         // look for an in-FACE node
1582         for ( int iN = 0; iN < nbN; ++iN )
1583         {
1584           if ( iN == iOnE || iN == iNext[i] )
1585             continue;
1586           SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1587           gp_XYZ v = pInFace - segEnd;
1588           if ( segLen < 0 )
1589           {
1590             segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1591             segLen = segVec.Modulus();
1592           }
1593           double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1594           faceSize = Min( faceSize, distToSeg );
1595           done = true;
1596         }
1597         segLen = -1;
1598       }
1599     }
1600     return done;
1601   }
1602   //================================================================================
1603   /*!
1604    * \brief Return direction of axis or revolution of a surface
1605    */
1606   //================================================================================
1607
1608   bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1609                           gp_Dir &                 axis )
1610   {
1611     switch ( surface.GetType() ) {
1612     case GeomAbs_Cone:
1613     {
1614       gp_Cone cone = surface.Cone();
1615       axis = cone.Axis().Direction();
1616       break;
1617     }
1618     case GeomAbs_Sphere:
1619     {
1620       gp_Sphere sphere = surface.Sphere();
1621       axis = sphere.Position().Direction();
1622       break;
1623     }
1624     case GeomAbs_SurfaceOfRevolution:
1625     {
1626       axis = surface.AxeOfRevolution().Direction();
1627       break;
1628     }
1629     //case GeomAbs_SurfaceOfExtrusion:
1630     case GeomAbs_OffsetSurface:
1631     {
1632       Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1633       return getRovolutionAxis( base->Surface(), axis );
1634     }
1635     default: return false;
1636     }
1637     return true;
1638   }
1639
1640   //--------------------------------------------------------------------------------
1641   // DEBUG. Dump intermediate node positions into a python script
1642   // HOWTO use: run python commands written in a console to see
1643   //  construction steps of viscous layers
1644 #ifdef __myDEBUG
1645   ofstream* py;
1646   int       theNbPyFunc;
1647   struct PyDump {
1648     PyDump(SMESH_Mesh& m) {
1649       int tag = 3 + m.GetId();
1650       const char* fname = "/tmp/viscous.py";
1651       cout << "execfile('"<<fname<<"')"<<endl;
1652       py = new ofstream(fname);
1653       *py << "import SMESH" << endl
1654           << "from salome.smesh import smeshBuilder" << endl
1655           << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
1656           << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
1657           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
1658       theNbPyFunc = 0;
1659     }
1660     void Finish() {
1661       if (py) {
1662         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1663           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1664         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1665           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1666       }
1667       delete py; py=0;
1668     }
1669     ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1670   };
1671 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1672 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
1673 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1674 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
1675   void _dumpFunction(const string& fun, int ln)
1676   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1677   void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1678   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1679                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1680   void _dumpCmd(const string& txt, int ln)
1681   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
1682   void dumpFunctionEnd()
1683   { if (py) *py<< "  return"<< endl; }
1684   void dumpChangeNodes( const SMDS_MeshElement* f )
1685   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
1686       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1687       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1688 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1689
1690 #else
1691
1692   struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} };
1693 #define dumpFunction(f) f
1694 #define dumpMove(n)
1695 #define dumpMoveComm(n,txt)
1696 #define dumpCmd(txt)
1697 #define dumpFunctionEnd()
1698 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1699 #define debugMsg( txt ) {}
1700
1701 #endif
1702 }
1703
1704 using namespace VISCOUS_3D;
1705
1706 //================================================================================
1707 /*!
1708  * \brief Constructor of _ViscousBuilder
1709  */
1710 //================================================================================
1711
1712 _ViscousBuilder::_ViscousBuilder()
1713 {
1714   _error = SMESH_ComputeError::New(COMPERR_OK);
1715   _tmpFaceID = 0;
1716 }
1717
1718 //================================================================================
1719 /*!
1720  * \brief Stores error description and returns false
1721  */
1722 //================================================================================
1723
1724 bool _ViscousBuilder::error(const string& text, int solidId )
1725 {
1726   const string prefix = string("Viscous layers builder: ");
1727   _error->myName    = COMPERR_ALGO_FAILED;
1728   _error->myComment = prefix + text;
1729   if ( _mesh )
1730   {
1731     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1732     if ( !sm && !_sdVec.empty() )
1733       sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1734     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1735     {
1736       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1737       if ( smError && smError->myAlgo )
1738         _error->myAlgo = smError->myAlgo;
1739       smError = _error;
1740       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1741     }
1742     // set KO to all solids
1743     for ( size_t i = 0; i < _sdVec.size(); ++i )
1744     {
1745       if ( _sdVec[i]._index == solidId )
1746         continue;
1747       sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1748       if ( !sm->IsEmpty() )
1749         continue;
1750       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1751       if ( !smError || smError->IsOK() )
1752       {
1753         smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1754         sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1755       }
1756     }
1757   }
1758   makeGroupOfLE(); // debug
1759
1760   return false;
1761 }
1762
1763 //================================================================================
1764 /*!
1765  * \brief At study restoration, restore event listeners used to clear an inferior
1766  *  dim sub-mesh modified by viscous layers
1767  */
1768 //================================================================================
1769
1770 void _ViscousBuilder::RestoreListeners()
1771 {
1772   // TODO
1773 }
1774
1775 //================================================================================
1776 /*!
1777  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1778  */
1779 //================================================================================
1780
1781 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1782 {
1783   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1784   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1785   for ( ; fExp.More(); fExp.Next() )
1786   {
1787     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1788     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1789
1790     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1791       continue;
1792     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1793       continue;
1794
1795     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1796       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1797
1798     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1799     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1800     while( prxIt->more() )
1801     {
1802       const SMDS_MeshElement* fSrc = srcIt->next();
1803       const SMDS_MeshElement* fPrx = prxIt->next();
1804       if ( fSrc->NbNodes() != fPrx->NbNodes())
1805         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1806       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1807         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1808     }
1809   }
1810   pm->_n2nMapComputed = true;
1811   return true;
1812 }
1813
1814 //================================================================================
1815 /*!
1816  * \brief Does its job
1817  */
1818 //================================================================================
1819
1820 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
1821                                                const TopoDS_Shape& theShape)
1822 {
1823   // TODO: set priority of solids during Gen::Compute()
1824
1825   _mesh = & theMesh;
1826
1827   // check if proxy mesh already computed
1828   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1829   if ( !exp.More() )
1830     return error("No SOLID's in theShape"), _error;
1831
1832   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1833     return SMESH_ComputeErrorPtr(); // everything already computed
1834
1835   PyDump debugDump( theMesh );
1836
1837   // TODO: ignore already computed SOLIDs 
1838   if ( !findSolidsWithLayers())
1839     return _error;
1840
1841   if ( !findFacesWithLayers() )
1842     return _error;
1843
1844   for ( size_t i = 0; i < _sdVec.size(); ++i )
1845   {
1846     if ( ! makeLayer(_sdVec[i]) )
1847       return _error;
1848
1849     if ( _sdVec[i]._n2eMap.size() == 0 )
1850       continue;
1851     
1852     if ( ! inflate(_sdVec[i]) )
1853       return _error;
1854
1855     if ( ! refine(_sdVec[i]) )
1856       return _error;
1857   }
1858   if ( !shrink() )
1859     return _error;
1860
1861   addBoundaryElements();
1862
1863   makeGroupOfLE(); // debug
1864   debugDump.Finish();
1865
1866   return _error;
1867 }
1868
1869 //================================================================================
1870 /*!
1871  * \brief Check validity of hypotheses
1872  */
1873 //================================================================================
1874
1875 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh&         mesh,
1876                                                         const TopoDS_Shape& shape )
1877 {
1878   _mesh = & mesh;
1879
1880   if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1881     return SMESH_ComputeErrorPtr(); // everything already computed
1882
1883
1884   findSolidsWithLayers();
1885   bool ok = findFacesWithLayers( true );
1886
1887   // remove _MeshOfSolid's of _SolidData's
1888   for ( size_t i = 0; i < _sdVec.size(); ++i )
1889     _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1890
1891   if ( !ok )
1892     return _error;
1893
1894   return SMESH_ComputeErrorPtr();
1895 }
1896
1897 //================================================================================
1898 /*!
1899  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1900  */
1901 //================================================================================
1902
1903 bool _ViscousBuilder::findSolidsWithLayers()
1904 {
1905   // get all solids
1906   TopTools_IndexedMapOfShape allSolids;
1907   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1908   _sdVec.reserve( allSolids.Extent());
1909
1910   SMESH_Gen* gen = _mesh->GetGen();
1911   SMESH_HypoFilter filter;
1912   for ( int i = 1; i <= allSolids.Extent(); ++i )
1913   {
1914     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1915     SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1916     if ( !algo ) continue;
1917     // TODO: check if algo is hidden
1918     const list <const SMESHDS_Hypothesis *> & allHyps =
1919       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1920     _SolidData* soData = 0;
1921     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1922     const StdMeshers_ViscousLayers* viscHyp = 0;
1923     for ( ; hyp != allHyps.end(); ++hyp )
1924       if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
1925       {
1926         TopoDS_Shape hypShape;
1927         filter.Init( filter.Is( viscHyp ));
1928         _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1929
1930         if ( !soData )
1931         {
1932           _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1933                                                                     allSolids(i),
1934                                                                     /*toCreate=*/true);
1935           _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1936           soData = & _sdVec.back();
1937           soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1938           soData->_helper = new SMESH_MesherHelper( *_mesh );
1939           soData->_helper->SetSubShape( allSolids(i) );
1940         }
1941         soData->_hyps.push_back( viscHyp );
1942         soData->_hypShapes.push_back( hypShape );
1943       }
1944   }
1945   if ( _sdVec.empty() )
1946     return error
1947       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1948
1949   return true;
1950 }
1951
1952 //================================================================================
1953 /*!
1954  * \brief 
1955  */
1956 //================================================================================
1957
1958 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
1959 {
1960   SMESH_MesherHelper helper( *_mesh );
1961   TopExp_Explorer exp;
1962   TopTools_IndexedMapOfShape solids;
1963
1964   // collect all faces-to-ignore defined by hyp
1965   for ( size_t i = 0; i < _sdVec.size(); ++i )
1966   {
1967     solids.Add( _sdVec[i]._solid );
1968
1969     // get faces-to-ignore defined by each hyp
1970     typedef const StdMeshers_ViscousLayers* THyp;
1971     typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
1972     list< TFacesOfHyp > ignoreFacesOfHyps;
1973     list< THyp >::iterator              hyp = _sdVec[i]._hyps.begin();
1974     list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
1975     for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
1976     {
1977       ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
1978       getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
1979     }
1980
1981     // fill _SolidData::_face2hyp and check compatibility of hypotheses
1982     const int nbHyps = _sdVec[i]._hyps.size();
1983     if ( nbHyps > 1 )
1984     {
1985       // check if two hypotheses define different parameters for the same FACE
1986       list< TFacesOfHyp >::iterator igFacesOfHyp;
1987       for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
1988       {
1989         const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
1990         THyp hyp = 0;
1991         igFacesOfHyp = ignoreFacesOfHyps.begin();
1992         for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
1993           if ( ! igFacesOfHyp->first.count( faceID ))
1994           {
1995             if ( hyp )
1996               return error(SMESH_Comment("Several hypotheses define "
1997                                          "Viscous Layers on the face #") << faceID );
1998             hyp = igFacesOfHyp->second;
1999           }
2000         if ( hyp )
2001           _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2002         else
2003           _sdVec[i]._ignoreFaceIds.insert( faceID );
2004       }
2005
2006       // check if two hypotheses define different number of viscous layers for
2007       // adjacent faces of a solid
2008       set< int > nbLayersSet;
2009       igFacesOfHyp = ignoreFacesOfHyps.begin();
2010       for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2011       {
2012         nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2013       }
2014       if ( nbLayersSet.size() > 1 )
2015       {
2016         for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2017         {
2018           PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2019           THyp hyp1 = 0, hyp2 = 0;
2020           while( const TopoDS_Shape* face = fIt->next() )
2021           {
2022             const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2023             map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2024             if ( f2h != _sdVec[i]._face2hyp.end() )
2025             {
2026               ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2027             }
2028           }
2029           if ( hyp1 && hyp2 &&
2030                hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2031           {
2032             return error("Two hypotheses define different number of "
2033                          "viscous layers on adjacent faces");
2034           }
2035         }
2036       }
2037     } // if ( nbHyps > 1 )
2038     else
2039     {
2040       _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2041     }
2042   } // loop on _sdVec
2043
2044   if ( onlyWith ) // is called to check hypotheses compatibility only
2045     return true;
2046
2047   // fill _SolidData::_reversedFaceIds
2048   for ( size_t i = 0; i < _sdVec.size(); ++i )
2049   {
2050     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2051     for ( ; exp.More(); exp.Next() )
2052     {
2053       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2054       const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2055       if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2056           helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2057           helper.IsReversedSubMesh( face ))
2058       {
2059         _sdVec[i]._reversedFaceIds.insert( faceID );
2060       }
2061     }
2062   }
2063
2064   // Find faces to shrink mesh on (solution 2 in issue 0020832);
2065   TopTools_IndexedMapOfShape shapes;
2066   for ( size_t i = 0; i < _sdVec.size(); ++i )
2067   {
2068     shapes.Clear();
2069     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2070     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2071     {
2072       const TopoDS_Shape& edge = shapes(iE);
2073       // find 2 faces sharing an edge
2074       TopoDS_Shape FF[2];
2075       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
2076       while ( fIt->more())
2077       {
2078         const TopoDS_Shape* f = fIt->next();
2079         if ( helper.IsSubShape( *f, _sdVec[i]._solid))
2080           FF[ int( !FF[0].IsNull()) ] = *f;
2081       }
2082       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2083       // check presence of layers on them
2084       int ignore[2];
2085       for ( int j = 0; j < 2; ++j )
2086         ignore[j] = _sdVec[i]._ignoreFaceIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
2087       if ( ignore[0] == ignore[1] )
2088         continue; // nothing interesting
2089       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
2090       // check presence of layers on fWOL within an adjacent SOLID
2091       bool collision = false;
2092       PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
2093       while ( const TopoDS_Shape* solid = sIt->next() )
2094         if ( !solid->IsSame( _sdVec[i]._solid ))
2095         {
2096           int iSolid = solids.FindIndex( *solid );
2097           int  iFace = getMeshDS()->ShapeToIndex( fWOL );
2098           if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
2099           {
2100             //_sdVec[i]._noShrinkShapes.insert( iFace );
2101             //fWOL.Nullify();
2102             collision = true;
2103           }
2104         }
2105       // add edge to maps
2106       if ( !fWOL.IsNull())
2107       {
2108         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2109         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2110         if ( collision )
2111         {
2112           // _shrinkShape2Shape will be used to temporary inflate _LayerEdge's based
2113           // on the edge but shrink won't be performed
2114           _sdVec[i]._noShrinkShapes.insert( edgeInd );
2115         }
2116       }
2117     }
2118   }
2119   // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
2120   // the algo of the SOLID sharing the FACE does not support it
2121   set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
2122   for ( size_t i = 0; i < _sdVec.size(); ++i )
2123   {
2124     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2125     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2126     {
2127       const TopoDS_Shape& fWOL = e2f->second;
2128       const TGeomID     edgeID = e2f->first;
2129       bool notShrinkFace = false;
2130       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2131       while ( soIt->more() )
2132       {
2133         const TopoDS_Shape* solid = soIt->next();
2134         if ( _sdVec[i]._solid.IsSame( *solid )) continue;
2135         SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
2136         if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
2137         notShrinkFace = true;
2138         size_t iSolid = 0;
2139         for ( ; iSolid < _sdVec.size(); ++iSolid )
2140         {
2141           if ( _sdVec[iSolid]._solid.IsSame( *solid ) ) {
2142             if ( _sdVec[iSolid]._shrinkShape2Shape.count( edgeID ))
2143               notShrinkFace = false;
2144             break;
2145           }
2146         }
2147         if ( notShrinkFace )
2148         {
2149           _sdVec[i]._noShrinkShapes.insert( edgeID );
2150
2151           // add VERTEXes of the edge in _noShrinkShapes
2152           TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
2153           for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2154             _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( vIt.Value() ));
2155
2156           // check if there is a collision with to-shrink-from EDGEs in iSolid
2157           if ( iSolid == _sdVec.size() )
2158             continue; // no VL in the solid
2159           shapes.Clear();
2160           TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2161           for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2162           {
2163             const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2164             const TGeomID    eID = getMeshDS()->ShapeToIndex( E );
2165             if ( eID == edgeID ||
2166                  !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2167                  _sdVec[i]._noShrinkShapes.count( eID ))
2168               continue;
2169             for ( int is1st = 0; is1st < 2; ++is1st )
2170             {
2171               TopoDS_Vertex V = helper.IthVertex( is1st, E );
2172               if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2173               {
2174                 // _sdVec[i]._noShrinkShapes.insert( eID );
2175                 // V = helper.IthVertex( !is1st, E );
2176                 // _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( V ));
2177                 //iE = 0; // re-start the loop on EDGEs of fWOL
2178                 return error("No way to make a conformal mesh with "
2179                              "the given set of faces with layers", _sdVec[i]._index);
2180               }
2181             }
2182           }
2183         }
2184
2185       } // while ( soIt->more() )
2186     } // loop on _sdVec[i]._shrinkShape2Shape
2187   } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2188
2189   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2190
2191   for ( size_t i = 0; i < _sdVec.size(); ++i )
2192   {
2193     shapes.Clear();
2194     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2195     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2196     {
2197       const TopoDS_Shape& vertex = shapes(iV);
2198       // find faces WOL sharing the vertex
2199       vector< TopoDS_Shape > facesWOL;
2200       size_t totalNbFaces = 0;
2201       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
2202       while ( fIt->more())
2203       {
2204         const TopoDS_Shape* f = fIt->next();
2205         if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
2206         {
2207           totalNbFaces++;
2208           const int fID = getMeshDS()->ShapeToIndex( *f );
2209           if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&&
2210                !_sdVec[i]._noShrinkShapes.count( fID )*/)
2211             facesWOL.push_back( *f );
2212         }
2213       }
2214       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2215         continue; // no layers at this vertex or no WOL
2216       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2217       switch ( facesWOL.size() )
2218       {
2219       case 1:
2220       {
2221         helper.SetSubShape( facesWOL[0] );
2222         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2223         {
2224           TopoDS_Shape seamEdge;
2225           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2226           while ( eIt->more() && seamEdge.IsNull() )
2227           {
2228             const TopoDS_Shape* e = eIt->next();
2229             if ( helper.IsRealSeam( *e ) )
2230               seamEdge = *e;
2231           }
2232           if ( !seamEdge.IsNull() )
2233           {
2234             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2235             break;
2236           }
2237         }
2238         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2239         break;
2240       }
2241       case 2:
2242       {
2243         // find an edge shared by 2 faces
2244         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2245         while ( eIt->more())
2246         {
2247           const TopoDS_Shape* e = eIt->next();
2248           if ( helper.IsSubShape( *e, facesWOL[0]) &&
2249                helper.IsSubShape( *e, facesWOL[1]))
2250           {
2251             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2252           }
2253         }
2254         break;
2255       }
2256       default:
2257         return error("Not yet supported case", _sdVec[i]._index);
2258       }
2259     }
2260   }
2261
2262   // add FACEs of other SOLIDs to _ignoreFaceIds
2263   for ( size_t i = 0; i < _sdVec.size(); ++i )
2264   {
2265     shapes.Clear();
2266     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2267
2268     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2269     {
2270       if ( !shapes.Contains( exp.Current() ))
2271         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2272     }
2273   }
2274
2275   return true;
2276 }
2277
2278 //================================================================================
2279 /*!
2280  * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2281  */
2282 //================================================================================
2283
2284 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape&             solid,
2285                                      const StdMeshers_ViscousLayers* hyp,
2286                                      const TopoDS_Shape&             hypShape,
2287                                      set<TGeomID>&                   ignoreFaceIds)
2288 {
2289   TopExp_Explorer exp;
2290
2291   vector<TGeomID> ids = hyp->GetBndShapes();
2292   if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2293   {
2294     for ( size_t ii = 0; ii < ids.size(); ++ii )
2295     {
2296       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2297       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2298         ignoreFaceIds.insert( ids[ii] );
2299     }
2300   }
2301   else // FACEs with layers are given
2302   {
2303     exp.Init( solid, TopAbs_FACE );
2304     for ( ; exp.More(); exp.Next() )
2305     {
2306       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2307       if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2308         ignoreFaceIds.insert( faceInd );
2309     }
2310   }
2311
2312   // ignore internal FACEs if inlets and outlets are specified
2313   if ( hyp->IsToIgnoreShapes() )
2314   {
2315     TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2316     TopExp::MapShapesAndAncestors( hypShape,
2317                                    TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2318
2319     for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2320     {
2321       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2322       if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2323         continue;
2324
2325       int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2326       if ( nbSolids > 1 )
2327         ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2328     }
2329   }
2330 }
2331
2332 //================================================================================
2333 /*!
2334  * \brief Create the inner surface of the viscous layer and prepare data for infation
2335  */
2336 //================================================================================
2337
2338 bool _ViscousBuilder::makeLayer(_SolidData& data)
2339 {
2340   // get all sub-shapes to make layers on
2341   set<TGeomID> subIds, faceIds;
2342   subIds = data._noShrinkShapes;
2343   TopExp_Explorer exp( data._solid, TopAbs_FACE );
2344   for ( ; exp.More(); exp.Next() )
2345   {
2346     SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2347     if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2348       faceIds.insert( fSubM->GetId() );
2349   }
2350
2351   // make a map to find new nodes on sub-shapes shared with other SOLID
2352   map< TGeomID, TNode2Edge* >::iterator s2ne;
2353   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2354   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2355   {
2356     TGeomID shapeInd = s2s->first;
2357     for ( size_t i = 0; i < _sdVec.size(); ++i )
2358     {
2359       if ( _sdVec[i]._index == data._index ) continue;
2360       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2361       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2362            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2363       {
2364         data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2365         break;
2366       }
2367     }
2368   }
2369
2370   // Create temporary faces and _LayerEdge's
2371
2372   dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2373
2374   data._stepSize = Precision::Infinite();
2375   data._stepSizeNodes[0] = 0;
2376
2377   SMESH_MesherHelper helper( *_mesh );
2378   helper.SetSubShape( data._solid );
2379   helper.SetElementsOnShape( true );
2380
2381   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2382   TNode2Edge::iterator n2e2;
2383
2384   // collect _LayerEdge's of shapes they are based on
2385   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2386   const int nbShapes = getMeshDS()->MaxShapeIndex();
2387   edgesByGeom.resize( nbShapes+1 );
2388
2389   // set data of _EdgesOnShape's
2390   if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2391   {
2392     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2393     while ( smIt->more() )
2394     {
2395       sm = smIt->next();
2396       if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2397            !faceIds.count( sm->GetId() ))
2398         continue;
2399       setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2400     }
2401   }
2402   // make _LayerEdge's
2403   for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2404   {
2405     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2406     SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2407     SMESH_ProxyMesh::SubMesh* proxySub =
2408       data._proxyMesh->getFaceSubM( F, /*create=*/true);
2409
2410     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2411     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2412
2413     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2414     while ( eIt->more() )
2415     {
2416       const SMDS_MeshElement* face = eIt->next();
2417       double          faceMaxCosin = -1;
2418       _LayerEdge*     maxCosinEdge = 0;
2419       int             nbDegenNodes = 0;
2420
2421       newNodes.resize( face->NbCornerNodes() );
2422       for ( size_t i = 0 ; i < newNodes.size(); ++i )
2423       {
2424         const SMDS_MeshNode* n = face->GetNode( i );
2425         const int      shapeID = n->getshapeId();
2426         const bool onDegenShap = helper.IsDegenShape( shapeID );
2427         const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2428         if ( onDegenShap )
2429         {
2430           if ( onDegenEdge )
2431           {
2432             // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2433             const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2434             TopoDS_Vertex       V = helper.IthVertex( 0, TopoDS::Edge( E ));
2435             if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2436               n = vN;
2437               nbDegenNodes++;
2438             }
2439           }
2440           else
2441           {
2442             nbDegenNodes++;
2443           }
2444         }
2445         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2446         if ( !(*n2e).second )
2447         {
2448           // add a _LayerEdge
2449           _LayerEdge* edge = new _LayerEdge();
2450           edge->_nodes.push_back( n );
2451           n2e->second = edge;
2452           edgesByGeom[ shapeID ]._edges.push_back( edge );
2453           const bool noShrink = data._noShrinkShapes.count( shapeID );
2454
2455           SMESH_TNodeXYZ xyz( n );
2456
2457           // set edge data or find already refined _LayerEdge and get data from it
2458           if (( !noShrink                                                     ) &&
2459               ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE        ) &&
2460               (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2461               (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end()     ))
2462           {
2463             _LayerEdge* foundEdge = (*n2e2).second;
2464             gp_XYZ        lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2465             foundEdge->_pos.push_back( lastPos );
2466             // location of the last node is modified and we restore it by foundEdge->_pos.back()
2467             const_cast< SMDS_MeshNode* >
2468               ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2469           }
2470           else
2471           {
2472             if ( !noShrink )
2473             {
2474               edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2475             }
2476             if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2477               return false;
2478
2479             if ( edge->_nodes.size() < 2 )
2480               edge->Block( data );
2481               //data._noShrinkShapes.insert( shapeID );
2482           }
2483           dumpMove(edge->_nodes.back());
2484
2485           if ( edge->_cosin > faceMaxCosin )
2486           {
2487             faceMaxCosin = edge->_cosin;
2488             maxCosinEdge = edge;
2489           }
2490         }
2491         newNodes[ i ] = n2e->second->_nodes.back();
2492
2493         if ( onDegenEdge )
2494           data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2495       }
2496       if ( newNodes.size() - nbDegenNodes < 2 )
2497         continue;
2498
2499       // create a temporary face
2500       const SMDS_MeshElement* newFace =
2501         new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId(), face->getIdInShape() );
2502       proxySub->AddElement( newFace );
2503
2504       // compute inflation step size by min size of element on a convex surface
2505       if ( faceMaxCosin > theMinSmoothCosin )
2506         limitStepSize( data, face, maxCosinEdge );
2507
2508     } // loop on 2D elements on a FACE
2509   } // loop on FACEs of a SOLID to create _LayerEdge's
2510
2511
2512   // Set _LayerEdge::_neibors
2513   TNode2Edge::iterator n2e;
2514   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2515   {
2516     _EdgesOnShape& eos = data._edgesOnShape[iS];
2517     for ( size_t i = 0; i < eos._edges.size(); ++i )
2518     {
2519       _LayerEdge* edge = eos._edges[i];
2520       TIDSortedNodeSet nearNodes;
2521       SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2522       while ( fIt->more() )
2523       {
2524         const SMDS_MeshElement* f = fIt->next();
2525         if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2526           nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2527       }
2528       nearNodes.erase( edge->_nodes[0] );
2529       edge->_neibors.reserve( nearNodes.size() );
2530       TIDSortedNodeSet::iterator node = nearNodes.begin();
2531       for ( ; node != nearNodes.end(); ++node )
2532         if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2533           edge->_neibors.push_back( n2e->second );
2534     }
2535   }
2536
2537   data._epsilon = 1e-7;
2538   if ( data._stepSize < 1. )
2539     data._epsilon *= data._stepSize;
2540
2541   if ( !findShapesToSmooth( data ))
2542     return false;
2543
2544   // limit data._stepSize depending on surface curvature and fill data._convexFaces
2545   limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2546
2547   // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2548   const SMDS_MeshNode* nn[2];
2549   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2550   {
2551     _EdgesOnShape& eos = data._edgesOnShape[iS];
2552     for ( size_t i = 0; i < eos._edges.size(); ++i )
2553     {
2554       _LayerEdge* edge = eos._edges[i];
2555       if ( edge->IsOnEdge() )
2556       {
2557         // get neighbor nodes
2558         bool hasData = ( edge->_2neibors->_edges[0] );
2559         if ( hasData ) // _LayerEdge is a copy of another one
2560         {
2561           nn[0] = edge->_2neibors->srcNode(0);
2562           nn[1] = edge->_2neibors->srcNode(1);
2563         }
2564         else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2565         {
2566           return false;
2567         }
2568         // set neighbor _LayerEdge's
2569         for ( int j = 0; j < 2; ++j )
2570         {
2571           if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2572             return error("_LayerEdge not found by src node", data._index);
2573           edge->_2neibors->_edges[j] = n2e->second;
2574         }
2575         if ( !hasData )
2576           edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2577       }
2578
2579       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2580       {
2581         _Simplex& s = edge->_simplices[j];
2582         s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2583         s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2584       }
2585
2586       // For an _LayerEdge on a degenerated EDGE, copy some data from
2587       // a corresponding _LayerEdge on a VERTEX
2588       // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2589       if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2590       {
2591         // Generally we should not get here
2592         if ( eos.ShapeType() != TopAbs_EDGE )
2593           continue;
2594         TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2595         const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2596         if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2597           continue;
2598         const _LayerEdge* vEdge = n2e->second;
2599         edge->_normal    = vEdge->_normal;
2600         edge->_lenFactor = vEdge->_lenFactor;
2601         edge->_cosin     = vEdge->_cosin;
2602       }
2603
2604     } // loop on data._edgesOnShape._edges
2605   } // loop on data._edgesOnShape
2606
2607   // fix _LayerEdge::_2neibors on EDGEs to smooth
2608   // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2609   // for ( ; e2c != data._edge2curve.end(); ++e2c )
2610   //   if ( !e2c->second.IsNull() )
2611   //   {
2612   //     if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2613   //       data.Sort2NeiborsOnEdge( eos->_edges );
2614   //   }
2615
2616   dumpFunctionEnd();
2617   return true;
2618 }
2619
2620 //================================================================================
2621 /*!
2622  * \brief Compute inflation step size by min size of element on a convex surface
2623  */
2624 //================================================================================
2625
2626 void _ViscousBuilder::limitStepSize( _SolidData&             data,
2627                                      const SMDS_MeshElement* face,
2628                                      const _LayerEdge*       maxCosinEdge )
2629 {
2630   int iN = 0;
2631   double minSize = 10 * data._stepSize;
2632   const int nbNodes = face->NbCornerNodes();
2633   for ( int i = 0; i < nbNodes; ++i )
2634   {
2635     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2636     const SMDS_MeshNode*  curN = face->GetNode( i );
2637     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2638          curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2639     {
2640       double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2641       if ( dist < minSize )
2642         minSize = dist, iN = i;
2643     }
2644   }
2645   double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2646   if ( newStep < data._stepSize )
2647   {
2648     data._stepSize = newStep;
2649     data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2650     data._stepSizeNodes[0] = face->GetNode( iN );
2651     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2652   }
2653 }
2654
2655 //================================================================================
2656 /*!
2657  * \brief Compute inflation step size by min size of element on a convex surface
2658  */
2659 //================================================================================
2660
2661 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2662 {
2663   if ( minSize < data._stepSize )
2664   {
2665     data._stepSize = minSize;
2666     if ( data._stepSizeNodes[0] )
2667     {
2668       double dist =
2669         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2670       data._stepSizeCoeff = data._stepSize / dist;
2671     }
2672   }
2673 }
2674
2675 //================================================================================
2676 /*!
2677  * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2678  */
2679 //================================================================================
2680
2681 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2682 {
2683   const int nbTestPnt = 5; // on a FACE sub-shape
2684
2685   BRepLProp_SLProps surfProp( 2, 1e-6 );
2686   SMESH_MesherHelper helper( *_mesh );
2687
2688   data._convexFaces.clear();
2689
2690   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2691   {
2692     _EdgesOnShape& eof = data._edgesOnShape[iS];
2693     if ( eof.ShapeType() != TopAbs_FACE ||
2694          data._ignoreFaceIds.count( eof._shapeID ))
2695       continue;
2696
2697     TopoDS_Face        F = TopoDS::Face( eof._shape );
2698     SMESH_subMesh *   sm = eof._subMesh;
2699     const TGeomID faceID = eof._shapeID;
2700
2701     BRepAdaptor_Surface surface( F, false );
2702     surfProp.SetSurface( surface );
2703
2704     bool isTooCurved = false;
2705
2706     _ConvexFace cnvFace;
2707     const double        oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2708     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
2709     while ( smIt->more() )
2710     {
2711       sm = smIt->next();
2712       const TGeomID subID = sm->GetId();
2713       // find _LayerEdge's of a sub-shape
2714       _EdgesOnShape* eos;
2715       if (( eos = data.GetShapeEdges( subID )))
2716         cnvFace._subIdToEOS.insert( make_pair( subID, eos ));
2717       else
2718         continue;
2719       // check concavity and curvature and limit data._stepSize
2720       const double minCurvature =
2721         1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2722       size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
2723       for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
2724       {
2725         gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
2726         surfProp.SetParameters( uv.X(), uv.Y() );
2727         if ( !surfProp.IsCurvatureDefined() )
2728           continue;
2729         if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2730         {
2731           limitStepSize( data, 0.9 / surfProp.MaxCurvature() * oriFactor );
2732           isTooCurved = true;
2733         }
2734         if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2735         {
2736           limitStepSize( data, 0.9 / surfProp.MinCurvature() * oriFactor );
2737           isTooCurved = true;
2738         }
2739       }
2740     } // loop on sub-shapes of the FACE
2741
2742     if ( !isTooCurved ) continue;
2743
2744     _ConvexFace & convFace =
2745       data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2746
2747     convFace._face = F;
2748     convFace._normalsFixed = false;
2749
2750     // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2751     // prism distortion.
2752     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2753     if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2754     {
2755       // there are _LayerEdge's on the FACE it-self;
2756       // select _LayerEdge's near EDGEs
2757       _EdgesOnShape& eos = * id2eos->second;
2758       for ( size_t i = 0; i < eos._edges.size(); ++i )
2759       {
2760         _LayerEdge* ledge = eos._edges[ i ];
2761         for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2762           if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2763           {
2764             convFace._simplexTestEdges.push_back( ledge );
2765             break;
2766           }
2767       }
2768     }
2769     else
2770     {
2771       // where there are no _LayerEdge's on a _ConvexFace,
2772       // as e.g. on a fillet surface with no internal nodes - issue 22580,
2773       // so that collision of viscous internal faces is not detected by check of
2774       // intersection of _LayerEdge's with the viscous internal faces.
2775
2776       set< const SMDS_MeshNode* > usedNodes;
2777
2778       // look for _LayerEdge's with null _sWOL
2779       id2eos = convFace._subIdToEOS.begin();
2780       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2781       {
2782         _EdgesOnShape& eos = * id2eos->second;
2783         if ( !eos._sWOL.IsNull() )
2784           continue;
2785         for ( size_t i = 0; i < eos._edges.size(); ++i )
2786         {
2787           _LayerEdge* ledge = eos._edges[ i ];
2788           const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2789           if ( !usedNodes.insert( srcNode ).second ) continue;
2790
2791           for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2792           {
2793             usedNodes.insert( ledge->_simplices[i]._nPrev );
2794             usedNodes.insert( ledge->_simplices[i]._nNext );
2795           }
2796           convFace._simplexTestEdges.push_back( ledge );
2797         }
2798       }
2799     }
2800   } // loop on FACEs of data._solid
2801 }
2802
2803 //================================================================================
2804 /*!
2805  * \brief Detect shapes (and _LayerEdge's on them) to smooth
2806  */
2807 //================================================================================
2808
2809 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2810 {
2811   // define allowed thickness
2812   computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2813
2814   data._maxThickness = 0;
2815   data._minThickness = 1e100;
2816   list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
2817   for ( ; hyp != data._hyps.end(); ++hyp )
2818   {
2819     data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
2820     data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
2821   }
2822   //const double tgtThick = /*Min( 0.5 * data._geomSize, */data._maxThickness;
2823
2824   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2825   // boundry inclined to the shape at a sharp angle
2826
2827   //list< TGeomID > shapesToSmooth;
2828   TopTools_MapOfShape edgesOfSmooFaces;
2829
2830   SMESH_MesherHelper helper( *_mesh );
2831   bool ok = true;
2832
2833   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2834   data._nbShapesToSmooth = 0;
2835
2836   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2837   {
2838     _EdgesOnShape& eos = edgesByGeom[iS];
2839     eos._toSmooth = false;
2840     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2841       continue;
2842
2843     double tgtThick = eos._hyp.GetTotalThickness();
2844     TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE );
2845     for ( ; eExp.More() && !eos._toSmooth; eExp.Next() )
2846     {
2847       TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
2848       vector<_LayerEdge*>& eE = edgesByGeom[ iE ]._edges;
2849       if ( eE.empty() ) continue;
2850
2851       double faceSize;
2852       for ( size_t i = 0; i < eE.size() && !eos._toSmooth; ++i )
2853         if ( eE[i]->_cosin > theMinSmoothCosin )
2854         {
2855           SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2856           while ( fIt->more() && !eos._toSmooth )
2857           {
2858             const SMDS_MeshElement* face = fIt->next();
2859             if ( face->getshapeId() == eos._shapeID &&
2860                  getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
2861             {
2862               eos._toSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
2863             }
2864           }
2865         }
2866     }
2867     if ( eos._toSmooth )
2868     {
2869       for ( eExp.ReInit(); eExp.More(); eExp.Next() )
2870         edgesOfSmooFaces.Add( eExp.Current() );
2871
2872       data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
2873     }
2874     data._nbShapesToSmooth += eos._toSmooth;
2875
2876   }  // check FACEs
2877
2878   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
2879   {
2880     _EdgesOnShape& eos = edgesByGeom[iS];
2881     eos._edgeSmoother = NULL;
2882     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
2883     if ( !eos._hyp.ToSmooth() ) continue;
2884
2885     const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
2886     if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
2887       continue;
2888
2889     double tgtThick = eos._hyp.GetTotalThickness();
2890     for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
2891     {
2892       TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
2893       vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
2894       if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
2895       gp_Vec  eDir    = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
2896       double angle    = eDir.Angle( eV[0]->_normal );
2897       double cosin    = Cos( angle );
2898       double cosinAbs = Abs( cosin );
2899       if ( cosinAbs > theMinSmoothCosin )
2900       {
2901         // always smooth analytic EDGEs
2902         Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
2903         eos._toSmooth = ! curve.IsNull();
2904
2905         // compare tgtThick with the length of an end segment
2906         SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
2907         while ( eIt->more() && !eos._toSmooth )
2908         {
2909           const SMDS_MeshElement* endSeg = eIt->next();
2910           if ( endSeg->getshapeId() == (int) iS )
2911           {
2912             double segLen =
2913               SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
2914             eos._toSmooth = needSmoothing( cosinAbs, tgtThick, segLen );
2915           }
2916         }
2917         if ( eos._toSmooth )
2918         {
2919           eos._edgeSmoother = new _Smoother1D( curve, eos );
2920
2921           for ( size_t i = 0; i < eos._edges.size(); ++i )
2922             eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
2923         }
2924       }
2925     }
2926     data._nbShapesToSmooth += eos._toSmooth;
2927
2928   } // check EDGEs
2929
2930   // Reset _cosin if no smooth is allowed by the user
2931   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
2932   {
2933     _EdgesOnShape& eos = edgesByGeom[iS];
2934     if ( eos._edges.empty() ) continue;
2935
2936     if ( !eos._hyp.ToSmooth() )
2937       for ( size_t i = 0; i < eos._edges.size(); ++i )
2938         eos._edges[i]->SetCosin( 0 );
2939   }
2940
2941
2942   // Fill _eosC1 to make that C1 FACEs and EGDEs between them to be smoothed as a whole
2943
2944   TopTools_MapOfShape c1VV;
2945
2946   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2947   {
2948     _EdgesOnShape& eos = edgesByGeom[iS];
2949     if ( eos._edges.empty() ||
2950          eos.ShapeType() != TopAbs_FACE ||
2951          !eos._toSmooth )
2952       continue;
2953
2954     // check EDGEs of a FACE
2955     TopTools_MapOfShape checkedEE, allVV;
2956     list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
2957     while ( !smQueue.empty() )
2958     {
2959       SMESH_subMesh* sm = smQueue.front();
2960       smQueue.pop_front();
2961       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2962       while ( smIt->more() )
2963       {
2964         sm = smIt->next();
2965         if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
2966           allVV.Add( sm->GetSubShape() );
2967         if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
2968              !checkedEE.Add( sm->GetSubShape() ))
2969           continue;
2970
2971         _EdgesOnShape*      eoe = data.GetShapeEdges( sm->GetId() );
2972         vector<_LayerEdge*>& eE = eoe->_edges;
2973         if ( eE.empty() || !eoe->_sWOL.IsNull() )
2974           continue;
2975
2976         bool isC1 = true; // check continuity along an EDGE
2977         for ( size_t i = 0; i < eE.size() && isC1; ++i )
2978           isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
2979         if ( !isC1 )
2980           continue;
2981
2982         // check that mesh faces are C1 as well
2983         {
2984           gp_XYZ norm1, norm2;
2985           const SMDS_MeshNode*   n = eE[ eE.size() / 2 ]->_nodes[0];
2986           SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
2987           if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
2988             continue;
2989           while ( fIt->more() && isC1 )
2990             isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
2991                      Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
2992           if ( !isC1 )
2993             continue;
2994         }
2995
2996         // add the EDGE and an adjacent FACE to _eosC1
2997         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
2998         while ( const TopoDS_Shape* face = fIt->next() )
2999         {
3000           _EdgesOnShape* eof = data.GetShapeEdges( *face );
3001           if ( !eof ) continue; // other solid
3002           if ( !eos.HasC1( eoe ))
3003           {
3004             eos._eosC1.push_back( eoe );
3005             eoe->_toSmooth = false;
3006             data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3007           }
3008           if ( eos._shapeID != eof->_shapeID && !eos.HasC1( eof )) 
3009           {
3010             eos._eosC1.push_back( eof );
3011             eof->_toSmooth = false;
3012             data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3013             smQueue.push_back( eof->_subMesh );
3014           }
3015         }
3016       }
3017     }
3018     if ( eos._eosC1.empty() )
3019       continue;
3020
3021     // check VERTEXes of C1 FACEs
3022     TopTools_MapIteratorOfMapOfShape vIt( allVV );
3023     for ( ; vIt.More(); vIt.Next() )
3024     {
3025       _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3026       if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3027         continue;
3028
3029       bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3030       PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3031       while ( const TopoDS_Shape* face = fIt->next() )
3032       {
3033         _EdgesOnShape* eof = data.GetShapeEdges( *face );
3034         if ( !eof ) continue; // other solid
3035         isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3036         if ( !isC1 )
3037           break;
3038       }
3039       if ( isC1 )
3040       {
3041         eos._eosC1.push_back( eov );
3042         data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3043         c1VV.Add( eov->_shape );
3044       }
3045     }
3046
3047   } // fill _eosC1 of FACEs
3048
3049
3050   // Find C1 EDGEs
3051
3052   vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3053
3054   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3055   {
3056     _EdgesOnShape& eov = edgesByGeom[iS];
3057     if ( eov._edges.empty() ||
3058          eov.ShapeType() != TopAbs_VERTEX ||
3059          c1VV.Contains( eov._shape ))
3060       continue;
3061     const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3062
3063     // get directions of surrounding EDGEs
3064     dirOfEdges.clear();
3065     PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3066     while ( const TopoDS_Shape* e = fIt->next() )
3067     {
3068       _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3069       if ( !eoe ) continue; // other solid
3070       gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3071       if ( !Precision::IsInfinite( eDir.X() ))
3072         dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3073     }
3074
3075     // find EDGEs with C1 directions
3076     for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3077       for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3078         if ( dirOfEdges[i].first && dirOfEdges[j].first )
3079         {
3080           double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3081           bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3082           if ( isC1 )
3083           {
3084             double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3085             double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3086             double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3087             if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3088             if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3089             dirOfEdges[i].first = 0;
3090             dirOfEdges[j].first = 0;
3091           }
3092         }
3093   } // fill _eosC1 of VERTEXes
3094
3095
3096
3097   return ok;
3098 }
3099
3100 //================================================================================
3101 /*!
3102  * \brief initialize data of _EdgesOnShape
3103  */
3104 //================================================================================
3105
3106 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3107                                     SMESH_subMesh* sm,
3108                                     _SolidData&    data )
3109 {
3110   if ( !eos._shape.IsNull() ||
3111        sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3112     return;
3113
3114   SMESH_MesherHelper helper( *_mesh );
3115
3116   eos._subMesh = sm;
3117   eos._shapeID = sm->GetId();
3118   eos._shape   = sm->GetSubShape();
3119   if ( eos.ShapeType() == TopAbs_FACE )
3120     eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3121   eos._toSmooth = false;
3122   eos._data = &data;
3123
3124   // set _SWOL
3125   map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3126     data._shrinkShape2Shape.find( eos._shapeID );
3127   if ( s2s != data._shrinkShape2Shape.end() )
3128     eos._sWOL = s2s->second;
3129
3130   eos._isRegularSWOL = true;
3131   if ( eos.SWOLType() == TopAbs_FACE )
3132   {
3133     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3134     Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3135     eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3136   }
3137
3138   // set _hyp
3139   if ( data._hyps.size() == 1 )
3140   {
3141     eos._hyp = data._hyps.back();
3142   }
3143   else
3144   {
3145     // compute average StdMeshers_ViscousLayers parameters
3146     map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3147     if ( eos.ShapeType() == TopAbs_FACE )
3148     {
3149       if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3150         eos._hyp = f2hyp->second;
3151     }
3152     else
3153     {
3154       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3155       while ( const TopoDS_Shape* face = fIt->next() )
3156       {
3157         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3158         if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3159           eos._hyp.Add( f2hyp->second );
3160       }
3161     }
3162   }
3163
3164   // set _faceNormals
3165   if ( ! eos._hyp.UseSurfaceNormal() )
3166   {
3167     if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3168     {
3169       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3170       eos._faceNormals.resize( smDS->NbElements() );
3171
3172       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3173       for ( int iF = 0; eIt->more(); ++iF )
3174       {
3175         const SMDS_MeshElement* face = eIt->next();
3176         if ( !SMESH_MeshAlgos::FaceNormal( face, eos._faceNormals[iF], /*normalized=*/true ))
3177           eos._faceNormals[iF].SetCoord( 0,0,0 );
3178       }
3179
3180       if ( !helper.IsReversedSubMesh( TopoDS::Face( eos._shape )))
3181         for ( size_t iF = 0; iF < eos._faceNormals.size(); ++iF )
3182           eos._faceNormals[iF].Reverse();
3183     }
3184     else // find EOS of adjacent FACEs
3185     {
3186       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3187       while ( const TopoDS_Shape* face = fIt->next() )
3188       {
3189         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3190         eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3191         if ( eos._faceEOS.back()->_shape.IsNull() )
3192           // avoid using uninitialised _shapeID in GetNormal()
3193           eos._faceEOS.back()->_shapeID = faceID;
3194       }
3195     }
3196   }
3197 }
3198
3199 //================================================================================
3200 /*!
3201  * \brief Returns normal of a face
3202  */
3203 //================================================================================
3204
3205 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3206 {
3207   bool ok = false;
3208   const _EdgesOnShape* eos = 0;
3209
3210   if ( face->getshapeId() == _shapeID )
3211   {
3212     eos = this;
3213   }
3214   else
3215   {
3216     for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3217       if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3218         eos = _faceEOS[ iF ];
3219   }
3220
3221   if (( eos ) &&
3222       ( ok = ( face->getIdInShape() < (int) eos->_faceNormals.size() )))
3223   {
3224     norm = eos->_faceNormals[ face->getIdInShape() ];
3225   }
3226   else if ( !eos )
3227   {
3228     debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3229               << " on _shape #" << _shapeID );
3230   }
3231   return ok;
3232 }
3233
3234
3235 //================================================================================
3236 /*!
3237  * \brief Set data of _LayerEdge needed for smoothing
3238  */
3239 //================================================================================
3240
3241 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
3242                                   _EdgesOnShape&      eos,
3243                                   SMESH_MesherHelper& helper,
3244                                   _SolidData&         data)
3245 {
3246   const SMDS_MeshNode* node = edge._nodes[0]; // source node
3247
3248   edge._len       = 0;
3249   edge._maxLen    = Precision::Infinite();
3250   edge._minAngle  = 0;
3251   edge._2neibors  = 0;
3252   edge._curvature = 0;
3253   edge._flags     = 0;
3254
3255   // --------------------------
3256   // Compute _normal and _cosin
3257   // --------------------------
3258
3259   edge._cosin     = 0;
3260   edge._lenFactor = 1.;
3261   edge._normal.SetCoord(0,0,0);
3262   _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3263
3264   int totalNbFaces = 0;
3265   TopoDS_Face F;
3266   std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3267   gp_Vec geomNorm;
3268   bool normOK = true;
3269
3270   const bool onShrinkShape = !eos._sWOL.IsNull();
3271   const bool useGeometry   = (( eos._hyp.UseSurfaceNormal() ) ||
3272                               ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3273
3274   // get geom FACEs the node lies on
3275   //if ( useGeometry )
3276   {
3277     set<TGeomID> faceIds;
3278     if  ( eos.ShapeType() == TopAbs_FACE )
3279     {
3280       faceIds.insert( eos._shapeID );
3281     }
3282     else
3283     {
3284       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3285       while ( fIt->more() )
3286         faceIds.insert( fIt->next()->getshapeId() );
3287     }
3288     set<TGeomID>::iterator id = faceIds.begin();
3289     for ( ; id != faceIds.end(); ++id )
3290     {
3291       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3292       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3293         continue;
3294       F = TopoDS::Face( s );
3295       face2Norm[ totalNbFaces ].first = F;
3296       totalNbFaces++;
3297     }
3298   }
3299
3300   // find _normal
3301   if ( useGeometry )
3302   {
3303     if ( onShrinkShape ) // one of faces the node is on has no layers
3304     {
3305       if ( eos.SWOLType() == TopAbs_EDGE )
3306       {
3307         // inflate from VERTEX along EDGE
3308         edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3309       }
3310       else if ( eos.ShapeType() == TopAbs_VERTEX )
3311       {
3312         // inflate from VERTEX along FACE
3313         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3314                                    node, helper, normOK, &edge._cosin);
3315       }
3316       else
3317       {
3318         // inflate from EDGE along FACE
3319         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3320                                    node, helper, normOK);
3321       }
3322     }
3323     else // layers are on all FACEs of SOLID the node is on
3324     {
3325       int nbOkNorms = 0;
3326       for ( int iF = 0; iF < totalNbFaces; ++iF )
3327       {
3328         F = TopoDS::Face( face2Norm[ iF ].first );
3329         geomNorm = getFaceNormal( node, F, helper, normOK );
3330         if ( !normOK ) continue;
3331         nbOkNorms++;
3332
3333         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3334           geomNorm.Reverse();
3335         face2Norm[ iF ].second = geomNorm.XYZ();
3336         edge._normal += geomNorm.XYZ();
3337       }
3338       if ( nbOkNorms == 0 )
3339         return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3340
3341       if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3342       {
3343         // opposite normals, re-get normals at shifted positions (IPAL 52426)
3344         edge._normal.SetCoord( 0,0,0 );
3345         for ( int iF = 0; iF < totalNbFaces; ++iF )
3346         {
3347           const TopoDS_Face& F = face2Norm[iF].first;
3348           geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3349           if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3350             geomNorm.Reverse();
3351           if ( normOK )
3352             face2Norm[ iF ].second = geomNorm.XYZ();
3353           edge._normal += face2Norm[ iF ].second;
3354         }
3355       }
3356
3357       if ( totalNbFaces >= 3 )
3358       {
3359         edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces );
3360       }
3361     }
3362   }
3363   else // !useGeometry - get _normal using surrounding mesh faces
3364   {
3365     edge._normal = getWeigthedNormal( &edge );
3366
3367     // set<TGeomID> faceIds;
3368     //
3369     // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3370     // while ( fIt->more() )
3371     // {
3372     //   const SMDS_MeshElement* face = fIt->next();
3373     //   if ( eos.GetNormal( face, geomNorm ))
3374     //   {
3375     //     if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3376     //       continue; // use only one mesh face on FACE
3377     //     edge._normal += geomNorm.XYZ();
3378     //     totalNbFaces++;
3379     //   }
3380     // }
3381   }
3382
3383   // compute _cosin
3384   //if ( eos._hyp.UseSurfaceNormal() )
3385   {
3386     switch ( eos.ShapeType() )
3387     {
3388     case TopAbs_FACE: {
3389       edge._cosin = 0;
3390       break;
3391     }
3392     case TopAbs_EDGE: {
3393       TopoDS_Edge E    = TopoDS::Edge( eos._shape );
3394       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3395       double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3396       edge._cosin      = Cos( angle );
3397       break;
3398     }
3399     case TopAbs_VERTEX: {
3400       if ( eos.SWOLType() != TopAbs_FACE ) { // else _cosin is set by getFaceDir()
3401         TopoDS_Vertex V  = TopoDS::Vertex( eos._shape );
3402         gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3403         double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3404         edge._cosin      = Cos( angle );
3405         if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3406           for ( int iF = totalNbFaces-2; iF >=0; --iF )
3407           {
3408             F = face2Norm[ iF ].first;
3409             inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3410             if ( normOK ) {
3411               double angle = inFaceDir.Angle( edge._normal );
3412               double cosin = Cos( angle );
3413               if ( Abs( cosin ) > edge._cosin )
3414                 edge._cosin = cosin;
3415             }
3416           }
3417       }
3418       break;
3419     }
3420     default:
3421       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3422     }
3423   }
3424
3425   double normSize = edge._normal.SquareModulus();
3426   if ( normSize < numeric_limits<double>::min() )
3427     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3428
3429   edge._normal /= sqrt( normSize );
3430
3431   if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3432   {
3433     getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3434     edge._nodes.resize( 1 );
3435     edge._normal.SetCoord( 0,0,0 );
3436     edge._maxLen = 0;
3437   }
3438
3439   // Set the rest data
3440   // --------------------
3441
3442   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3443
3444   if ( onShrinkShape )
3445   {
3446     const SMDS_MeshNode* tgtNode = edge._nodes.back();
3447     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3448       sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
3449
3450     // set initial position which is parameters on _sWOL in this case
3451     if ( eos.SWOLType() == TopAbs_EDGE )
3452     {
3453       double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3454       edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3455       if ( edge._nodes.size() > 1 )
3456         getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3457     }
3458     else // eos.SWOLType() == TopAbs_FACE
3459     {
3460       gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3461       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3462       if ( edge._nodes.size() > 1 )
3463         getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3464     }
3465
3466     if ( edge._nodes.size() > 1 )
3467     {
3468       // check if an angle between a FACE with layers and SWOL is sharp,
3469       // else the edge should not inflate
3470       F.Nullify();
3471       for ( int iF = 0; iF < totalNbFaces  &&  F.IsNull();  ++iF ) // find a FACE with VL
3472         if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3473           F = face2Norm[iF].first;
3474       if ( !F.IsNull())
3475       {
3476         geomNorm = getFaceNormal( node, F, helper, normOK );
3477         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3478           geomNorm.Reverse(); // inside the SOLID
3479         if ( geomNorm * edge._normal < -0.001 )
3480         {
3481           getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3482           edge._nodes.resize( 1 );
3483         }
3484         else if ( edge._lenFactor > 3 )
3485         {
3486           edge._lenFactor = 2;
3487           edge.Set( _LayerEdge::RISKY_SWOL );
3488         }
3489       }
3490     }
3491   }
3492   else
3493   {
3494     edge._pos.push_back( SMESH_TNodeXYZ( node ));
3495
3496     if ( eos.ShapeType() == TopAbs_FACE )
3497     {
3498       double angle;
3499       for ( size_t i = 0; i < edge._simplices.size(); ++i )
3500       {
3501         edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3502         edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3503       }
3504     }
3505   }
3506
3507   // Set neighbor nodes for a _LayerEdge based on EDGE
3508
3509   if ( eos.ShapeType() == TopAbs_EDGE /*||
3510        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3511   {
3512     edge._2neibors = new _2NearEdges;
3513     // target nodes instead of source ones will be set later
3514   }
3515
3516   return true;
3517 }
3518
3519 //================================================================================
3520 /*!
3521  * \brief Return normal to a FACE at a node
3522  *  \param [in] n - node
3523  *  \param [in] face - FACE
3524  *  \param [in] helper - helper
3525  *  \param [out] isOK - true or false
3526  *  \param [in] shiftInside - to find normal at a position shifted inside the face
3527  *  \return gp_XYZ - normal
3528  */
3529 //================================================================================
3530
3531 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3532                                       const TopoDS_Face&   face,
3533                                       SMESH_MesherHelper&  helper,
3534                                       bool&                isOK,
3535                                       bool                 shiftInside)
3536 {
3537   gp_XY uv;
3538   if ( shiftInside )
3539   {
3540     // get a shifted position
3541     gp_Pnt p = SMESH_TNodeXYZ( node );
3542     gp_XYZ shift( 0,0,0 );
3543     TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3544     switch ( S.ShapeType() ) {
3545     case TopAbs_VERTEX:
3546     {
3547       shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3548       break;
3549     }
3550     case TopAbs_EDGE:
3551     {
3552       shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3553       break;
3554     }
3555     default:
3556       isOK = false;
3557     }
3558     if ( isOK )
3559       shift.Normalize();
3560     p.Translate( shift * 1e-5 );
3561
3562     TopLoc_Location loc;
3563     GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3564
3565     if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3566     
3567     projector.Perform( p );
3568     if ( !projector.IsDone() || projector.NbPoints() < 1 )
3569     {
3570       isOK = false;
3571       return p.XYZ();
3572     }
3573     Quantity_Parameter U,V;
3574     projector.LowerDistanceParameters(U,V);
3575     uv.SetCoord( U,V );
3576   }
3577   else
3578   {
3579     uv = helper.GetNodeUV( face, node, 0, &isOK );
3580   }
3581
3582   gp_Dir normal;
3583   isOK = false;
3584
3585   Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3586
3587   if ( !shiftInside &&
3588        helper.IsDegenShape( node->getshapeId() ) &&
3589        getFaceNormalAtSingularity( uv, face, helper, normal ))
3590   {
3591     isOK = true;
3592     return normal.XYZ();
3593   }
3594
3595   int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3596   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3597
3598   if ( pointKind == IMPOSSIBLE &&
3599        node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3600   {
3601     // probably NormEstim() failed due to a too high tolerance
3602     pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3603     isOK = ( pointKind < IMPOSSIBLE );
3604   }
3605   if ( pointKind < IMPOSSIBLE )
3606   {
3607     if ( pointKind != REGULAR &&
3608          !shiftInside &&
3609          node->GetPosition()->GetDim() < 2 ) // FACE boundary
3610     {
3611       gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3612       if ( normShift * normal.XYZ() < 0. )
3613         normal = normShift;
3614     }
3615     isOK = true;
3616   }
3617
3618   if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3619   {
3620     const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3621
3622     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3623     while ( fIt->more() )
3624     {
3625       const SMDS_MeshElement* f = fIt->next();
3626       if ( f->getshapeId() == faceID )
3627       {
3628         isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3629         if ( isOK )
3630         {
3631           TopoDS_Face ff = face;
3632           ff.Orientation( TopAbs_FORWARD );
3633           if ( helper.IsReversedSubMesh( ff ))
3634             normal.Reverse();
3635           break;
3636         }
3637       }
3638     }
3639   }
3640   return normal.XYZ();
3641 }
3642
3643 //================================================================================
3644 /*!
3645  * \brief Try to get normal at a singularity of a surface basing on it's nature
3646  */
3647 //================================================================================
3648
3649 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY&        uv,
3650                                                   const TopoDS_Face&  face,
3651                                                   SMESH_MesherHelper& helper,
3652                                                   gp_Dir&             normal )
3653 {
3654   BRepAdaptor_Surface surface( face );
3655   gp_Dir axis;
3656   if ( !getRovolutionAxis( surface, axis ))
3657     return false;
3658
3659   double f,l, d, du, dv;
3660   f = surface.FirstUParameter();
3661   l = surface.LastUParameter();
3662   d = ( uv.X() - f ) / ( l - f );
3663   du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3664   f = surface.FirstVParameter();
3665   l = surface.LastVParameter();
3666   d = ( uv.Y() - f ) / ( l - f );
3667   dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3668
3669   gp_Dir refDir;
3670   gp_Pnt2d testUV = uv;
3671   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3672   double tol = 1e-5;
3673   Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3674   for ( int iLoop = 0; true ; ++iLoop )
3675   {
3676     testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3677     if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3678       break;
3679     if ( iLoop > 20 )
3680       return false;
3681     tol /= 10.;
3682   }
3683
3684   if ( axis * refDir < 0. )
3685     axis.Reverse();
3686
3687   normal = axis;
3688
3689   return true;
3690 }
3691
3692 //================================================================================
3693 /*!
3694  * \brief Return a normal at a node weighted with angles taken by faces
3695  */
3696 //================================================================================
3697
3698 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3699 {
3700   const SMDS_MeshNode* n = edge->_nodes[0];
3701
3702   gp_XYZ resNorm(0,0,0);
3703   SMESH_TNodeXYZ p0( n ), pP, pN;
3704   for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3705   {
3706     pP.Set( edge->_simplices[i]._nPrev );
3707     pN.Set( edge->_simplices[i]._nNext );
3708     gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3709     double l0P = v0P.SquareMagnitude();
3710     double l0N = v0N.SquareMagnitude();
3711     double lPN = vPN.SquareMagnitude();
3712     if ( l0P < std::numeric_limits<double>::min() ||
3713          l0N < std::numeric_limits<double>::min() ||
3714          lPN < std::numeric_limits<double>::min() )
3715       continue;
3716     double lNorm = norm.SquareMagnitude();
3717     double  sin2 = lNorm / l0P / l0N;
3718     double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3719
3720     double weight = sin2 * angle / lPN;
3721     resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3722   }
3723
3724   return resNorm;
3725 }
3726
3727 //================================================================================
3728 /*!
3729  * \brief Return a normal at a node by getting a common point of offset planes
3730  *        defined by the FACE normals
3731  */
3732 //================================================================================
3733
3734 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge*                      edge,
3735                                            std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3736                                            int                              nbFaces )
3737 {
3738   SMESH_TNodeXYZ p0 = edge->_nodes[0];
3739
3740   gp_XYZ resNorm(0,0,0);
3741   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3742   if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3743   {
3744     for ( int i = 0; i < nbFaces; ++i )
3745       resNorm += f2Normal[i].second;
3746     return resNorm;
3747   }
3748
3749   // prepare _OffsetPlane's
3750   vector< _OffsetPlane > pln( nbFaces );
3751   for ( int i = 0; i < nbFaces; ++i )
3752   {
3753     pln[i]._faceIndex = i;
3754     pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3755   }
3756
3757   // intersect neighboring OffsetPlane's
3758   PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3759   while ( const TopoDS_Shape* edge = edgeIt->next() )
3760   {
3761     int f1 = -1, f2 = -1;
3762     for ( int i = 0; i < nbFaces &&  f2 < 0;  ++i )
3763       if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3764         (( f1 < 0 ) ? f1 : f2 ) = i;
3765
3766     if ( f2 >= 0 )
3767       pln[ f1 ].ComputeIntersectionLine( pln[ f2 ]);
3768   }
3769
3770   // get a common point
3771   gp_XYZ commonPnt( 0, 0, 0 );
3772   int nbPoints = 0;
3773   bool isPointFound;
3774   for ( int i = 0; i < nbFaces; ++i )
3775   {
3776     commonPnt += pln[ i ].GetCommonPoint( isPointFound );
3777     nbPoints  += isPointFound;
3778   }
3779   gp_XYZ wgtNorm = getWeigthedNormal( edge );
3780   if ( nbPoints == 0 )
3781     return wgtNorm;
3782
3783   commonPnt /= nbPoints;
3784   resNorm = commonPnt - p0;
3785
3786   // choose the best among resNorm and wgtNorm
3787   resNorm.Normalize();
3788   wgtNorm.Normalize();
3789   double resMinDot = std::numeric_limits<double>::max();
3790   double wgtMinDot = std::numeric_limits<double>::max();
3791   for ( int i = 0; i < nbFaces; ++i )
3792   {
3793     resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
3794     wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
3795   }
3796
3797   if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
3798   {
3799     edge->Set( _LayerEdge::MULTI_NORMAL );
3800   }
3801
3802   return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
3803 }
3804
3805 //================================================================================
3806 /*!
3807  * \brief Compute line of intersection of 2 planes
3808  */
3809 //================================================================================
3810
3811 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane& pln )
3812 {
3813   int iNext = bool( _faceIndexNext[0] >= 0 );
3814   _faceIndexNext[ iNext ] = pln._faceIndex;
3815
3816   gp_XYZ n1 = _plane.Axis().Direction().XYZ();
3817   gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
3818
3819   gp_XYZ lineDir = n1 ^ n2;
3820
3821   double x = Abs( lineDir.X() );
3822   double y = Abs( lineDir.Y() );
3823   double z = Abs( lineDir.Z() );
3824
3825   int cooMax; // max coordinate
3826   if (x > y) {
3827     if (x > z) cooMax = 1;
3828     else       cooMax = 3;
3829   }
3830   else {
3831     if (y > z) cooMax = 2;
3832     else       cooMax = 3;
3833   }
3834
3835   if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
3836     return;
3837
3838   gp_Pnt linePos;
3839   // the constants in the 2 plane equations
3840   double d1 = - ( _plane.Axis().Direction().XYZ()     * _plane.Location().XYZ() );
3841   double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
3842
3843   switch ( cooMax ) {
3844   case 1:
3845     linePos.SetX(  0 );
3846     linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
3847     linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
3848     break;
3849   case 2:
3850     linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
3851     linePos.SetY(  0 );
3852     linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
3853     break;
3854   case 3:
3855     linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
3856     linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
3857     linePos.SetZ(  0 );
3858   }
3859
3860   gp_Lin& line = _lines[ iNext ];
3861   line.SetDirection( lineDir );
3862   line.SetLocation ( linePos );
3863
3864   _isLineOK[ iNext ] = true;
3865
3866
3867   iNext = bool( pln._faceIndexNext[0] >= 0 );
3868   pln._lines        [ iNext ] = line;
3869   pln._faceIndexNext[ iNext ] = this->_faceIndex;
3870   pln._isLineOK     [ iNext ] = true;
3871 }
3872
3873 //================================================================================
3874 /*!
3875  * \brief Computes intersection point of two _lines
3876  */
3877 //================================================================================
3878
3879 gp_XYZ _OffsetPlane::GetCommonPoint(bool& isFound) const
3880 {
3881   gp_XYZ p( 0,0,0 );
3882   isFound = false;
3883
3884   if ( NbLines() == 2 )
3885   {
3886     gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
3887     double  dot01 = lPerp0 * _lines[1].Direction().XYZ();
3888     if ( Abs( dot01 ) > std::numeric_limits<double>::min() )
3889     {
3890       gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
3891       double   u1 = - ( lPerp0 * l0l1 ) / dot01;
3892       p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
3893       isFound = true;
3894     }
3895   }
3896
3897   return p;
3898 }
3899
3900 //================================================================================
3901 /*!
3902  * \brief Find 2 neigbor nodes of a node on EDGE
3903  */
3904 //================================================================================
3905
3906 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
3907                                         const SMDS_MeshNode*& n1,
3908                                         const SMDS_MeshNode*& n2,
3909                                         _EdgesOnShape&        eos,
3910                                         _SolidData&           data)
3911 {
3912   const SMDS_MeshNode* node = edge->_nodes[0];
3913   const int        shapeInd = eos._shapeID;
3914   SMESHDS_SubMesh*   edgeSM = 0;
3915   if ( eos.ShapeType() == TopAbs_EDGE )
3916   {
3917     edgeSM = eos._subMesh->GetSubMeshDS();
3918     if ( !edgeSM || edgeSM->NbElements() == 0 )
3919       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
3920   }
3921   int iN = 0;
3922   n2 = 0;
3923   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
3924   while ( eIt->more() && !n2 )
3925   {
3926     const SMDS_MeshElement* e = eIt->next();
3927     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
3928     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
3929     if ( edgeSM )
3930     {
3931       if (!edgeSM->Contains(e)) continue;
3932     }
3933     else
3934     {
3935       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
3936       if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
3937     }
3938     ( iN++ ? n2 : n1 ) = nNeibor;
3939   }
3940   if ( !n2 )
3941     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
3942   return true;
3943 }
3944
3945 //================================================================================
3946 /*!
3947  * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
3948  */
3949 //================================================================================
3950
3951 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
3952                                      const SMDS_MeshNode* n2,
3953                                      const _EdgesOnShape& eos,
3954                                      SMESH_MesherHelper&  helper)
3955 {
3956   if ( eos.ShapeType() != TopAbs_EDGE )
3957     return;
3958
3959   gp_XYZ  pos = SMESH_TNodeXYZ( _nodes[0] );
3960   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
3961   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
3962
3963   // Set _curvature
3964
3965   double      sumLen = vec1.Modulus() + vec2.Modulus();
3966   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
3967   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
3968   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
3969   double      avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
3970   if ( _curvature ) delete _curvature;
3971   _curvature = _Curvature::New( avgNormProj, avgLen );
3972   // if ( _curvature )
3973   //   debugMsg( _nodes[0]->GetID()
3974   //             << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
3975   //             << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
3976   //             << _curvature->lenDelta(0) );
3977
3978   // Set _plnNorm
3979
3980   if ( eos._sWOL.IsNull() )
3981   {
3982     TopoDS_Edge  E = TopoDS::Edge( eos._shape );
3983     // if ( SMESH_Algo::isDegenerated( E ))
3984     //   return;
3985     gp_XYZ dirE    = getEdgeDir( E, _nodes[0], helper );
3986     gp_XYZ plnNorm = dirE ^ _normal;
3987     double proj0   = plnNorm * vec1;
3988     double proj1   = plnNorm * vec2;
3989     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
3990     {
3991       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
3992       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
3993     }
3994   }
3995 }
3996
3997 //================================================================================
3998 /*!
3999  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4000  * this and other _LayerEdge's are inflated along a FACE or an EDGE
4001  */
4002 //================================================================================
4003
4004 gp_XYZ _LayerEdge::Copy( _LayerEdge&         other,
4005                          _EdgesOnShape&      eos,
4006                          SMESH_MesherHelper& helper )
4007 {
4008   _nodes     = other._nodes;
4009   _normal    = other._normal;
4010   _len       = 0;
4011   _lenFactor = other._lenFactor;
4012   _cosin     = other._cosin;
4013   _2neibors  = other._2neibors;
4014   _curvature = 0; std::swap( _curvature, other._curvature );
4015   _2neibors  = 0; std::swap( _2neibors,  other._2neibors );
4016
4017   gp_XYZ lastPos( 0,0,0 );
4018   if ( eos.SWOLType() == TopAbs_EDGE )
4019   {
4020     double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4021     _pos.push_back( gp_XYZ( u, 0, 0));
4022
4023     u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4024     lastPos.SetX( u );
4025   }
4026   else // TopAbs_FACE
4027   {
4028     gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4029     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4030
4031     uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4032     lastPos.SetX( uv.X() );
4033     lastPos.SetY( uv.Y() );
4034   }
4035   return lastPos;
4036 }
4037
4038 //================================================================================
4039 /*!
4040  * \brief Set _cosin and _lenFactor
4041  */
4042 //================================================================================
4043
4044 void _LayerEdge::SetCosin( double cosin )
4045 {
4046   _cosin = cosin;
4047   cosin = Abs( _cosin );
4048   //_lenFactor = ( cosin < 1.-1e-12 ) ?  Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4049   _lenFactor = ( cosin < 1.-1e-12 ) ?  1./sqrt(1-cosin*cosin ) : 1.0;
4050 }
4051
4052 //================================================================================
4053 /*!
4054  * \brief Check if another _LayerEdge is a neighbor on EDGE
4055  */
4056 //================================================================================
4057
4058 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4059 {
4060   return (( this->_2neibors && this->_2neibors->include( edge )) ||
4061           ( edge->_2neibors && edge->_2neibors->include( this )));
4062 }
4063
4064 //================================================================================
4065 /*!
4066  * \brief Fills a vector<_Simplex > 
4067  */
4068 //================================================================================
4069
4070 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4071                              vector<_Simplex>&    simplices,
4072                              const set<TGeomID>&  ingnoreShapes,
4073                              const _SolidData*    dataToCheckOri,
4074                              const bool           toSort)
4075 {
4076   simplices.clear();
4077   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4078   while ( fIt->more() )
4079   {
4080     const SMDS_MeshElement* f = fIt->next();
4081     const TGeomID    shapeInd = f->getshapeId();
4082     if ( ingnoreShapes.count( shapeInd )) continue;
4083     const int nbNodes = f->NbCornerNodes();
4084     const int  srcInd = f->GetNodeIndex( node );
4085     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4086     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4087     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4088     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4089       std::swap( nPrev, nNext );
4090     simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4091   }
4092
4093   if ( toSort )
4094     SortSimplices( simplices );
4095 }
4096
4097 //================================================================================
4098 /*!
4099  * \brief Set neighbor simplices side by side
4100  */
4101 //================================================================================
4102
4103 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4104 {
4105   vector<_Simplex> sortedSimplices( simplices.size() );
4106   sortedSimplices[0] = simplices[0];
4107   size_t nbFound = 0;
4108   for ( size_t i = 1; i < simplices.size(); ++i )
4109   {
4110     for ( size_t j = 1; j < simplices.size(); ++j )
4111       if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4112       {
4113         sortedSimplices[i] = simplices[j];
4114         nbFound++;
4115         break;
4116       }
4117   }
4118   if ( nbFound == simplices.size() - 1 )
4119     simplices.swap( sortedSimplices );
4120 }
4121
4122 //================================================================================
4123 /*!
4124  * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
4125  */
4126 //================================================================================
4127
4128 void _ViscousBuilder::makeGroupOfLE()
4129 {
4130 #ifdef _DEBUG_
4131   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4132   {
4133     if ( _sdVec[i]._n2eMap.empty() ) continue;
4134
4135     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4136     TNode2Edge::iterator n2e;
4137     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4138     {
4139       _LayerEdge* le = n2e->second;
4140       // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4141       //   dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4142       //           << ", " << le->_nodes[iN]->GetID() <<"])");
4143       if ( le ) {
4144         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4145                 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4146       }
4147     }
4148     dumpFunctionEnd();
4149
4150     dumpFunction( SMESH_Comment("makeNormals") << i );
4151     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4152     {
4153       _LayerEdge* edge = n2e->second;
4154       SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4155       nXYZ += edge->_normal * _sdVec[i]._stepSize;
4156       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4157               << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4158     }
4159     dumpFunctionEnd();
4160
4161     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4162     dumpCmd( "faceId1 = mesh.NbElements()" );
4163     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4164     for ( ; fExp.More(); fExp.Next() )
4165     {
4166       if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4167       {
4168         if ( sm->NbElements() == 0 ) continue;
4169         SMDS_ElemIteratorPtr fIt = sm->GetElements();
4170         while ( fIt->more())
4171         {
4172           const SMDS_MeshElement* e = fIt->next();
4173           SMESH_Comment cmd("mesh.AddFace([");
4174           for ( int j = 0; j < e->NbCornerNodes(); ++j )
4175             cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4176           dumpCmd( cmd );
4177         }
4178       }
4179     }
4180     dumpCmd( "faceId2 = mesh.NbElements()" );
4181     dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4182              << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4183              << "'%s-%s' % (faceId1+1, faceId2))");
4184     dumpFunctionEnd();
4185   }
4186 #endif
4187 }
4188
4189 //================================================================================
4190 /*!
4191  * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4192  */
4193 //================================================================================
4194
4195 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4196 {
4197   data._geomSize = Precision::Infinite();
4198   double intersecDist;
4199   const SMDS_MeshElement* face;
4200   SMESH_MesherHelper helper( *_mesh );
4201
4202   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4203     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4204                                            data._proxyMesh->GetFaces( data._solid )));
4205
4206   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4207   {
4208     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4209     if ( eos._edges.empty() )
4210       continue;
4211     // get neighbor faces intersection with which should not be considered since
4212     // collisions are avoided by means of smoothing
4213     set< TGeomID > neighborFaces;
4214     if ( eos._hyp.ToSmooth() )
4215     {
4216       SMESH_subMeshIteratorPtr subIt =
4217         eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4218       while ( subIt->more() )
4219       {
4220         SMESH_subMesh* sm = subIt->next();
4221         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4222         while ( const TopoDS_Shape* face = fIt->next() )
4223           neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4224       }
4225     }
4226     // find intersections
4227     double thinkness = eos._hyp.GetTotalThickness();
4228     for ( size_t i = 0; i < eos._edges.size(); ++i )
4229     {
4230       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4231       eos._edges[i]->_maxLen = thinkness;
4232       eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4233       if ( intersecDist > 0 && face )
4234       {
4235         data._geomSize = Min( data._geomSize, intersecDist );
4236         if ( !neighborFaces.count( face->getshapeId() ))
4237           eos._edges[i]->_maxLen = Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. ));
4238       }
4239     }
4240   }
4241 }
4242
4243 //================================================================================
4244 /*!
4245  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4246  */
4247 //================================================================================
4248
4249 bool _ViscousBuilder::inflate(_SolidData& data)
4250 {
4251   SMESH_MesherHelper helper( *_mesh );
4252
4253   // Limit inflation step size by geometry size found by itersecting
4254   // normals of _LayerEdge's with mesh faces
4255   if ( data._stepSize > 0.3 * data._geomSize )
4256     limitStepSize( data, 0.3 * data._geomSize );
4257
4258   const double tgtThick = data._maxThickness;
4259   if ( data._stepSize > data._minThickness )
4260     limitStepSize( data, data._minThickness );
4261
4262   if ( data._stepSize < 1. )
4263     data._epsilon = data._stepSize * 1e-7;
4264
4265   debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4266
4267   findCollisionEdges( data, helper );
4268
4269   // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4270   for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4271     if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4272          data._edgesOnShape[i]._edges.size() > 0 &&
4273          data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4274     {
4275       data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4276       data._edgesOnShape[i]._edges[0]->Block( data );
4277     }
4278
4279   const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4280
4281   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4282   int nbSteps = 0, nbRepeats = 0;
4283   while ( avgThick < 0.99 )
4284   {
4285     // new target length
4286     double prevThick = curThick;
4287     curThick += data._stepSize;
4288     if ( curThick > tgtThick )
4289     {
4290       curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4291       nbRepeats++;
4292     }
4293
4294     double stepSize = curThick - prevThick;
4295     updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4296
4297     // Elongate _LayerEdge's
4298     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4299     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4300     {
4301       _EdgesOnShape& eos = data._edgesOnShape[iS];
4302       if ( eos._edges.empty() ) continue;
4303
4304       const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4305       for ( size_t i = 0; i < eos._edges.size(); ++i )
4306       {
4307         eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4308       }
4309     }
4310     dumpFunctionEnd();
4311
4312     if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4313       return false;
4314
4315     // Improve and check quality
4316     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4317     {
4318       if ( nbSteps > 0 )
4319       {
4320 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4321         debugMsg("NOT INVALIDATED STEP!");
4322         return error("Smoothing failed", data._index);
4323 #endif
4324         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4325         for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4326         {
4327           _EdgesOnShape& eos = data._edgesOnShape[iS];
4328           for ( size_t i = 0; i < eos._edges.size(); ++i )
4329             eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4330         }
4331         dumpFunctionEnd();
4332       }
4333       break; // no more inflating possible
4334     }
4335     nbSteps++;
4336
4337     // Evaluate achieved thickness
4338     avgThick = 0;
4339     int nbActiveEdges = 0;
4340     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4341     {
4342       _EdgesOnShape& eos = data._edgesOnShape[iS];
4343       if ( eos._edges.empty() ) continue;
4344
4345       const double shapeTgtThick = eos._hyp.GetTotalThickness();
4346       for ( size_t i = 0; i < eos._edges.size(); ++i )
4347       {
4348         avgThick      += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4349         nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4350       }
4351     }
4352     avgThick /= data._n2eMap.size();
4353     debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4354
4355 #ifdef BLOCK_INFLATION
4356     if ( nbActiveEdges == 0 )
4357     {
4358       debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4359       break;
4360     }
4361 #else
4362     if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4363     {
4364       debugMsg( "-- Stop inflation since "
4365                 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4366                 << tgtThick * avgThick << " ) * " << safeFactor );
4367       break;
4368     }
4369 #endif
4370     // new step size
4371     limitStepSize( data, 0.25 * distToIntersection );
4372     if ( data._stepSizeNodes[0] )
4373       data._stepSize = data._stepSizeCoeff *
4374         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4375
4376   } // while ( avgThick < 0.99 )
4377
4378   if ( nbSteps == 0 )
4379     return error("failed at the very first inflation step", data._index);
4380
4381   if ( avgThick < 0.99 )
4382   {
4383     if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4384     {
4385       data._proxyMesh->_warning.reset
4386         ( new SMESH_ComputeError (COMPERR_WARNING,
4387                                   SMESH_Comment("Thickness ") << tgtThick <<
4388                                   " of viscous layers not reached,"
4389                                   " average reached thickness is " << avgThick*tgtThick));
4390     }
4391   }
4392
4393   // Restore position of src nodes moved by inflation on _noShrinkShapes
4394   dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4395   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4396   {
4397     _EdgesOnShape& eos = data._edgesOnShape[iS];
4398     if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4399       for ( size_t i = 0; i < eos._edges.size(); ++i )
4400       {
4401         restoreNoShrink( *eos._edges[ i ] );
4402       }
4403   }
4404   dumpFunctionEnd();
4405
4406   return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4407 }
4408
4409 //================================================================================
4410 /*!
4411  * \brief Improve quality of layer inner surface and check intersection
4412  */
4413 //================================================================================
4414
4415 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4416                                      const int   infStep,
4417                                      double &    distToIntersection)
4418 {
4419   if ( data._nbShapesToSmooth == 0 )
4420     return true; // no shapes needing smoothing
4421
4422   bool moved, improved;
4423   double vol;
4424   vector< _LayerEdge* >    movedEdges, badEdges;
4425   vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4426   vector< bool >           isConcaveFace;
4427
4428   SMESH_MesherHelper helper(*_mesh);
4429   Handle(ShapeAnalysis_Surface) surface;
4430   TopoDS_Face F;
4431
4432   for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4433   {
4434     const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4435
4436     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4437     {
4438       _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4439       if ( !eos._toSmooth ||
4440            eos.ShapeType() != shapeType ||
4441            eos._edges.empty() )
4442         continue;
4443
4444       // already smoothed?
4445       // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4446       // if ( !toSmooth ) continue;
4447
4448       if ( !eos._hyp.ToSmooth() )
4449       {
4450         // smooth disabled by the user; check validy only
4451         if ( !isFace ) continue;
4452         for ( size_t i = 0; i < eos._edges.size(); ++i )
4453         {
4454           _LayerEdge* edge = eos._edges[i];
4455           for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4456             if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4457             {
4458               debugMsg( "-- Stop inflation. Bad simplex ("
4459                         << " "<< edge->_nodes[0]->GetID()
4460                         << " "<< edge->_nodes.back()->GetID()
4461                         << " "<< edge->_simplices[iF]._nPrev->GetID()
4462                         << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4463               return false;
4464             }
4465         }
4466         continue; // goto the next EDGE or FACE
4467       }
4468
4469       // prepare data
4470       if ( eos.SWOLType() == TopAbs_FACE )
4471       {
4472         if ( !F.IsSame( eos._sWOL )) {
4473           F = TopoDS::Face( eos._sWOL );
4474           helper.SetSubShape( F );
4475           surface = helper.GetSurface( F );
4476         }
4477       }
4478       else
4479       {
4480         F.Nullify(); surface.Nullify();
4481       }
4482       const TGeomID sInd = eos._shapeID;
4483
4484       // perform smoothing
4485
4486       if ( eos.ShapeType() == TopAbs_EDGE )
4487       {
4488         dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4489
4490         if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4491         {
4492           // smooth on EDGE's (normally we should not get here)
4493           int step = 0;
4494           do {
4495             moved = false;
4496             for ( size_t i = 0; i < eos._edges.size(); ++i )
4497             {
4498               moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4499             }
4500             dumpCmd( SMESH_Comment("# end step ")<<step);
4501           }
4502           while ( moved && step++ < 5 );
4503         }
4504         dumpFunctionEnd();
4505       }
4506
4507       else // smooth on FACE
4508       {
4509         eosC1.clear();
4510         eosC1.push_back( & eos );
4511         eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4512
4513         movedEdges.clear();
4514         isConcaveFace.resize( eosC1.size() );
4515         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4516         {
4517           isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID  );
4518           vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4519           for ( size_t i = 0; i < edges.size(); ++i )
4520             if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4521                  edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4522               movedEdges.push_back( edges[i] );
4523
4524           makeOffsetSurface( *eosC1[ iEOS ], helper );
4525         }
4526
4527         int step = 0, stepLimit = 5, nbBad = 0;
4528         while (( ++step <= stepLimit ) || improved )
4529         {
4530           dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4531                        <<"_InfStep"<<infStep<<"_"<<step); // debug
4532           int oldBadNb = nbBad;
4533           badEdges.clear();
4534
4535 #ifdef INCREMENTAL_SMOOTH
4536           bool findBest = false; // ( step == stepLimit );
4537           for ( size_t i = 0; i < movedEdges.size(); ++i )
4538           {
4539             movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4540             if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4541               badEdges.push_back( movedEdges[i] );
4542           }
4543 #else
4544           bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4545           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4546           {
4547             vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4548             for ( size_t i = 0; i < edges.size(); ++i )
4549             {
4550               edges[i]->Unset( _LayerEdge::SMOOTHED );
4551               if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4552                 badEdges.push_back( eos._edges[i] );
4553             }
4554           }
4555 #endif
4556           nbBad = badEdges.size();
4557
4558           if ( nbBad > 0 )
4559             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4560
4561           if ( !badEdges.empty() && step >= stepLimit / 2 )
4562           {
4563             if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4564               stepLimit = 9;
4565
4566             // resolve hard smoothing situation around concave VERTEXes
4567             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4568             {
4569               vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4570               for ( size_t i = 0; i < eosCoVe.size(); ++i )
4571                 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4572                                                          step, badEdges );
4573             }
4574             // look for the best smooth of _LayerEdge's neighboring badEdges
4575             nbBad = 0;
4576             for ( size_t i = 0; i < badEdges.size(); ++i )
4577             {
4578               _LayerEdge* ledge = badEdges[i];
4579               for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4580               {
4581                 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4582                 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4583               }
4584               ledge->Unset( _LayerEdge::SMOOTHED );
4585               nbBad += ledge->Smooth( step, true, /*findBest=*/true );
4586             }
4587             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4588           }
4589
4590           if ( nbBad == oldBadNb  &&
4591                nbBad > 0 &&
4592                step < stepLimit ) // smooth w/o chech of validity
4593           {
4594             dumpFunctionEnd();
4595             dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4596                          <<"_InfStep"<<infStep<<"_"<<step); // debug
4597             for ( size_t i = 0; i < movedEdges.size(); ++i )
4598             {
4599               movedEdges[i]->SmoothWoCheck();
4600             }
4601             if ( stepLimit < 9 )
4602               stepLimit++;
4603           }
4604
4605           improved = ( nbBad < oldBadNb );
4606
4607           dumpFunctionEnd();
4608
4609           if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
4610             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4611             {
4612               putOnOffsetSurface( *eosC1[ iEOS ], infStep, step, /*moveAll=*/step == 1 );
4613             }
4614
4615         } // smoothing steps
4616
4617         // project -- to prevent intersections or fix bad simplices
4618         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4619         {
4620           if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
4621             putOnOffsetSurface( *eosC1[ iEOS ], infStep );
4622         }
4623
4624         if ( !badEdges.empty() )
4625         {
4626           badEdges.clear();
4627           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4628           {
4629             for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4630             {
4631               if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4632
4633               _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4634               edge->CheckNeiborsOnBoundary( & badEdges );
4635               if ( nbBad > 0 )
4636               {
4637                 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4638                 const gp_XYZ& prevXYZ = edge->PrevCheckPos();
4639                 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4640                   if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4641                   {
4642                     debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
4643                              << " "<< tgtXYZ._node->GetID()
4644                              << " "<< edge->_simplices[j]._nPrev->GetID()
4645                              << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4646                     badEdges.push_back( edge );
4647                     break;
4648                   }
4649               }
4650             }
4651           }
4652
4653           // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4654           nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4655
4656           if ( nbBad > 0 )
4657             return false;
4658         }
4659
4660       } // // smooth on FACE's
4661     } // loop on shapes
4662   } // smooth on [ EDGEs, FACEs ]
4663
4664   // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
4665   eosC1.resize(1);
4666   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4667   {
4668     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4669     if ( eos.ShapeType() == TopAbs_FACE ||
4670          eos._edges.empty() ||
4671          !eos._sWOL.IsNull() )
4672       continue;
4673
4674     badEdges.clear();
4675     for ( size_t i = 0; i < eos._edges.size(); ++i )
4676     {
4677       _LayerEdge*      edge = eos._edges[i];
4678       if ( edge->_nodes.size() < 2 ) continue;
4679       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4680       const gp_XYZ& prevXYZ = edge->PrevCheckPos();
4681       //const gp_XYZ& prevXYZ = edge->PrevPos();
4682       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4683         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4684         {
4685           debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
4686                    << " "<< tgtXYZ._node->GetID()
4687                    << " "<< edge->_simplices[j]._nPrev->GetID()
4688                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4689           badEdges.push_back( edge );
4690           break;
4691         }
4692     }
4693
4694     // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4695     eosC1[0] = &eos;
4696     int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4697     if ( nbBad > 0 )
4698       return false;
4699   }
4700
4701
4702   // Check if the last segments of _LayerEdge intersects 2D elements;
4703   // checked elements are either temporary faces or faces on surfaces w/o the layers
4704
4705   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4706     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4707                                            data._proxyMesh->GetFaces( data._solid )) );
4708
4709 #ifdef BLOCK_INFLATION
4710   const bool toBlockInfaltion = true;
4711 #else
4712   const bool toBlockInfaltion = false;
4713 #endif
4714   distToIntersection = Precision::Infinite();
4715   double dist;
4716   const SMDS_MeshElement* intFace = 0;
4717   const SMDS_MeshElement* closestFace = 0;
4718   _LayerEdge* le = 0;
4719   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4720   {
4721     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4722     if ( eos._edges.empty() || !eos._sWOL.IsNull() )
4723       continue;
4724     for ( size_t i = 0; i < eos._edges.size(); ++i )
4725     {
4726       if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
4727            eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
4728         continue;
4729       if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4730       {
4731         return false;
4732         // commented due to "Illegal hash-positionPosition" error in NETGEN
4733         // on Debian60 on viscous_layers_01/B2 case
4734         // Collision; try to deflate _LayerEdge's causing it
4735         // badEdges.clear();
4736         // badEdges.push_back( eos._edges[i] );
4737         // eosC1[0] = & eos;
4738         // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4739         // if ( nbBad > 0 )
4740         //   return false;
4741
4742         // badEdges.clear();
4743         // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4744         // {
4745         //   if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4746         //   {
4747         //     const SMDS_MeshElement* srcFace =
4748         //       eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4749         //     SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4750         //     while ( nIt->more() )
4751         //     {
4752         //       const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4753         //       TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4754         //       if ( n2e != data._n2eMap.end() )
4755         //         badEdges.push_back( n2e->second );
4756         //     }
4757         //     eosC1[0] = eof;
4758         //     nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4759         //     if ( nbBad > 0 )
4760         //       return false;
4761         //   }
4762         // }
4763         // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4764         //   return false;
4765         // else
4766         //   continue;
4767       }
4768       if ( !intFace )
4769       {
4770         SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
4771         debugMsg( msg );
4772         continue;
4773       }
4774
4775       const bool isShorterDist = ( distToIntersection > dist );
4776       if ( toBlockInfaltion || isShorterDist )
4777       {
4778         // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
4779         // lying on this _ConvexFace
4780         if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
4781           if ( convFace->_subIdToEOS.count ( eos._shapeID ))
4782             continue;
4783
4784         // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
4785         // ( avoid limiting the thickness on the case of issue 22576)
4786         if ( intFace->getshapeId() == eos._shapeID  )
4787           continue;
4788
4789         // ignore intersection with intFace of an adjacent FACE
4790         if ( dist > 0 )
4791         {
4792           bool toIgnore = false;
4793           if (  eos._edges[i]->Is( _LayerEdge::TO_SMOOTH ))
4794           {
4795             const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
4796             if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
4797             {
4798               TopExp_Explorer edge( eos._shape, TopAbs_EDGE );
4799               for ( ; !toIgnore && edge.More(); edge.Next() )
4800                 // is adjacent - has a common EDGE
4801                 toIgnore = ( helper.IsSubShape( edge.Current(), S ));
4802
4803               if ( toIgnore ) // check angle between normals
4804               {
4805                 gp_XYZ normal;
4806                 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
4807                   toIgnore  = ( normal * eos._edges[i]->_normal > -0.5 );
4808               }
4809             }
4810           }
4811           if ( !toIgnore ) // check if the edge is a neighbor of intFace
4812           {
4813             for ( size_t iN = 0; !toIgnore &&  iN < eos._edges[i]->_neibors.size(); ++iN )
4814             {
4815               int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
4816               toIgnore = ( nInd >= 0 );
4817             }
4818           }
4819           if ( toIgnore )
4820             continue;
4821         }
4822
4823         // intersection not ignored
4824
4825         if ( toBlockInfaltion &&
4826              dist < ( eos._edges[i]->_len * theThickToIntersection ))
4827         {
4828           eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
4829           eos._edges[i]->Block( data );                  // not to inflate
4830
4831           if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4832           {
4833             // block _LayerEdge's, on top of which intFace is
4834             if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4835             {
4836               const SMDS_MeshElement* srcFace =
4837                 eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4838               SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4839               while ( nIt->more() )
4840               {
4841                 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4842                 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4843                 if ( n2e != data._n2eMap.end() )
4844                   n2e->second->Block( data );
4845               }
4846             }
4847           }
4848         }
4849
4850         if ( isShorterDist )
4851         {
4852           distToIntersection = dist;
4853           le = eos._edges[i];
4854           closestFace = intFace;
4855         }
4856
4857       } // if ( toBlockInfaltion || isShorterDist )
4858     } // loop on eos._edges
4859   } // loop on data._edgesOnShape
4860
4861 #ifdef __myDEBUG
4862   if ( closestFace )
4863   {
4864     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
4865     cout << "Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
4866          << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
4867          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
4868          << ") distance = " << distToIntersection<< endl;
4869   }
4870 #endif
4871
4872   return true;
4873 }
4874
4875 //================================================================================
4876 /*!
4877  * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4878  *  \param [in,out] badSmooEdges - _LayerEdge's to fix
4879  *  \return int - resulting nb of bad _LayerEdge's
4880  */
4881 //================================================================================
4882
4883 int _ViscousBuilder::invalidateBadSmooth( _SolidData&               data,
4884                                           SMESH_MesherHelper&       helper,
4885                                           vector< _LayerEdge* >&    badSmooEdges,
4886                                           vector< _EdgesOnShape* >& eosC1,
4887                                           const int                 infStep )
4888 {
4889   if ( badSmooEdges.empty() || infStep == 0 ) return 0;
4890
4891   dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
4892
4893   //data.UnmarkEdges();
4894
4895   double vol;
4896   //size_t iniNbBad = badSmooEdges.size();
4897   for ( size_t i = 0; i < badSmooEdges.size(); ++i )
4898   {
4899     _LayerEdge* edge = badSmooEdges[i];
4900     if ( edge->NbSteps() < 2 /*|| edge->Is( _LayerEdge::MARKED )*/)
4901       continue;
4902
4903     _EdgesOnShape* eos = data.GetShapeEdges( edge );
4904     edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
4905     edge->Block( data );
4906     //edge->Set( _LayerEdge::MARKED );
4907
4908     // look for _LayerEdge's of bad _simplices
4909     SMESH_TNodeXYZ tgtXYZ  = edge->_nodes.back();
4910     const gp_XYZ& prevXYZ1 = edge->PrevCheckPos();
4911     const gp_XYZ& prevXYZ2 = edge->PrevPos();
4912     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4913     {
4914       if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) &&
4915           ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol )))
4916         continue;
4917       for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
4918         if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
4919           badSmooEdges.push_back( edge->_neibors[iN] );
4920     }
4921
4922     if ( eos->ShapeType() == TopAbs_VERTEX )
4923     {
4924       // re-smooth on analytical EDGEs
4925       PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
4926       while ( const TopoDS_Shape* e = eIt->next() )
4927         if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
4928           if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
4929           {
4930             TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
4931             if ( eoe->SWOLType() == TopAbs_FACE ) {
4932               F       = TopoDS::Face( eoe->_sWOL );
4933               surface = helper.GetSurface( F );
4934             }
4935             eoe->_edgeSmoother->Perform( data, surface, F, helper );
4936           }
4937
4938     }
4939   } // loop on badSmooEdges
4940
4941
4942   // check result of invalidation
4943
4944   int nbBad = 0;
4945   for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4946   {
4947     for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4948     {
4949       if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4950       _LayerEdge*      edge = eosC1[ iEOS ]->_edges[i];
4951       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4952       const gp_XYZ& prevXYZ = edge->PrevCheckPos();
4953       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4954         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4955         {
4956           ++nbBad;
4957           debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
4958                    << " "<< tgtXYZ._node->GetID()
4959                    << " "<< edge->_simplices[j]._nPrev->GetID()
4960                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4961         }
4962     }
4963   }
4964   dumpFunctionEnd();
4965
4966   return nbBad;
4967 }
4968
4969 //================================================================================
4970 /*!
4971  * \brief Create an offset surface
4972  */
4973 //================================================================================
4974
4975 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
4976 {
4977   if ( eos._offsetSurf.IsNull() ||
4978        eos._edgeForOffset == 0 ||
4979        eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
4980     return;
4981
4982   Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
4983
4984   // find offset
4985   gp_Pnt   tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
4986   gp_Pnt2d   uv = baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
4987   double offset = baseSurface->Gap();
4988
4989   eos._offsetSurf.Nullify();
4990
4991   try
4992   {
4993     BRepOffsetAPI_MakeOffsetShape offsetMaker( eos._shape, -offset, Precision::Confusion() );
4994     if ( !offsetMaker.IsDone() ) return;
4995
4996     TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
4997     if ( !fExp.More() ) return;
4998
4999     TopoDS_Face F = TopoDS::Face( fExp.Current() );
5000     Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5001     if ( surf.IsNull() ) return;
5002
5003     eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5004   }
5005   catch ( Standard_Failure )
5006   {
5007   }
5008 }
5009
5010 //================================================================================
5011 /*!
5012  * \brief Put nodes of a curved FACE to its offset surface
5013  */
5014 //================================================================================
5015
5016 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape& eos,
5017                                           int            infStep,
5018                                           int            smooStep,
5019                                           bool           moveAll )
5020 {
5021   if ( eos._offsetSurf.IsNull() ||
5022        eos.ShapeType() != TopAbs_FACE ||
5023        eos._edgeForOffset == 0 ||
5024        eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5025     return;
5026
5027   double preci = BRep_Tool::Tolerance( TopoDS::Face( eos._shape )), vol;
5028   for ( size_t i = 0; i < eos._edges.size(); ++i )
5029   {
5030     _LayerEdge* edge = eos._edges[i];
5031     edge->Unset( _LayerEdge::MARKED );
5032     if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5033       continue;
5034     if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5035         continue;
5036
5037     int nbBlockedAround = 0;
5038     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5039       nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5040     if ( nbBlockedAround > 1 )
5041       continue;
5042
5043     gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5044     gp_Pnt2d uv = eos._offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5045     if ( eos._offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug 
5046     edge->_curvature->_uv = uv;
5047     if ( eos._offsetSurf->Gap() < 10 * preci ) continue; // same pos
5048
5049     gp_XYZ  newP = eos._offsetSurf->Value( uv ).XYZ();
5050     gp_XYZ prevP = edge->PrevCheckPos();
5051     bool      ok = true;
5052     if ( !moveAll )
5053       for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5054       {
5055         ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5056       }
5057     if ( ok )
5058     {
5059       SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5060       n->setXYZ( newP.X(), newP.Y(), newP.Z());
5061       edge->_pos.back() = newP;
5062
5063       edge->Set( _LayerEdge::MARKED );
5064     }
5065   }
5066
5067 #ifdef _DEBUG_
5068   // dumpMove() for debug
5069   size_t i = 0;
5070   for ( ; i < eos._edges.size(); ++i )
5071     if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5072       break;
5073   if ( i < eos._edges.size() )
5074   {
5075     dumpFunction(SMESH_Comment("putOnOffsetSurface_F") << eos._shapeID
5076                  << "_InfStep" << infStep << "_" << smooStep );
5077     for ( ; i < eos._edges.size(); ++i )
5078     {
5079       if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5080         dumpMove( eos._edges[i]->_nodes.back() );
5081     }
5082     dumpFunctionEnd();
5083   }
5084 #endif
5085 }
5086
5087 //================================================================================
5088 /*!
5089  * \brief Return a curve of the EDGE to be used for smoothing and arrange
5090  *        _LayerEdge's to be in a consequent order
5091  */
5092 //================================================================================
5093
5094 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge&  E,
5095                                                 _EdgesOnShape&      eos,
5096                                                 SMESH_MesherHelper& helper)
5097 {
5098   SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5099
5100   TopLoc_Location loc; double f,l;
5101
5102   Handle(Geom_Line)   line;
5103   Handle(Geom_Circle) circle;
5104   bool isLine, isCirc;
5105   if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5106   {
5107     // check if the EDGE is a line
5108     Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5109     if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5110       curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5111
5112     line   = Handle(Geom_Line)::DownCast( curve );
5113     circle = Handle(Geom_Circle)::DownCast( curve );
5114     isLine = (!line.IsNull());
5115     isCirc = (!circle.IsNull());
5116
5117     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5118     {
5119       isLine = SMESH_Algo::IsStraight( E );
5120
5121       if ( isLine )
5122         line = new Geom_Line( gp::OX() ); // only type does matter
5123     }
5124     if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5125     {
5126       // TODO
5127     }
5128   }
5129   else //////////////////////////////////////////////////////////////////////// 2D case
5130   {
5131     if ( !eos._isRegularSWOL ) // 23190
5132       return NULL;
5133
5134     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5135
5136     // check if the EDGE is a line
5137     Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5138     if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5139       curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5140
5141     Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
5142     Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5143     isLine = (!line2d.IsNull());
5144     isCirc = (!circle2d.IsNull());
5145
5146     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5147     {
5148       Bnd_B2d bndBox;
5149       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5150       while ( nIt->more() )
5151         bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5152       gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5153
5154       const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5155       for ( int i = 0; i < 2 && !isLine; ++i )
5156         isLine = ( size.Coord( i+1 ) <= lineTol );
5157     }
5158     if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5159     {
5160       // TODO
5161     }
5162     if ( isLine )
5163     {
5164       line = new Geom_Line( gp::OX() ); // only type does matter
5165     }
5166     else if ( isCirc )
5167     {
5168       gp_Pnt2d p = circle2d->Location();
5169       gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5170       circle = new Geom_Circle( ax, 1.); // only center position does matter
5171     }
5172   }
5173
5174   if ( isLine )
5175     return line;
5176   if ( isCirc )
5177     return circle;
5178
5179   return Handle(Geom_Curve)();
5180 }
5181
5182 //================================================================================
5183 /*!
5184  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5185  */
5186 //================================================================================
5187
5188 bool _Smoother1D::smoothAnalyticEdge( _SolidData&                    data,
5189                                       Handle(ShapeAnalysis_Surface)& surface,
5190                                       const TopoDS_Face&             F,
5191                                       SMESH_MesherHelper&            helper)
5192 {
5193   if ( !isAnalytic() ) return false;
5194
5195   const size_t iFrom = 0, iTo = _eos._edges.size();
5196
5197   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5198   {
5199     if ( F.IsNull() ) // 3D
5200     {
5201       SMESH_TNodeXYZ p0   ( _eos._edges[iFrom]->_2neibors->tgtNode(0) );
5202       SMESH_TNodeXYZ p1   ( _eos._edges[iTo-1]->_2neibors->tgtNode(1) );
5203       SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5204       SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5205       gp_XYZ newPos;
5206       for ( size_t i = iFrom; i < iTo; ++i )
5207       {
5208         _LayerEdge*       edge = _eos._edges[i];
5209         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5210         newPos = p0 * ( 1. - _leParams[i] ) + p1 * _leParams[i];
5211
5212         if ( _eos._edges[i]->Is( _LayerEdge::NORMAL_UPDATED ))
5213         {
5214           gp_XYZ curPos  = SMESH_TNodeXYZ ( tgtNode );
5215           gp_XYZ lineDir = pSrc1 - pSrc0;
5216           double   shift = ( lineDir * ( newPos - pSrc0 ) -
5217                              lineDir * ( curPos - pSrc0 ));
5218           newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5219         }
5220         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED ))
5221         {
5222           SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5223           double curThick = pSrc.SquareDistance( tgtNode );
5224           double newThink = ( pSrc - newPos ).SquareModulus();
5225           if ( newThink > curThick )
5226             continue;
5227         }
5228         edge->_pos.back() = newPos;
5229         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5230         dumpMove( tgtNode );
5231       }
5232     }
5233     else // 2D
5234     {
5235       _LayerEdge* e0 = getLEdgeOnV( 0 );
5236       _LayerEdge* e1 = getLEdgeOnV( 1 );
5237       gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ));
5238       gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ));
5239       if ( e0->_nodes.back() == e1->_nodes.back() ) // closed edge
5240       {
5241         int iPeriodic = helper.GetPeriodicIndex();
5242         if ( iPeriodic == 1 || iPeriodic == 2 )
5243         {
5244           uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
5245           if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
5246             std::swap( uv0, uv1 );
5247         }
5248       }
5249       const gp_XY rangeUV = uv1 - uv0;
5250       for ( size_t i = iFrom; i < iTo; ++i )
5251       {
5252         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5253         gp_XY newUV = uv0 + _leParams[i] * rangeUV;
5254         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5255
5256         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5257         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5258         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5259         dumpMove( tgtNode );
5260
5261         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5262         pos->SetUParameter( newUV.X() );
5263         pos->SetVParameter( newUV.Y() );
5264       }
5265     }
5266     return true;
5267   }
5268
5269   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5270   {
5271     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5272     gp_Pnt center3D = circle->Location();
5273
5274     if ( F.IsNull() ) // 3D
5275     {
5276       if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5277         return true; // closed EDGE - nothing to do
5278
5279       // circle is a real curve of EDGE
5280       gp_Circ circ = circle->Circ();
5281
5282       // new center is shifted along its axis
5283       const gp_Dir& axis = circ.Axis().Direction();
5284       _LayerEdge*     e0 = getLEdgeOnV(0);
5285       _LayerEdge*     e1 = getLEdgeOnV(1);
5286       SMESH_TNodeXYZ  p0 = e0->_nodes.back();
5287       SMESH_TNodeXYZ  p1 = e1->_nodes.back();
5288       double      shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5289       double      shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5290       gp_Pnt   newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5291
5292       double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5293
5294       gp_Ax2  newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5295       gp_Circ newCirc( newAxis, newRadius );
5296       gp_Vec  vecC1  ( newCenter, p1 );
5297
5298       double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5299       if ( uLast < 0 )
5300         uLast += 2 * M_PI;
5301       
5302       for ( size_t i = iFrom; i < iTo; ++i )
5303       {
5304         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5305         double u = uLast * _leParams[i];
5306         gp_Pnt p = ElCLib::Value( u, newCirc );
5307         _eos._edges[i]->_pos.back() = p.XYZ();
5308
5309         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5310         tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5311         dumpMove( tgtNode );
5312       }
5313       return true;
5314     }
5315     else // 2D
5316     {
5317       const gp_XY center( center3D.X(), center3D.Y() );
5318
5319       _LayerEdge* e0 = getLEdgeOnV(0);
5320       _LayerEdge* eM = _eos._edges[ 0 ];
5321       _LayerEdge* e1 = getLEdgeOnV(1);
5322       gp_XY      uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5323       gp_XY      uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5324       gp_XY      uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5325       gp_Vec2d vec0( center, uv0 );
5326       gp_Vec2d vecM( center, uvM );
5327       gp_Vec2d vec1( center, uv1 );
5328       double uLast = vec0.Angle( vec1 ); // -PI - +PI
5329       double uMidl = vec0.Angle( vecM );
5330       if ( uLast * uMidl <= 0. )
5331         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5332       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5333
5334       gp_Ax2d   axis( center, vec0 );
5335       gp_Circ2d circ( axis, radius );
5336       for ( size_t i = iFrom; i < iTo; ++i )
5337       {
5338         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5339         double    newU = uLast * _leParams[i];
5340         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5341         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5342
5343         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5344         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5345         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5346         dumpMove( tgtNode );
5347
5348         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5349         pos->SetUParameter( newUV.X() );
5350         pos->SetVParameter( newUV.Y() );
5351       }
5352     }
5353     return true;
5354   }
5355
5356   return false;
5357 }
5358
5359 //================================================================================
5360 /*!
5361  * \brief smooth _LayerEdge's on a an EDGE
5362  */
5363 //================================================================================
5364
5365 bool _Smoother1D::smoothComplexEdge( _SolidData&                    data,
5366                                      Handle(ShapeAnalysis_Surface)& surface,
5367                                      const TopoDS_Face&             F,
5368                                      SMESH_MesherHelper&            helper)
5369 {
5370   if ( _offPoints.empty() )
5371     return false;
5372
5373   // move _offPoints to positions along normals of _LayerEdge's
5374
5375   _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5376   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED )) setNormalOnV( 0, helper );
5377   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) setNormalOnV( 1, helper );
5378   _leOnV[0]._len = e[0]->_len;
5379   _leOnV[1]._len = e[1]->_len;
5380   for ( size_t i = 0; i < _offPoints.size(); i++ )
5381   {
5382     _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5383     _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5384     const double w0 = _offPoints[i]._2edges._wgt[0];
5385     const double w1 = _offPoints[i]._2edges._wgt[1];
5386     gp_XYZ  avgNorm = ( e0->_normal    * w0 + e1->_normal    * w1 ).Normalized();
5387     double  avgLen  = ( e0->_len       * w0 + e1->_len       * w1 );
5388     double  avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
5389
5390     _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
5391     _offPoints[i]._len  = avgLen;
5392   }
5393
5394   double fTol = 0;
5395   if ( !surface.IsNull() ) // project _offPoints to the FACE
5396   {
5397     fTol = 100 * BRep_Tool::Tolerance( F );
5398     //const double segLen = _offPoints[0].Distance( _offPoints[1] );
5399
5400     gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
5401     //if ( surface->Gap() < 0.5 * segLen )
5402       _offPoints[0]._xyz = surface->Value( uv ).XYZ();
5403
5404     for ( size_t i = 1; i < _offPoints.size(); ++i )
5405     {
5406       uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
5407       //if ( surface->Gap() < 0.5 * segLen )
5408         _offPoints[i]._xyz = surface->Value( uv ).XYZ();
5409     }
5410   }
5411
5412   // project tgt nodes of extreme _LayerEdge's to the offset segments
5413
5414   gp_Pnt pExtreme[2], pProj[2];
5415   for ( int is2nd = 0; is2nd < 2; ++is2nd )
5416   {
5417     pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
5418     int  i = _iSeg[ is2nd ];
5419     int di = is2nd ? -1 : +1;
5420     bool projected = false;
5421     double uOnSeg, uOnSegDiff, uOnSegBestDiff = Precision::Infinite(), uOnSegPrevDiff = 0;
5422     int nbWorse = 0;
5423     do {
5424       gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ]    );
5425       gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
5426       uOnSeg     = ( v0p * v01 ) / v01.SquareMagnitude();
5427       uOnSegDiff = Abs( uOnSeg - 0.5 );
5428       projected  = ( uOnSegDiff <= 0.5 );
5429       if ( uOnSegDiff < uOnSegBestDiff )
5430       {
5431         _iSeg[ is2nd ] = i;
5432         pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
5433         uOnSegBestDiff = uOnSegDiff;
5434       }
5435       else if ( uOnSegDiff > uOnSegPrevDiff )
5436       {
5437         if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
5438           break;
5439       }
5440       uOnSegPrevDiff = uOnSegDiff;
5441       i += di;
5442     }
5443     while ( !projected &&
5444             i >= 0 && i+1 < (int)_offPoints.size() );
5445
5446     if ( !projected )
5447     {
5448       if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
5449       {
5450         _iSeg[0] = 0;
5451         _iSeg[1] = _offPoints.size()-2;
5452         debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
5453         return false;
5454       }
5455     }
5456   }
5457   if ( _iSeg[0] > _iSeg[1] )
5458   {
5459     debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
5460     return false;
5461   }
5462
5463   // compute normalized length of the offset segments located between the projections
5464
5465   size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
5466   vector< double > len( nbSeg + 1 );
5467   len[ iSeg++ ] = 0;
5468   len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz );
5469   for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
5470   {
5471     len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
5472   }
5473   len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
5474
5475   double d0 = pProj[0].Distance( pExtreme[0]);
5476   double d1 = pProj[1].Distance( pExtreme[1]);
5477   double fullLen = len.back() - d0 - d1;
5478   for ( iSeg = 0; iSeg < len.size(); ++iSeg )
5479     len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
5480
5481   // temporary replace extreme _offPoints by pExtreme
5482   gp_XYZ op[2] = { _offPoints[ _iSeg[0]   ]._xyz,
5483                    _offPoints[ _iSeg[1]+1 ]._xyz };
5484   _offPoints[ _iSeg[0]   ]._xyz = pExtreme[0].XYZ();
5485   _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
5486
5487   // distribute tgt nodes of _LayerEdge's between the projections
5488
5489   iSeg = 0;
5490   for ( size_t i = 0; i < _eos._edges.size(); ++i )
5491   {
5492     if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5493     while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
5494       iSeg++;
5495     double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
5496     gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0]     ]._xyz * ( 1 - r ) +
5497                  _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
5498
5499     if ( surface.IsNull() )
5500     {
5501       _eos._edges[i]->_pos.back() = p;
5502     }
5503     else // project a new node position to a FACE
5504     {
5505       gp_Pnt2d uv ( _eos._edges[i]->_pos.back().X(), _eos._edges[i]->_pos.back().Y() );
5506       gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
5507
5508       p = surface->Value( uv2 ).XYZ();
5509       _eos._edges[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
5510     }
5511     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5512     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5513     dumpMove( tgtNode );
5514   }
5515
5516   _offPoints[ _iSeg[0]   ]._xyz = op[0];
5517   _offPoints[ _iSeg[1]+1 ]._xyz = op[1];
5518
5519   return true;
5520 }
5521
5522 //================================================================================
5523 /*!
5524  * \brief Prepare for smoothing
5525  */
5526 //================================================================================
5527
5528 void _Smoother1D::prepare(_SolidData& data)
5529 {
5530   const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
5531   _curveLen = SMESH_Algo::EdgeLength( E );
5532
5533   // sort _LayerEdge's by position on the EDGE
5534   data.SortOnEdge( E, _eos._edges );
5535
5536   SMESH_MesherHelper& helper = data.GetHelper();
5537
5538   // compute normalized param of _eos._edges on EDGE
5539   _leParams.resize( _eos._edges.size() + 1 );
5540   {
5541     double curLen, prevLen = _leParams[0] = 1.0;
5542     gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
5543     _leParams[0] = 0;
5544     for ( size_t i = 0; i < _eos._edges.size(); ++i )
5545     {
5546       gp_Pnt p = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
5547       //curLen = prevLen * _eos._edges[i]->_2neibors->_wgt[1] / _eos._edges[i]->_2neibors->_wgt[0];
5548       curLen = p.Distance( pPrev );
5549       _leParams[i+1] = _leParams[i] + curLen;
5550       prevLen = curLen;
5551       pPrev = p;
5552     }
5553     double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
5554     for ( size_t i = 0; i < _leParams.size()-1; ++i )
5555       _leParams[i] = _leParams[i+1] / fullLen;
5556   }
5557
5558   // find intersection of neighbor _LayerEdge's to limit _maxLen
5559   // according to EDGE curvature (IPAL52648)
5560   _LayerEdge* e0 = _eos._edges[0];
5561   for ( size_t i = 1; i < _eos._edges.size(); ++i )
5562   {
5563     _LayerEdge* ei = _eos._edges[i];
5564     gp_XYZ plnNorm = e0->_normal ^ ei->_normal;
5565     gp_XYZ   perp0 = e0->_normal ^ plnNorm;
5566     double   dot0i = perp0 * ei->_normal;
5567     if ( Abs( dot0i ) > std::numeric_limits<double>::min() )
5568     {
5569       SMESH_TNodeXYZ srci( ei->_nodes[0] ), src0( e0->_nodes[0] );
5570       double ui = ( perp0 * ( src0 - srci )) / dot0i;
5571       if ( ui > 0 )
5572       {
5573         ei->_maxLen = Min(  ei->_maxLen, 0.75 * ui / ei->_lenFactor );
5574         if ( ei->_maxLen < ei->_len )
5575         {
5576           ei->InvalidateStep( ei->NbSteps(), _eos, /*restoreLength=*/true  );
5577           ei->SetNewLength( ei->_maxLen, _eos, helper );
5578           ei->Block( data );
5579         }
5580         gp_Pnt pi = srci + ei->_normal * ui;
5581         double u0 = pi.Distance( src0 );
5582         e0->_maxLen = Min(  e0->_maxLen, 0.75 * u0 / e0->_lenFactor );
5583         if ( e0->_maxLen < e0->_len )
5584         {
5585           e0->InvalidateStep( e0->NbSteps(), _eos, /*restoreLength=*/true  );
5586           e0->SetNewLength( e0->_maxLen, _eos, helper );
5587           e0->Block( data );
5588         }
5589       }
5590     }
5591     e0 = ei;
5592   }
5593     
5594   if ( isAnalytic() )
5595     return;
5596
5597   // divide E to have offset segments with low deflection
5598   BRepAdaptor_Curve c3dAdaptor( E );
5599   const double curDeflect = 0.1; //0.3; // 0.01; // Curvature deflection
5600   const double angDeflect = 0.1; //0.2; // 0.09; // Angular deflection
5601   GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
5602   if ( discret.NbPoints() <= 2 )
5603   {
5604     _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
5605     return;
5606   }
5607
5608   const double edgeLen = SMESH_Algo::EdgeLength( E );
5609   const double u0      = c3dAdaptor.FirstParameter();
5610   _offPoints.resize( discret.NbPoints() );
5611   for ( size_t i = 0; i < _offPoints.size(); i++ )
5612   {
5613     _offPoints[i]._xyz = discret.Value( i+1 ).XYZ();
5614     // use OffPnt::_len to  TEMPORARY  store normalized param of an offset point
5615     double u = discret.Parameter( i+1 );
5616     _offPoints[i]._len = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / edgeLen;
5617   }
5618
5619   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5620
5621   // set _2edges
5622   _offPoints    [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
5623   _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
5624   _2NearEdges tmp2edges;
5625   tmp2edges._edges[1] = _eos._edges[0];
5626   _leOnV[0]._2neibors = & tmp2edges;
5627   _leOnV[0]._nodes    = leOnV[0]->_nodes;
5628   _leOnV[1]._nodes    = leOnV[1]->_nodes;
5629   _LayerEdge* eNext, *ePrev = & _leOnV[0];
5630   for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
5631   {
5632     // find _LayerEdge's located before and after an offset point
5633     // (_eos._edges[ iLE ] is next after ePrev)
5634     while ( iLE < _eos._edges.size() && _offPoints[i]._len > _leParams[ iLE ] )
5635       ePrev = _eos._edges[ iLE++ ];
5636     eNext = ePrev->_2neibors->_edges[1];
5637
5638     gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
5639     gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
5640     double  r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
5641     _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
5642   }
5643
5644   int iLBO = _offPoints.size() - 2; // last but one
5645   _offPoints[iLBO]._2edges._edges[1] = & _leOnV[1];
5646
5647   // {
5648   //   TopoDS_Face face[2]; // FACEs sharing the EDGE
5649   //   PShapeIteratorPtr fIt = helper.GetAncestors( _eos._shape, *helper.GetMesh(), TopAbs_FACE );
5650   //   while ( const TopoDS_Shape* F = fIt->next() )
5651   //   {
5652   //     TGeomID fID = helper.GetMeshDS()->ShapeToIndex( *F );
5653   //     if ( ! data._ignoreFaceIds.count( fID ))
5654   //       face[ !face[0].IsNull() ] = *F;
5655   //   }
5656   //   if ( face[0].IsNull() ) return;
5657   //   if ( face[1].IsNull() ) face[1] = face[0];
5658   // }
5659
5660
5661   // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
5662
5663   setNormalOnV( 0, data.GetHelper() );
5664   setNormalOnV( 1, data.GetHelper() );
5665   _leOnV[ 0 ]._len = 0;
5666   _leOnV[ 1 ]._len = 0;
5667   _leOnV[ 0 ]._lenFactor = _offPoints[1   ]._2edges._edges[1]->_lenFactor;
5668   _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
5669
5670   _iSeg[0] = 0;
5671   _iSeg[1] = _offPoints.size()-2;
5672
5673   // initialize OffPnt::_len
5674   for ( size_t i = 0; i < _offPoints.size(); ++i )
5675     _offPoints[i]._len = 0;
5676
5677   if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
5678   {
5679     _leOnV[0]._len = leOnV[0]->_len;
5680     _leOnV[1]._len = leOnV[1]->_len;
5681     for ( size_t i = 0; i < _offPoints.size(); i++ )
5682     {
5683       _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5684       _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5685       const double w0 = _offPoints[i]._2edges._wgt[0];
5686       const double w1 = _offPoints[i]._2edges._wgt[1];
5687       double  avgLen  = ( e0->_len * w0 + e1->_len * w1 );
5688       gp_XYZ  avgXYZ  = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
5689                           SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
5690       _offPoints[i]._xyz = avgXYZ;
5691       _offPoints[i]._len = avgLen;
5692     }
5693   }
5694 }
5695
5696 //================================================================================
5697 /*!
5698  * \brief set _normal of _leOnV[is2nd] to be normal to the EDGE
5699  */
5700 //================================================================================
5701
5702 void _Smoother1D::setNormalOnV( const bool          is2nd,
5703                                 SMESH_MesherHelper& helper)
5704 {
5705   _LayerEdge*    leOnV = getLEdgeOnV( is2nd );
5706   const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
5707   TopoDS_Shape       V = helper.GetSubShapeByNode( leOnV->_nodes[0], helper.GetMeshDS() );
5708   gp_XYZ          eDir = getEdgeDir( E, TopoDS::Vertex( V ));
5709   gp_XYZ         cross = leOnV->_normal ^ eDir;
5710   gp_XYZ          norm = eDir ^ cross;
5711   double          size = norm.Modulus();
5712
5713   _leOnV[ is2nd ]._normal = norm / size;
5714 }
5715
5716 //================================================================================
5717 /*!
5718  * \brief Sort _LayerEdge's by a parameter on a given EDGE
5719  */
5720 //================================================================================
5721
5722 void _SolidData::SortOnEdge( const TopoDS_Edge&     E,
5723                              vector< _LayerEdge* >& edges)
5724 {
5725   map< double, _LayerEdge* > u2edge;
5726   for ( size_t i = 0; i < edges.size(); ++i )
5727     u2edge.insert( u2edge.end(),
5728                    make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
5729
5730   ASSERT( u2edge.size() == edges.size() );
5731   map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
5732   for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
5733     edges[i] = u2e->second;
5734
5735   Sort2NeiborsOnEdge( edges );
5736 }
5737
5738 //================================================================================
5739 /*!
5740  * \brief Set _2neibors according to the order of _LayerEdge on EDGE
5741  */
5742 //================================================================================
5743
5744 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
5745 {
5746   if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
5747
5748   for ( size_t i = 0; i < edges.size()-1; ++i )
5749     if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
5750       edges[i]->_2neibors->reverse();
5751
5752   const size_t iLast = edges.size() - 1;
5753   if ( edges.size() > 1 &&
5754        edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
5755     edges[iLast]->_2neibors->reverse();
5756 }
5757
5758 //================================================================================
5759 /*!
5760  * \brief Return _EdgesOnShape* corresponding to the shape
5761  */
5762 //================================================================================
5763
5764 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
5765 {
5766   if ( shapeID < (int)_edgesOnShape.size() &&
5767        _edgesOnShape[ shapeID ]._shapeID == shapeID )
5768     return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
5769
5770   for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
5771     if ( _edgesOnShape[i]._shapeID == shapeID )
5772       return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
5773
5774   return 0;
5775 }
5776
5777 //================================================================================
5778 /*!
5779  * \brief Return _EdgesOnShape* corresponding to the shape
5780  */
5781 //================================================================================
5782
5783 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
5784 {
5785   SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
5786   return GetShapeEdges( meshDS->ShapeToIndex( shape ));
5787 }
5788
5789 //================================================================================
5790 /*!
5791  * \brief Prepare data of the _LayerEdge for smoothing on FACE
5792  */
5793 //================================================================================
5794
5795 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
5796 {
5797   SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
5798
5799   set< TGeomID > vertices;
5800   TopoDS_Face F;
5801   if ( eos->ShapeType() == TopAbs_FACE )
5802   {
5803     // check FACE concavity and get concave VERTEXes
5804     F = TopoDS::Face( eos->_shape );
5805     if ( isConcave( F, helper, &vertices ))
5806       _concaveFaces.insert( eos->_shapeID );
5807
5808     // set eos._eosConcaVer
5809     eos->_eosConcaVer.clear();
5810     eos->_eosConcaVer.reserve( vertices.size() );
5811     for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
5812     {
5813       _EdgesOnShape* eov = GetShapeEdges( *v );
5814       if ( eov && eov->_edges.size() == 1 )
5815       {
5816         eos->_eosConcaVer.push_back( eov );
5817         for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
5818           eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
5819       }
5820     }
5821
5822     // SetSmooLen() to _LayerEdge's on FACE
5823     for ( size_t i = 0; i < eos->_edges.size(); ++i )
5824     {
5825       eos->_edges[i]->SetSmooLen( Precision::Infinite() );
5826     }
5827     SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
5828     while ( smIt->more() ) // loop on sub-shapes of the FACE
5829     {
5830       _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
5831       if ( !eoe ) continue;
5832
5833       vector<_LayerEdge*>& eE = eoe->_edges;
5834       for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
5835       {
5836         if ( eE[iE]->_cosin <= theMinSmoothCosin )
5837           continue;
5838
5839         SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
5840         while ( segIt->more() )
5841         {
5842           const SMDS_MeshElement* seg = segIt->next();
5843           if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
5844             continue;
5845           if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
5846             continue; // not to check a seg twice
5847           for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
5848           {
5849             _LayerEdge* eN = eE[iE]->_neibors[iN];
5850             if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
5851               continue;
5852             double dist    = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
5853             double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
5854             eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
5855             eN->Set( _LayerEdge::NEAR_BOUNDARY );
5856           }
5857         }
5858       }
5859     }
5860   } // if ( eos->ShapeType() == TopAbs_FACE )
5861
5862   for ( size_t i = 0; i < eos->_edges.size(); ++i )
5863   {
5864     eos->_edges[i]->_smooFunction = 0;
5865     eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
5866   }
5867   bool isCurved = false;
5868   for ( size_t i = 0; i < eos->_edges.size(); ++i )
5869   {
5870     _LayerEdge* edge = eos->_edges[i];
5871
5872     // get simplices sorted
5873     _Simplex::SortSimplices( edge->_simplices );
5874
5875     // smoothing function
5876     edge->ChooseSmooFunction( vertices, _n2eMap );
5877
5878     // set _curvature
5879     double avgNormProj = 0, avgLen = 0;
5880     for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
5881     {
5882       _Simplex& s = edge->_simplices[iS];
5883
5884       gp_XYZ  vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
5885       avgNormProj += edge->_normal * vec;
5886       avgLen      += vec.Modulus();
5887       if ( substituteSrcNodes )
5888       {
5889         s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
5890         s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
5891       }
5892     }
5893     avgNormProj /= edge->_simplices.size();
5894     avgLen      /= edge->_simplices.size();
5895     if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
5896     {
5897       isCurved = true;
5898       SMDS_FacePosition* fPos = dynamic_cast<SMDS_FacePosition*>( edge->_nodes[0]->GetPosition() );
5899       if ( !fPos )
5900         for ( size_t iS = 0; iS < edge->_simplices.size()  &&  !fPos; ++iS )
5901           fPos = dynamic_cast<SMDS_FacePosition*>( edge->_simplices[iS]._nPrev->GetPosition() );
5902       if ( fPos )
5903         edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
5904     }
5905   }
5906
5907   // prepare for putOnOffsetSurface()
5908   if (( eos->ShapeType() == TopAbs_FACE ) &&
5909       ( isCurved || !eos->_eosConcaVer.empty() ))
5910   {
5911     eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
5912     eos->_edgeForOffset = 0;
5913
5914     double maxCosin = -1;
5915     for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
5916     {
5917       _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
5918       if ( !eoe || eoe->_edges.empty() ) continue;
5919
5920       vector<_LayerEdge*>& eE = eoe->_edges;
5921       _LayerEdge* e = eE[ eE.size() / 2 ];
5922       if ( e->_cosin > maxCosin )
5923       {
5924         eos->_edgeForOffset = e;
5925         maxCosin = e->_cosin;
5926       }
5927     }
5928   }
5929 }
5930
5931 //================================================================================
5932 /*!
5933  * \brief Add faces for smoothing
5934  */
5935 //================================================================================
5936
5937 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
5938                                     const set< _EdgesOnShape* >* edgesNoAnaSmooth )
5939 {
5940   set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
5941   for ( ; eos != eosToSmooth.end(); ++eos )
5942   {
5943     if ( !*eos || (*eos)->_toSmooth ) continue;
5944
5945     (*eos)->_toSmooth = true;
5946
5947     if ( (*eos)->ShapeType() == TopAbs_FACE )
5948     {
5949       PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
5950       (*eos)->_toSmooth = true;
5951     }
5952   }
5953
5954   // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
5955   if ( edgesNoAnaSmooth )
5956     for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
5957     {
5958       if ( (*eos)->_edgeSmoother )
5959         (*eos)->_edgeSmoother->_anaCurve.Nullify();
5960     }
5961 }
5962
5963 //================================================================================
5964 /*!
5965  * \brief Fill data._collisionEdges
5966  */
5967 //================================================================================
5968
5969 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
5970 {
5971   data._collisionEdges.clear();
5972
5973   // set the full thickness of the layers to LEs
5974   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5975   {
5976     _EdgesOnShape& eos = data._edgesOnShape[iS];
5977     if ( eos._edges.empty() ) continue;
5978     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
5979
5980     for ( size_t i = 0; i < eos._edges.size(); ++i )
5981     {
5982       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5983       double maxLen = eos._edges[i]->_maxLen;
5984       eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
5985       eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
5986       eos._edges[i]->_maxLen = maxLen;
5987     }
5988   }
5989
5990   // make temporary quadrangles got by extrusion of
5991   // mesh edges along _LayerEdge._normal's
5992
5993   vector< const SMDS_MeshElement* > tmpFaces;
5994
5995   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5996   {
5997     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5998     if ( eos.ShapeType() != TopAbs_EDGE )
5999       continue;
6000     if ( eos._edges.empty() )
6001     {
6002       _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6003       SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6004       while ( smIt->more() )
6005         if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6006           if ( eov->_edges.size() == 1 )
6007             edge[ bool( edge[0]) ] = eov->_edges[0];
6008
6009       if ( edge[1] )
6010       {
6011         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6012         tmpFaces.push_back( f );
6013       }
6014     }
6015     for ( size_t i = 0; i < eos._edges.size(); ++i )
6016     {
6017       _LayerEdge* edge = eos._edges[i];
6018       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6019       {
6020         const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6021         if ( src2->GetPosition()->GetDim() > 0 &&
6022              src2->GetID() < edge->_nodes[0]->GetID() )
6023           continue; // avoid using same segment twice
6024
6025         // a _LayerEdge containg tgt2
6026         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6027
6028         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6029         tmpFaces.push_back( f );
6030       }
6031     }
6032   }
6033
6034   // Find _LayerEdge's intersecting tmpFaces.
6035
6036   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6037                                                             tmpFaces.end()));
6038   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6039     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6040
6041   double dist1, dist2, segLen, eps;
6042   _CollisionEdges collEdges;
6043   vector< const SMDS_MeshElement* > suspectFaces;
6044   const double angle30 = Cos( 30. * M_PI / 180. );
6045
6046   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6047   {
6048     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6049     if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6050       continue;
6051     // find sub-shapes whose VL can influence VL on eos
6052     set< TGeomID > neighborShapes;
6053     PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6054     while ( const TopoDS_Shape* face = fIt->next() )
6055     {
6056       TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6057       if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6058       {
6059         SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6060         while ( subIt->more() )
6061           neighborShapes.insert( subIt->next()->GetId() );
6062       }
6063     }
6064     if ( eos.ShapeType() == TopAbs_VERTEX )
6065     {
6066       PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6067       while ( const TopoDS_Shape* edge = eIt->next() )
6068         neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6069     }
6070     // find intersecting _LayerEdge's
6071     for ( size_t i = 0; i < eos._edges.size(); ++i )
6072     {
6073       _LayerEdge*   edge = eos._edges[i];
6074       gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6075       eps     = 0.5 * edge->_len;
6076       segLen *= 1.2;
6077
6078       gp_Vec eSegDir0, eSegDir1;
6079       if ( edge->IsOnEdge() )
6080       {
6081         SMESH_TNodeXYZ eP( edge->_nodes[0] );
6082         eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6083         eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6084       }
6085       suspectFaces.clear();
6086       searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len,
6087                                      SMDSAbs_Face, suspectFaces );
6088       collEdges._intEdges.clear();
6089       for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6090       {
6091         const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6092         if ( f->_le1 == edge || f->_le2 == edge ) continue;
6093         if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6094         if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6095         if ( edge->IsOnEdge() ) {
6096           if ( edge->_2neibors->include( f->_le1 ) ||
6097                edge->_2neibors->include( f->_le2 )) continue;
6098         }
6099         else {
6100           if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6101               ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge )))  continue;
6102         }
6103         dist1 = dist2 = Precision::Infinite();
6104         if ( !edge->SegTriaInter( lastSegment, f->_nn[0], f->_nn[1], f->_nn[2], dist1, eps ))
6105           dist1 = Precision::Infinite();
6106         if ( !edge->SegTriaInter( lastSegment, f->_nn[3], f->_nn[2], f->_nn[0], dist2, eps ))
6107           dist2 = Precision::Infinite();
6108         if (( dist1 > segLen ) && ( dist2 > segLen ))
6109           continue;
6110
6111         if ( edge->IsOnEdge() )
6112         {
6113           // skip perpendicular EDGEs
6114           gp_Vec fSegDir  = SMESH_TNodeXYZ( f->_nn[0] ) - SMESH_TNodeXYZ( f->_nn[3] );
6115           bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle30 ) ||
6116                               isLessAngle( eSegDir1, fSegDir, angle30 ) ||
6117                               isLessAngle( eSegDir0, fSegDir.Reversed(), angle30 ) ||
6118                               isLessAngle( eSegDir1, fSegDir.Reversed(), angle30 ));
6119           if ( !isParallel )
6120             continue;
6121         }
6122
6123         // either limit inflation of edges or remember them for updating _normal
6124         // double dot = edge->_normal * f->GetDir();
6125         // if ( dot > 0.1 )
6126         {
6127           collEdges._intEdges.push_back( f->_le1 );
6128           collEdges._intEdges.push_back( f->_le2 );
6129         }
6130         // else
6131         // {
6132         //   double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6133         //   edge->_maxLen = Min( shortLen, edge->_maxLen );
6134         // }
6135       }
6136
6137       if ( !collEdges._intEdges.empty() )
6138       {
6139         collEdges._edge = edge;
6140         data._collisionEdges.push_back( collEdges );
6141       }
6142     }
6143   }
6144
6145   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6146     delete tmpFaces[i];
6147
6148   // restore the zero thickness
6149   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6150   {
6151     _EdgesOnShape& eos = data._edgesOnShape[iS];
6152     if ( eos._edges.empty() ) continue;
6153     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6154
6155     for ( size_t i = 0; i < eos._edges.size(); ++i )
6156     {
6157       eos._edges[i]->InvalidateStep( 1, eos );
6158       eos._edges[i]->_len = 0;
6159     }
6160   }
6161 }
6162
6163 //================================================================================
6164 /*!
6165  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
6166  * _LayerEdge's on neighbor EDGE's
6167  */
6168 //================================================================================
6169
6170 bool _ViscousBuilder::updateNormals( _SolidData&         data,
6171                                      SMESH_MesherHelper& helper,
6172                                      int                 stepNb,
6173                                      double              stepSize)
6174 {
6175   updateNormalsOfC1Vertices( data );
6176
6177   if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
6178     return false;
6179
6180   // map to store new _normal and _cosin for each intersected edge
6181   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >           edge2newEdge;
6182   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
6183   _LayerEdge zeroEdge;
6184   zeroEdge._normal.SetCoord( 0,0,0 );
6185   zeroEdge._maxLen = Precision::Infinite();
6186   zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
6187
6188   set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
6189
6190   double segLen, dist1, dist2;
6191   vector< pair< _LayerEdge*, double > > intEdgesDist;
6192   _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
6193
6194   for ( int iter = 0; iter < 5; ++iter )
6195   {
6196     edge2newEdge.clear();
6197
6198     for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
6199     {
6200       _CollisionEdges& ce = data._collisionEdges[iE];
6201       _LayerEdge*   edge1 = ce._edge;
6202       if ( !edge1 || edge1->Is( _LayerEdge::BLOCKED )) continue;
6203       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6204       if ( !eos1 ) continue;
6205
6206       // detect intersections
6207       gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
6208       double testLen = 1.5 * edge1->_maxLen; //2 + edge1->_len * edge1->_lenFactor;
6209       double     eps = 0.5 * edge1->_len;
6210       intEdgesDist.clear();
6211       double minIntDist = Precision::Infinite();
6212       for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
6213       {
6214         if ( ce._intEdges[i  ]->Is( _LayerEdge::BLOCKED ) ||
6215              ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
6216           continue;
6217         double dot  = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
6218         double fact = ( 1.1 + dot * dot );
6219         SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
6220         SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
6221         gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
6222         gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
6223         dist1 = dist2 = Precision::Infinite();
6224         if ( !edge1->SegTriaInter( lastSeg, pSrc0, pTgt0, pSrc1, dist1, eps ) &&
6225              !edge1->SegTriaInter( lastSeg, pSrc1, pTgt1, pTgt0, dist2, eps ))
6226           continue;
6227         if (( dist1 > testLen || dist1 < 0 ) &&
6228             ( dist2 > testLen || dist2 < 0 ))
6229           continue;
6230
6231         // choose a closest edge
6232         gp_Pnt intP( lastSeg.Location().XYZ() +
6233                      lastSeg.Direction().XYZ() * ( Min( dist1, dist2 ) + segLen ));
6234         double d1 = intP.SquareDistance( pSrc0 );
6235         double d2 = intP.SquareDistance( pSrc1 );
6236         int iClose = i + ( d2 < d1 );
6237         _LayerEdge* edge2 = ce._intEdges[iClose];
6238         edge2->Unset( _LayerEdge::MARKED );
6239
6240         // choose a closest edge among neighbors
6241         gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
6242         d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
6243         for ( size_t j = 0; j < intEdgesDist.size(); ++j )
6244         {
6245           _LayerEdge * edgeJ = intEdgesDist[j].first;
6246           if ( edge2->IsNeiborOnEdge( edgeJ ))
6247           {
6248             d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
6249             ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
6250           }
6251         }
6252         intEdgesDist.push_back( make_pair( edge2, Min( dist1, dist2 )));
6253         // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
6254         // {
6255         //   iClose = i + !( d2 < d1 );
6256         //   intEdges.push_back( ce._intEdges[iClose] );
6257         //   ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
6258         // }
6259         minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist1, minIntDist );
6260         minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist2, minIntDist );
6261       }
6262
6263       //ce._edge = 0;
6264
6265       // compute new _normals
6266       for ( size_t i = 0; i < intEdgesDist.size(); ++i )
6267       {
6268         _LayerEdge* edge2    = intEdgesDist[i].first;
6269         double       distWgt = edge1->_len / intEdgesDist[i].second;
6270         if ( edge2->Is( _LayerEdge::MARKED )) continue;
6271         edge2->Set( _LayerEdge::MARKED );
6272
6273         // get a new normal
6274         gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
6275
6276         double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6277         double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6278         double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6279         // double cos1 = Abs( edge1->_cosin ),        cos2 = Abs( edge2->_cosin );
6280         // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
6281         // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6282         // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6283         gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
6284         newNormal.Normalize();
6285
6286         // get new cosin
6287         double newCos;
6288         double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
6289         if ( cos1 < theMinSmoothCosin )
6290         {
6291           newCos = cos2 * sgn1;
6292         }
6293         else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
6294         {
6295           newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
6296         }
6297         else
6298         {
6299           newCos = edge1->_cosin;
6300         }
6301
6302         e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
6303         e2neIt->second._normal += distWgt * newNormal;
6304         e2neIt->second._cosin   = newCos;
6305         e2neIt->second._maxLen  = 0.7 * minIntDist / edge1->_lenFactor;
6306         if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
6307           e2neIt->second._normal += dir2;
6308         e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
6309         e2neIt->second._normal += distWgt * newNormal;
6310         e2neIt->second._cosin   = edge2->_cosin;
6311         if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
6312           e2neIt->second._normal += dir1;
6313       }
6314     }
6315
6316     if ( edge2newEdge.empty() )
6317       break; //return true;
6318
6319     dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
6320
6321     // Update data of edges depending on a new _normal
6322
6323     data.UnmarkEdges();
6324     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6325     {
6326       _LayerEdge*    edge = e2neIt->first;
6327       _LayerEdge& newEdge = e2neIt->second;
6328       _EdgesOnShape*  eos = data.GetShapeEdges( edge );
6329
6330       // Check if a new _normal is OK:
6331       newEdge._normal.Normalize();
6332       if ( !isNewNormalOk( data, *edge, newEdge._normal ))
6333       {
6334         if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
6335         {
6336           edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6337           edge->_maxLen = newEdge._maxLen;
6338           edge->SetNewLength( newEdge._maxLen, *eos, helper );
6339         }
6340         continue; // the new _normal is bad
6341       }
6342       // the new _normal is OK
6343
6344       // find shapes that need smoothing due to change of _normal
6345       if ( edge->_cosin   < theMinSmoothCosin &&
6346            newEdge._cosin > theMinSmoothCosin )
6347       {
6348         if ( eos->_sWOL.IsNull() )
6349         {
6350           SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6351           while ( fIt->more() )
6352             shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
6353         }
6354         else // edge inflates along a FACE
6355         {
6356           TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
6357           PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE );
6358           while ( const TopoDS_Shape* E = eIt->next() )
6359           {
6360             if ( !helper.IsSubShape( *E, /*FACE=*/eos->_sWOL ))
6361               continue;
6362             gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
6363             double   angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
6364             if ( angle < M_PI / 2 )
6365               shapesToSmooth.insert( data.GetShapeEdges( *E ));
6366           }
6367         }
6368       }
6369
6370       double len = edge->_len;
6371       edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6372       edge->SetNormal( newEdge._normal );
6373       edge->SetCosin( newEdge._cosin );
6374       edge->SetNewLength( len, *eos, helper );
6375       edge->Set( _LayerEdge::MARKED );
6376       edge->Set( _LayerEdge::NORMAL_UPDATED );
6377       edgesNoAnaSmooth.insert( eos );
6378     }
6379
6380     // Update normals and other dependent data of not intersecting _LayerEdge's
6381     // neighboring the intersecting ones
6382
6383     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6384     {
6385       _LayerEdge*   edge1 = e2neIt->first;
6386       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6387       if ( !edge1->Is( _LayerEdge::MARKED ))
6388         continue;
6389
6390       if ( edge1->IsOnEdge() )
6391       {
6392         const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
6393         const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
6394         edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
6395       }
6396
6397       if ( !edge1->_2neibors )
6398         continue;
6399       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
6400       {
6401         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
6402         if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
6403           continue; // j-th neighbor is also intersected
6404         _LayerEdge* prevEdge = edge1;
6405         const int nbSteps = 10;
6406         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
6407         {
6408           if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
6409                neighbor->Is( _LayerEdge::MARKED ))
6410             break;
6411           _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
6412           if ( !eos ) continue;
6413           _LayerEdge* nextEdge = neighbor;
6414           if ( neighbor->_2neibors )
6415           {
6416             int iNext = 0;
6417             nextEdge = neighbor->_2neibors->_edges[iNext];
6418             if ( nextEdge == prevEdge )
6419               nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
6420           }
6421           double r = double(step-1)/nbSteps;
6422           if ( !nextEdge->_2neibors )
6423             r = Min( r, 0.5 );
6424
6425           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
6426           newNorm.Normalize();
6427           if ( !isNewNormalOk( data, *neighbor, newNorm ))
6428             break;
6429
6430           double len = neighbor->_len;
6431           neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6432           neighbor->SetNormal( newNorm );
6433           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
6434           if ( neighbor->_2neibors )
6435             neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
6436           neighbor->SetNewLength( len, *eos, helper );
6437           neighbor->Set( _LayerEdge::MARKED );
6438           neighbor->Set( _LayerEdge::NORMAL_UPDATED );
6439           edgesNoAnaSmooth.insert( eos );
6440
6441           if ( !neighbor->_2neibors )
6442             break; // neighbor is on VERTEX
6443
6444           // goto the next neighbor
6445           prevEdge = neighbor;
6446           neighbor = nextEdge;
6447         }
6448       }
6449     }
6450     dumpFunctionEnd();
6451   } // iterations
6452
6453   data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
6454
6455   return true;
6456 }
6457
6458 //================================================================================
6459 /*!
6460  * \brief Check if a new normal is OK
6461  */
6462 //================================================================================
6463
6464 bool _ViscousBuilder::isNewNormalOk( _SolidData&   data,
6465                                      _LayerEdge&   edge,
6466                                      const gp_XYZ& newNormal)
6467 {
6468   // check a min angle between the newNormal and surrounding faces
6469   vector<_Simplex> simplices;
6470   SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
6471   _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
6472   double newMinDot = 1, curMinDot = 1;
6473   for ( size_t i = 0; i < simplices.size(); ++i )
6474   {
6475     n1.Set( simplices[i]._nPrev );
6476     n2.Set( simplices[i]._nNext );
6477     gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
6478     double normLen2 = normFace.SquareModulus();
6479     if ( normLen2 < std::numeric_limits<double>::min() )
6480       continue;
6481     normFace /= Sqrt( normLen2 );
6482     newMinDot = Min( newNormal    * normFace, newMinDot );
6483     curMinDot = Min( edge._normal * normFace, curMinDot );
6484   }
6485   if ( newMinDot < 0.5 )
6486   {
6487     return ( newMinDot >= curMinDot * 0.9 );
6488     //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
6489     // double initMinDot2 = 1. - edge._cosin * edge._cosin;
6490     // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
6491   }
6492   return true;
6493 }
6494
6495 //================================================================================
6496 /*!
6497  * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
6498  */
6499 //================================================================================
6500
6501 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData&         data,
6502                                                SMESH_MesherHelper& helper,
6503                                                const int           nbSteps,
6504                                                const double        stepSize )
6505 {
6506   if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
6507     return true; // no shapes needing smoothing
6508
6509   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6510   {
6511     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6512     if ( //!eos._toSmooth ||  _eosC1 have _toSmooth == false
6513          !eos._hyp.ToSmooth() ||
6514          eos.ShapeType() != TopAbs_FACE ||
6515          eos._edges.empty() )
6516       continue;
6517
6518     bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
6519     if ( !toSmooth ) continue;
6520
6521     for ( size_t i = 0; i < eos._edges.size(); ++i )
6522     {
6523       _LayerEdge* edge = eos._edges[i];
6524       if ( !edge->Is( _LayerEdge::SMOOTHED ))
6525         continue;
6526       if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
6527         continue;
6528
6529       const gp_XYZ& pPrev = edge->PrevPos();
6530       const gp_XYZ& pLast = edge->_pos.back();
6531       gp_XYZ      stepVec = pLast - pPrev;
6532       double realStepSize = stepVec.Modulus();
6533       if ( realStepSize < numeric_limits<double>::min() )
6534         continue;
6535
6536       edge->_lenFactor = realStepSize / stepSize;
6537       edge->_normal    = stepVec / realStepSize;
6538       edge->Set( _LayerEdge::NORMAL_UPDATED );
6539     }
6540   }
6541
6542   return true;
6543 }
6544
6545 //================================================================================
6546 /*!
6547  * \brief Modify normals of _LayerEdge's on C1 VERTEXes
6548  */
6549 //================================================================================
6550
6551 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
6552 {
6553   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6554   {
6555     _EdgesOnShape& eov = data._edgesOnShape[ iS ];
6556     if ( eov._eosC1.empty() ||
6557          eov.ShapeType() != TopAbs_VERTEX ||
6558          eov._edges.empty() )
6559       continue;
6560
6561     gp_XYZ newNorm   = eov._edges[0]->_normal;
6562     double curThick  = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
6563     bool normChanged = false;
6564
6565     for ( size_t i = 0; i < eov._eosC1.size(); ++i )
6566     {
6567       _EdgesOnShape*   eoe = eov._eosC1[i];
6568       const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
6569       const double    eLen = SMESH_Algo::EdgeLength( e );
6570       TopoDS_Shape    oppV = SMESH_MesherHelper::IthVertex( 0, e );
6571       if ( oppV.IsSame( eov._shape ))
6572         oppV = SMESH_MesherHelper::IthVertex( 1, e );
6573       _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
6574       if ( !eovOpp || eovOpp->_edges.empty() ) continue;
6575
6576       double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
6577       if ( curThickOpp + curThick < eLen )
6578         continue;
6579
6580       double wgt = 2. * curThick / eLen;
6581       newNorm += wgt * eovOpp->_edges[0]->_normal;
6582       normChanged = true;
6583     }
6584     if ( normChanged )
6585     {
6586       eov._edges[0]->SetNormal( newNorm.Normalized() );
6587       eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
6588     }
6589   }
6590 }
6591
6592 //================================================================================
6593 /*!
6594  * \brief Modify normals of _LayerEdge's on _ConvexFace's
6595  */
6596 //================================================================================
6597
6598 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData&         data,
6599                                                   SMESH_MesherHelper& helper,
6600                                                   int                 stepNb )
6601 {
6602   SMESHDS_Mesh* meshDS = helper.GetMeshDS();
6603   bool isOK;
6604
6605   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
6606   for ( ; id2face != data._convexFaces.end(); ++id2face )
6607   {
6608     _ConvexFace & convFace = (*id2face).second;
6609     if ( convFace._normalsFixed )
6610       continue; // already fixed
6611     if ( convFace.CheckPrisms() )
6612       continue; // nothing to fix
6613
6614     convFace._normalsFixed = true;
6615
6616     BRepAdaptor_Surface surface ( convFace._face, false );
6617     BRepLProp_SLProps   surfProp( surface, 2, 1e-6 );
6618
6619     // check if the convex FACE is of spherical shape
6620
6621     Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
6622     Bnd_B3d nodesBox;
6623     gp_Pnt  center;
6624
6625     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6626     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6627     {
6628       _EdgesOnShape& eos = *(id2eos->second);
6629       if ( eos.ShapeType() == TopAbs_VERTEX )
6630       {
6631         _LayerEdge* ledge = eos._edges[ 0 ];
6632         if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
6633           centersBox.Add( center );
6634       }
6635       for ( size_t i = 0; i < eos._edges.size(); ++i )
6636         nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
6637     }
6638     if ( centersBox.IsVoid() )
6639     {
6640       debugMsg( "Error: centersBox.IsVoid()" );
6641       return false;
6642     }
6643     const bool isSpherical =
6644       ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
6645
6646     int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
6647     vector < _CentralCurveOnEdge > centerCurves( nbEdges );
6648
6649     if ( isSpherical )
6650     {
6651       // set _LayerEdge::_normal as average of all normals
6652
6653       // WARNING: different density of nodes on EDGEs is not taken into account that
6654       // can lead to an improper new normal
6655
6656       gp_XYZ avgNormal( 0,0,0 );
6657       nbEdges = 0;
6658       id2eos = convFace._subIdToEOS.begin();
6659       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6660       {
6661         _EdgesOnShape& eos = *(id2eos->second);
6662         // set data of _CentralCurveOnEdge
6663         if ( eos.ShapeType() == TopAbs_EDGE )
6664         {
6665           _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
6666           ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
6667           if ( !eos._sWOL.IsNull() )
6668             ceCurve._adjFace.Nullify();
6669           else
6670             ceCurve._ledges.insert( ceCurve._ledges.end(),
6671                                     eos._edges.begin(), eos._edges.end());
6672         }
6673         // summarize normals
6674         for ( size_t i = 0; i < eos._edges.size(); ++i )
6675           avgNormal += eos._edges[ i ]->_normal;
6676       }
6677       double normSize = avgNormal.SquareModulus();
6678       if ( normSize < 1e-200 )
6679       {
6680         debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
6681         return false;
6682       }
6683       avgNormal /= Sqrt( normSize );
6684
6685       // compute new _LayerEdge::_cosin on EDGEs
6686       double avgCosin = 0;
6687       int     nbCosin = 0;
6688       gp_Vec inFaceDir;
6689       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
6690       {
6691         _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
6692         if ( ceCurve._adjFace.IsNull() )
6693           continue;
6694         for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
6695         {
6696           const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
6697           inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
6698           if ( isOK )
6699           {
6700             double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
6701             ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
6702             avgCosin += ceCurve._ledges[ iLE ]->_cosin;
6703             nbCosin++;
6704           }
6705         }
6706       }
6707       if ( nbCosin > 0 )
6708         avgCosin /= nbCosin;
6709
6710       // set _LayerEdge::_normal = avgNormal
6711       id2eos = convFace._subIdToEOS.begin();
6712       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6713       {
6714         _EdgesOnShape& eos = *(id2eos->second);
6715         if ( eos.ShapeType() != TopAbs_EDGE )
6716           for ( size_t i = 0; i < eos._edges.size(); ++i )
6717             eos._edges[ i ]->_cosin = avgCosin;
6718
6719         for ( size_t i = 0; i < eos._edges.size(); ++i )
6720         {
6721           eos._edges[ i ]->SetNormal( avgNormal );
6722           eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
6723         }
6724       }
6725     }
6726     else // if ( isSpherical )
6727     {
6728       // We suppose that centers of curvature at all points of the FACE
6729       // lie on some curve, let's call it "central curve". For all _LayerEdge's
6730       // having a common center of curvature we define the same new normal
6731       // as a sum of normals of _LayerEdge's on EDGEs among them.
6732
6733       // get all centers of curvature for each EDGE
6734
6735       helper.SetSubShape( convFace._face );
6736       _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
6737
6738       TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
6739       for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
6740       {
6741         const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
6742
6743         // set adjacent FACE
6744         centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
6745
6746         // get _LayerEdge's of the EDGE
6747         TGeomID edgeID = meshDS->ShapeToIndex( edge );
6748         _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
6749         if ( !eos || eos->_edges.empty() )
6750         {
6751           // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
6752           for ( int iV = 0; iV < 2; ++iV )
6753           {
6754             TopoDS_Vertex v = helper.IthVertex( iV, edge );
6755             TGeomID     vID = meshDS->ShapeToIndex( v );
6756             eos = data.GetShapeEdges( vID );
6757             vertexLEdges[ iV ] = eos->_edges[ 0 ];
6758           }
6759           edgeLEdge    = &vertexLEdges[0];
6760           edgeLEdgeEnd = edgeLEdge + 2;
6761
6762           centerCurves[ iE ]._adjFace.Nullify();
6763         }
6764         else
6765         {
6766           if ( ! eos->_toSmooth )
6767             data.SortOnEdge( edge, eos->_edges );
6768           edgeLEdge    = &eos->_edges[ 0 ];
6769           edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
6770           vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
6771           vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
6772
6773           if ( ! eos->_sWOL.IsNull() )
6774             centerCurves[ iE ]._adjFace.Nullify();
6775         }
6776
6777         // Get curvature centers
6778
6779         centersBox.Clear();
6780
6781         if ( edgeLEdge[0]->IsOnEdge() &&
6782              convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
6783         { // 1st VERTEX
6784           centerCurves[ iE ].Append( center, vertexLEdges[0] );
6785           centersBox.Add( center );
6786         }
6787         for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
6788           if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
6789           { // EDGE or VERTEXes
6790             centerCurves[ iE ].Append( center, *edgeLEdge );
6791             centersBox.Add( center );
6792           }
6793         if ( edgeLEdge[-1]->IsOnEdge() &&
6794              convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
6795         { // 2nd VERTEX
6796           centerCurves[ iE ].Append( center, vertexLEdges[1] );
6797           centersBox.Add( center );
6798         }
6799         centerCurves[ iE ]._isDegenerated =
6800           ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
6801
6802       } // loop on EDGES of convFace._face to set up data of centerCurves
6803
6804       // Compute new normals for _LayerEdge's on EDGEs
6805
6806       double avgCosin = 0;
6807       int     nbCosin = 0;
6808       gp_Vec inFaceDir;
6809       for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
6810       {
6811         _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
6812         if ( ceCurve._isDegenerated )
6813           continue;
6814         const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
6815         vector< gp_XYZ > &   newNormals = ceCurve._normals;
6816         for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
6817         {
6818           isOK = false;
6819           for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
6820           {
6821             if ( iE1 != iE2 )
6822               isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
6823           }
6824           if ( isOK && !ceCurve._adjFace.IsNull() )
6825           {
6826             // compute new _LayerEdge::_cosin
6827             const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
6828             inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
6829             if ( isOK )
6830             {
6831               double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
6832               ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
6833               avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
6834               nbCosin++;
6835             }
6836           }
6837         }
6838       }
6839       // set new normals to _LayerEdge's of NOT degenerated central curves
6840       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
6841       {
6842         if ( centerCurves[ iE ]._isDegenerated )
6843           continue;
6844         for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
6845         {
6846           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
6847           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
6848         }
6849       }
6850       // set new normals to _LayerEdge's of     degenerated central curves
6851       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
6852       {
6853         if ( !centerCurves[ iE ]._isDegenerated ||
6854              centerCurves[ iE ]._ledges.size() < 3 )
6855           continue;
6856         // new normal is an average of new normals at VERTEXes that
6857         // was computed on non-degenerated _CentralCurveOnEdge's
6858         gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
6859                            centerCurves[ iE ]._ledges.back ()->_normal );
6860         double sz = newNorm.Modulus();
6861         if ( sz < 1e-200 )
6862           continue;
6863         newNorm /= sz;
6864         double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
6865                             0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
6866         for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
6867         {
6868           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
6869           centerCurves[ iE ]._ledges[ iLE ]->_cosin   = newCosin;
6870           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
6871         }
6872       }
6873
6874       // Find new normals for _LayerEdge's based on FACE
6875
6876       if ( nbCosin > 0 )
6877         avgCosin /= nbCosin;
6878       const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
6879       map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
6880       if ( id2eos != convFace._subIdToEOS.end() )
6881       {
6882         int iE = 0;
6883         gp_XYZ newNorm;
6884         _EdgesOnShape& eos = * ( id2eos->second );
6885         for ( size_t i = 0; i < eos._edges.size(); ++i )
6886         {
6887           _LayerEdge* ledge = eos._edges[ i ];
6888           if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
6889             continue;
6890           for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
6891           {
6892             iE = iE % centerCurves.size();
6893             if ( centerCurves[ iE ]._isDegenerated )
6894               continue;
6895             newNorm.SetCoord( 0,0,0 );
6896             if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
6897             {
6898               ledge->SetNormal( newNorm );
6899               ledge->_cosin  = avgCosin;
6900               ledge->Set( _LayerEdge::NORMAL_UPDATED );
6901               break;
6902             }
6903           }
6904         }
6905       }
6906
6907     } // not a quasi-spherical FACE
6908
6909     // Update _LayerEdge's data according to a new normal
6910
6911     dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
6912                  <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
6913
6914     id2eos = convFace._subIdToEOS.begin();
6915     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6916     {
6917       _EdgesOnShape& eos = * ( id2eos->second );
6918       for ( size_t i = 0; i < eos._edges.size(); ++i )
6919       {
6920         _LayerEdge* & ledge = eos._edges[ i ];
6921         double len = ledge->_len;
6922         ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
6923         ledge->SetCosin( ledge->_cosin );
6924         ledge->SetNewLength( len, eos, helper );
6925       }
6926       if ( eos.ShapeType() != TopAbs_FACE )
6927         for ( size_t i = 0; i < eos._edges.size(); ++i )
6928         {
6929           _LayerEdge* ledge = eos._edges[ i ];
6930           for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
6931           {
6932             _LayerEdge* neibor = ledge->_neibors[iN];
6933             if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
6934             {
6935               neibor->Set( _LayerEdge::NEAR_BOUNDARY );
6936               neibor->Set( _LayerEdge::MOVED );
6937               neibor->SetSmooLen( neibor->_len );
6938             }
6939           }
6940         }
6941     } // loop on sub-shapes of convFace._face
6942
6943     // Find FACEs adjacent to convFace._face that got necessity to smooth
6944     // as a result of normals modification
6945
6946     set< _EdgesOnShape* > adjFacesToSmooth;
6947     for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
6948     {
6949       if ( centerCurves[ iE ]._adjFace.IsNull() ||
6950            centerCurves[ iE ]._adjFaceToSmooth )
6951         continue;
6952       for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
6953       {
6954         if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
6955         {
6956           adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
6957           break;
6958         }
6959       }
6960     }
6961     data.AddShapesToSmooth( adjFacesToSmooth );
6962
6963     dumpFunctionEnd();
6964
6965
6966   } // loop on data._convexFaces
6967
6968   return true;
6969 }
6970
6971 //================================================================================
6972 /*!
6973  * \brief Finds a center of curvature of a surface at a _LayerEdge
6974  */
6975 //================================================================================
6976
6977 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge*         ledge,
6978                                         BRepLProp_SLProps&  surfProp,
6979                                         SMESH_MesherHelper& helper,
6980                                         gp_Pnt &            center ) const
6981 {
6982   gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
6983   surfProp.SetParameters( uv.X(), uv.Y() );
6984   if ( !surfProp.IsCurvatureDefined() )
6985     return false;
6986
6987   const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
6988   double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
6989   double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
6990   if ( surfCurvatureMin > surfCurvatureMax )
6991     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
6992   else
6993     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
6994
6995   return true;
6996 }
6997
6998 //================================================================================
6999 /*!
7000  * \brief Check that prisms are not distorted
7001  */
7002 //================================================================================
7003
7004 bool _ConvexFace::CheckPrisms() const
7005 {
7006   double vol = 0;
7007   for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
7008   {
7009     const _LayerEdge* edge = _simplexTestEdges[i];
7010     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
7011     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
7012       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
7013       {
7014         debugMsg( "Bad simplex of _simplexTestEdges ("
7015                   << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
7016                   << " "<< edge->_simplices[j]._nPrev->GetID()
7017                   << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
7018         return false;
7019       }
7020   }
7021   return true;
7022 }
7023
7024 //================================================================================
7025 /*!
7026  * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
7027  *        stored in this _CentralCurveOnEdge.
7028  *  \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
7029  *  \param [in,out] newNormal - current normal at this point, to be redefined
7030  *  \return bool - true if succeeded.
7031  */
7032 //================================================================================
7033
7034 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
7035 {
7036   if ( this->_isDegenerated )
7037     return false;
7038
7039   // find two centers the given one lies between
7040
7041   for ( size_t i = 0, nb = _curvaCenters.size()-1;  i < nb;  ++i )
7042   {
7043     double sl2 = 1.001 * _segLength2[ i ];
7044
7045     double d1 = center.SquareDistance( _curvaCenters[ i ]);
7046     if ( d1 > sl2 )
7047       continue;
7048     
7049     double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
7050     if ( d2 > sl2 || d2 + d1 < 1e-100 )
7051       continue;
7052
7053     d1 = Sqrt( d1 );
7054     d2 = Sqrt( d2 );
7055     double r = d1 / ( d1 + d2 );
7056     gp_XYZ norm = (( 1. - r ) * _ledges[ i   ]->_normal +
7057                    (      r ) * _ledges[ i+1 ]->_normal );
7058     norm.Normalize();
7059
7060     newNormal += norm;
7061     double sz = newNormal.Modulus();
7062     if ( sz < 1e-200 )
7063       break;
7064     newNormal /= sz;
7065     return true;
7066   }
7067   return false;
7068 }
7069
7070 //================================================================================
7071 /*!
7072  * \brief Set shape members
7073  */
7074 //================================================================================
7075
7076 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge&  edge,
7077                                      const _ConvexFace&  convFace,
7078                                      _SolidData&         data,
7079                                      SMESH_MesherHelper& helper)
7080 {
7081   _edge = edge;
7082
7083   PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
7084   while ( const TopoDS_Shape* F = fIt->next())
7085     if ( !convFace._face.IsSame( *F ))
7086     {
7087       _adjFace = TopoDS::Face( *F );
7088       _adjFaceToSmooth = false;
7089       // _adjFace already in a smoothing queue ?
7090       if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
7091         _adjFaceToSmooth = eos->_toSmooth;
7092       break;
7093     }
7094 }
7095
7096 //================================================================================
7097 /*!
7098  * \brief Looks for intersection of it's last segment with faces
7099  *  \param distance - returns shortest distance from the last node to intersection
7100  */
7101 //================================================================================
7102
7103 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
7104                                    double &                 distance,
7105                                    const double&            epsilon,
7106                                    _EdgesOnShape&           eos,
7107                                    const SMDS_MeshElement** intFace)
7108 {
7109   vector< const SMDS_MeshElement* > suspectFaces;
7110   double segLen;
7111   gp_Ax1 lastSegment = LastSegment( segLen, eos );
7112   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
7113
7114   bool segmentIntersected = false;
7115   distance = Precision::Infinite();
7116   int iFace = -1; // intersected face
7117   for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
7118   {
7119     const SMDS_MeshElement* face = suspectFaces[j];
7120     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
7121          face->GetNodeIndex( _nodes[0]     ) >= 0 )
7122       continue; // face sharing _LayerEdge node
7123     const int nbNodes = face->NbCornerNodes();
7124     bool intFound = false;
7125     double dist;
7126     SMDS_MeshElement::iterator nIt = face->begin_nodes();
7127     if ( nbNodes == 3 )
7128     {
7129       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
7130     }
7131     else
7132     {
7133       const SMDS_MeshNode* tria[3];
7134       tria[0] = *nIt++;
7135       tria[1] = *nIt++;
7136       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
7137       {
7138         tria[2] = *nIt++;
7139         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
7140         tria[1] = tria[2];
7141       }
7142     }
7143     if ( intFound )
7144     {
7145       if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
7146         segmentIntersected = true;
7147       if ( distance > dist )
7148         distance = dist, iFace = j;
7149     }
7150   }
7151   if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
7152
7153   distance -= segLen;
7154
7155   if ( segmentIntersected )
7156   {
7157 #ifdef __myDEBUG
7158     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
7159     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
7160     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
7161          << ", intersection with face ("
7162          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
7163          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
7164          << ") distance = " << distance << endl;
7165 #endif
7166   }
7167
7168   return segmentIntersected;
7169 }
7170
7171 //================================================================================
7172 /*!
7173  * \brief Returns size and direction of the last segment
7174  */
7175 //================================================================================
7176
7177 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
7178 {
7179   // find two non-coincident positions
7180   gp_XYZ orig = _pos.back();
7181   gp_XYZ vec;
7182   int iPrev = _pos.size() - 2;
7183   //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
7184   const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
7185   while ( iPrev >= 0 )
7186   {
7187     vec = orig - _pos[iPrev];
7188     if ( vec.SquareModulus() > tol*tol )
7189       break;
7190     else
7191       iPrev--;
7192   }
7193
7194   // make gp_Ax1
7195   gp_Ax1 segDir;
7196   if ( iPrev < 0 )
7197   {
7198     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
7199     segDir.SetDirection( _normal );
7200     segLen = 0;
7201   }
7202   else
7203   {
7204     gp_Pnt pPrev = _pos[ iPrev ];
7205     if ( !eos._sWOL.IsNull() )
7206     {
7207       TopLoc_Location loc;
7208       if ( eos.SWOLType() == TopAbs_EDGE )
7209       {
7210         double f,l;
7211         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
7212         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
7213       }
7214       else
7215       {
7216         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
7217         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
7218       }
7219       vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
7220     }
7221     segDir.SetLocation( pPrev );
7222     segDir.SetDirection( vec );
7223     segLen = vec.Modulus();
7224   }
7225
7226   return segDir;
7227 }
7228
7229 //================================================================================
7230 /*!
7231  * \brief Return the last position of the target node on a FACE. 
7232  *  \param [in] F - the FACE this _LayerEdge is inflated along
7233  *  \return gp_XY - result UV
7234  */
7235 //================================================================================
7236
7237 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const
7238 {
7239   if ( F.IsSame( eos._sWOL )) // F is my FACE
7240     return gp_XY( _pos.back().X(), _pos.back().Y() );
7241
7242   if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
7243     return gp_XY( 1e100, 1e100 );
7244
7245   // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
7246   double f, l, u = _pos.back().X();
7247   Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
7248   if ( !C2d.IsNull() && f <= u && u <= l )
7249     return C2d->Value( u ).XY();
7250
7251   return gp_XY( 1e100, 1e100 );
7252 }
7253
7254 //================================================================================
7255 /*!
7256  * \brief Test intersection of the last segment with a given triangle
7257  *   using Moller-Trumbore algorithm
7258  * Intersection is detected if distance to intersection is less than _LayerEdge._len
7259  */
7260 //================================================================================
7261
7262 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
7263                                const gp_XYZ& vert0,
7264                                const gp_XYZ& vert1,
7265                                const gp_XYZ& vert2,
7266                                double&       t,
7267                                const double& EPSILON) const
7268 {
7269   const gp_Pnt& orig = lastSegment.Location();
7270   const gp_Dir& dir  = lastSegment.Direction();
7271
7272   /* calculate distance from vert0 to ray origin */
7273   gp_XYZ tvec = orig.XYZ() - vert0;
7274
7275   //if ( tvec * dir > EPSILON )
7276     // intersected face is at back side of the temporary face this _LayerEdge belongs to
7277     //return false;
7278
7279   gp_XYZ edge1 = vert1 - vert0;
7280   gp_XYZ edge2 = vert2 - vert0;
7281
7282   /* begin calculating determinant - also used to calculate U parameter */
7283   gp_XYZ pvec = dir.XYZ() ^ edge2;
7284
7285   /* if determinant is near zero, ray lies in plane of triangle */
7286   double det = edge1 * pvec;
7287
7288   const double ANGL_EPSILON = 1e-12;
7289   if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
7290     return false;
7291
7292   /* calculate U parameter and test bounds */
7293   double u = ( tvec * pvec ) / det;
7294   //if (u < 0.0 || u > 1.0)
7295   if ( u < -EPSILON || u > 1.0 + EPSILON )
7296     return false;
7297
7298   /* prepare to test V parameter */
7299   gp_XYZ qvec = tvec ^ edge1;
7300
7301   /* calculate V parameter and test bounds */
7302   double v = (dir.XYZ() * qvec) / det;
7303   //if ( v < 0.0 || u + v > 1.0 )
7304   if ( v < -EPSILON || u + v > 1.0 + EPSILON )
7305     return false;
7306
7307   /* calculate t, ray intersects triangle */
7308   t = (edge2 * qvec) / det;
7309
7310   //return true;
7311   return t > 0.;
7312 }
7313
7314 //================================================================================
7315 /*!
7316  * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
7317  *        neighbor _LayerEdge's by it's own inflation vector.
7318  *  \param [in] eov - EOS of the VERTEX
7319  *  \param [in] eos - EOS of the FACE
7320  *  \param [in] step - inflation step
7321  *  \param [in,out] badSmooEdges - not untangled _LayerEdge's
7322  */
7323 //================================================================================
7324
7325 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape*    eov,
7326                                    const _EdgesOnShape*    eos,
7327                                    const int               step,
7328                                    vector< _LayerEdge* > & badSmooEdges )
7329 {
7330   // check if any of _neibors is in badSmooEdges
7331   if ( std::find_first_of( _neibors.begin(), _neibors.end(),
7332                            badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
7333     return;
7334
7335   // get all edges to move
7336
7337   set< _LayerEdge* > edges;
7338
7339   // find a distance between _LayerEdge on VERTEX and its neighbors
7340   gp_XYZ  curPosV = SMESH_TNodeXYZ( _nodes.back() );
7341   double dist2 = 0;
7342   for ( size_t i = 0; i < _neibors.size(); ++i )
7343   {
7344     _LayerEdge* nEdge = _neibors[i];
7345     if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
7346     {
7347       edges.insert( nEdge );
7348       dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
7349     }
7350   }
7351   // add _LayerEdge's close to curPosV
7352   size_t nbE;
7353   do {
7354     nbE = edges.size();
7355     for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7356     {
7357       _LayerEdge* edgeF = *e;
7358       for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
7359       {
7360         _LayerEdge* nEdge = edgeF->_neibors[i];
7361         if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
7362              dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
7363           edges.insert( nEdge );
7364       }
7365     }
7366   }
7367   while ( nbE < edges.size() );
7368
7369   // move the target node of the got edges
7370
7371   gp_XYZ prevPosV = PrevPos();
7372   if ( eov->SWOLType() == TopAbs_EDGE )
7373   {
7374     BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
7375     prevPosV = curve.Value( prevPosV.X() ).XYZ();
7376   }
7377   else if ( eov->SWOLType() == TopAbs_FACE )
7378   {
7379     BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
7380     prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
7381   }
7382
7383   SMDS_FacePosition* fPos;
7384   //double r = 1. - Min( 0.9, step / 10. );
7385   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7386   {
7387     _LayerEdge*       edgeF = *e;
7388     const gp_XYZ     prevVF = edgeF->PrevPos() - prevPosV;
7389     const gp_XYZ    newPosF = curPosV + prevVF;
7390     SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7391     tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
7392     edgeF->_pos.back() = newPosF;
7393     dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
7394
7395     // set _curvature to make edgeF updated by putOnOffsetSurface()
7396     if ( !edgeF->_curvature )
7397       if (( fPos = dynamic_cast<SMDS_FacePosition*>( edgeF->_nodes[0]->GetPosition() )))
7398       {
7399         edgeF->_curvature = new _Curvature;
7400         edgeF->_curvature->_r = 0;
7401         edgeF->_curvature->_k = 0;
7402         edgeF->_curvature->_h2lenRatio = 0;
7403         edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
7404       }
7405   }
7406   // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
7407   //                      SMESH_TNodeXYZ( _nodes[0]    ));
7408   // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7409   // {
7410   //   _LayerEdge*      edgeF = *e;
7411   //   gp_XYZ          newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7412   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7413   //   tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7414   //   edgeF->_pos.back() = newPosF;
7415   //   dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
7416   // }
7417
7418   // smooth _LayerEdge's around moved nodes
7419   //size_t nbBadBefore = badSmooEdges.size();
7420   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7421   {
7422     _LayerEdge* edgeF = *e;
7423     for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
7424       if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
7425         //&& !edges.count( edgeF->_neibors[j] ))
7426       {
7427         _LayerEdge* edgeFN = edgeF->_neibors[j];
7428         edgeFN->Unset( SMOOTHED );
7429         int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
7430         // if ( nbBad > 0 )
7431         // {
7432         //   gp_XYZ         newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
7433         //   const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
7434         //   int        nbBadAfter = edgeFN->_simplices.size();
7435         //   double vol;
7436         //   for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
7437         //   {
7438         //     nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
7439         //   }
7440         //   if ( nbBadAfter <= nbBad )
7441         //   {
7442         //     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
7443         //     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7444         //     edgeF->_pos.back() = newPosF;
7445         //     dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7446         //     nbBad = nbBadAfter;
7447         //   }
7448         // }
7449         if ( nbBad > 0 )
7450           badSmooEdges.push_back( edgeFN );
7451       }
7452   }
7453     // move a bit not smoothed around moved nodes
7454   //   for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
7455   //   {
7456   //   _LayerEdge*      edgeF = badSmooEdges[i];
7457   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7458   //   gp_XYZ         newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7459   //   gp_XYZ         newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
7460   //   tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
7461   //   edgeF->_pos.back() = newPosF;
7462   //   dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7463   // }
7464 }
7465
7466 //================================================================================
7467 /*!
7468  * \brief Perform smooth of _LayerEdge's based on EDGE's
7469  *  \retval bool - true if node has been moved
7470  */
7471 //================================================================================
7472
7473 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
7474                               const TopoDS_Face&             F,
7475                               SMESH_MesherHelper&            helper)
7476 {
7477   ASSERT( IsOnEdge() );
7478
7479   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
7480   SMESH_TNodeXYZ oldPos( tgtNode );
7481   double dist01, distNewOld;
7482   
7483   SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
7484   SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
7485   dist01 = p0.Distance( _2neibors->tgtNode(1) );
7486
7487   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
7488   double lenDelta = 0;
7489   if ( _curvature )
7490   {
7491     //lenDelta = _curvature->lenDelta( _len );
7492     lenDelta = _curvature->lenDeltaByDist( dist01 );
7493     newPos.ChangeCoord() += _normal * lenDelta;
7494   }
7495
7496   distNewOld = newPos.Distance( oldPos );
7497
7498   if ( F.IsNull() )
7499   {
7500     if ( _2neibors->_plnNorm )
7501     {
7502       // put newPos on the plane defined by source node and _plnNorm
7503       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
7504       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
7505       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
7506     }
7507     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7508     _pos.back() = newPos.XYZ();
7509   }
7510   else
7511   {
7512     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7513     gp_XY uv( Precision::Infinite(), 0 );
7514     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
7515     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
7516
7517     newPos = surface->Value( uv );
7518     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7519   }
7520
7521   // commented for IPAL0052478
7522   // if ( _curvature && lenDelta < 0 )
7523   // {
7524   //   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
7525   //   _len -= prevPos.Distance( oldPos );
7526   //   _len += prevPos.Distance( newPos );
7527   // }
7528   bool moved = distNewOld > dist01/50;
7529   //if ( moved )
7530   dumpMove( tgtNode ); // debug
7531
7532   return moved;
7533 }
7534
7535 //================================================================================
7536 /*!
7537  * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
7538  */
7539 //================================================================================
7540
7541 void _LayerEdge::SmoothWoCheck()
7542 {
7543   if ( Is( DIFFICULT ))
7544     return;
7545
7546   bool moved = Is( SMOOTHED );
7547   for ( size_t i = 0; i < _neibors.size()  &&  !moved; ++i )
7548     moved = _neibors[i]->Is( SMOOTHED );
7549   if ( !moved )
7550     return;
7551
7552   gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7553
7554   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7555   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7556   _pos.back() = newPos;
7557
7558   dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
7559 }
7560
7561 //================================================================================
7562 /*!
7563  * \brief Checks validity of _neibors on EDGEs and VERTEXes
7564  */
7565 //================================================================================
7566
7567 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
7568 {
7569   if ( ! Is( NEAR_BOUNDARY ))
7570     return 0;
7571
7572   int nbBad = 0;
7573   double vol;
7574   for ( size_t iN = 0; iN < _neibors.size(); ++iN )
7575   {
7576     _LayerEdge* eN = _neibors[iN];
7577     if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
7578       continue;
7579     if ( needSmooth )
7580       *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) || eN->Is( _LayerEdge::NORMAL_UPDATED ));
7581
7582     SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
7583     SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
7584     for ( size_t i = 0; i < eN->_simplices.size(); ++i )
7585       if ( eN->_nodes.size() > 1 &&
7586            eN->_simplices[i].Includes( _nodes.back() ) &&
7587            !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
7588       {
7589         ++nbBad;
7590         if ( badNeibors )
7591         {
7592           badNeibors->push_back( eN );
7593           debugMsg("Bad boundary simplex ( "
7594                    << " "<< eN->_nodes[0]->GetID()
7595                    << " "<< eN->_nodes.back()->GetID()
7596                    << " "<< eN->_simplices[i]._nPrev->GetID()
7597                    << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
7598         }
7599         else
7600         {
7601           break;
7602         }
7603       }
7604   }
7605   return nbBad;
7606 }
7607
7608 //================================================================================
7609 /*!
7610  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
7611  *  \retval int - nb of bad simplices around this _LayerEdge
7612  */
7613 //================================================================================
7614
7615 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
7616 {
7617   if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
7618     return 0; // shape of simplices not changed
7619   if ( _simplices.size() < 2 )
7620     return 0; // _LayerEdge inflated along EDGE or FACE
7621
7622   if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
7623     findBest = true;
7624
7625   const gp_XYZ& curPos  = _pos.back();
7626   const gp_XYZ& prevPos = PrevCheckPos();
7627
7628   // quality metrics (orientation) of tetras around _tgtNode
7629   int nbOkBefore = 0;
7630   double vol, minVolBefore = 1e100;
7631   for ( size_t i = 0; i < _simplices.size(); ++i )
7632   {
7633     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
7634     minVolBefore = Min( minVolBefore, vol );
7635   }
7636   int nbBad = _simplices.size() - nbOkBefore;
7637
7638   bool bndNeedSmooth = false;
7639   if ( nbBad == 0 )
7640     nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
7641   if ( nbBad > 0 )
7642     Set( DISTORTED );
7643
7644   // evaluate min angle
7645   if ( nbBad == 0 && !findBest && !bndNeedSmooth )
7646   {
7647     size_t nbGoodAngles = _simplices.size();
7648     double angle;
7649     for ( size_t i = 0; i < _simplices.size(); ++i )
7650     {
7651       if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
7652         --nbGoodAngles;
7653     }
7654     if ( nbGoodAngles == _simplices.size() )
7655     {
7656       Unset( MOVED );
7657       return 0;
7658     }
7659   }
7660   if ( Is( ON_CONCAVE_FACE ))
7661     findBest = true;
7662
7663   if ( step % 2 == 0 )
7664     findBest = false;
7665
7666   if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
7667   {
7668     if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
7669       _smooFunction = _funs[ FUN_CENTROIDAL ];
7670     else
7671       _smooFunction = _funs[ FUN_LAPLACIAN ];
7672   }
7673
7674   // compute new position for the last _pos using different _funs
7675   gp_XYZ newPos;
7676   bool moved = false;
7677   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
7678   {
7679     if ( iFun < 0 )
7680       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7681     else if ( _funs[ iFun ] == _smooFunction )
7682       continue; // _smooFunction again
7683     else if ( step > 1 )
7684       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
7685     else
7686       break; // let "easy" functions improve elements around distorted ones
7687
7688     if ( _curvature )
7689     {
7690       double delta  = _curvature->lenDelta( _len );
7691       if ( delta > 0 )
7692         newPos += _normal * delta;
7693       else
7694       {
7695         double segLen = _normal * ( newPos - prevPos );
7696         if ( segLen + delta > 0 )
7697           newPos += _normal * delta;
7698       }
7699       // double segLenChange = _normal * ( curPos - newPos );
7700       // newPos += 0.5 * _normal * segLenChange;
7701     }
7702
7703     int nbOkAfter = 0;
7704     double minVolAfter = 1e100;
7705     for ( size_t i = 0; i < _simplices.size(); ++i )
7706     {
7707       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
7708       minVolAfter = Min( minVolAfter, vol );
7709     }
7710     // get worse?
7711     if ( nbOkAfter < nbOkBefore )
7712       continue;
7713
7714     if (( findBest ) &&
7715         ( nbOkAfter == nbOkBefore ) &&
7716         ( minVolAfter <= minVolBefore ))
7717       continue;
7718
7719     nbBad        = _simplices.size() - nbOkAfter;
7720     minVolBefore = minVolAfter;
7721     nbOkBefore   = nbOkAfter;
7722     moved        = true;
7723
7724     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7725     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7726     _pos.back() = newPos;
7727
7728     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
7729                   << (nbBad ? " --BAD" : ""));
7730
7731     if ( iFun > -1 )
7732     {
7733       continue; // look for a better function
7734     }
7735
7736     if ( !findBest )
7737       break;
7738
7739   } // loop on smoothing functions
7740
7741   if ( moved ) // notify _neibors
7742   {
7743     Set( SMOOTHED );
7744     for ( size_t i = 0; i < _neibors.size(); ++i )
7745       if ( !_neibors[i]->Is( MOVED ))
7746       {
7747         _neibors[i]->Set( MOVED );
7748         toSmooth.push_back( _neibors[i] );
7749       }
7750   }
7751
7752   return nbBad;
7753 }
7754
7755 //================================================================================
7756 /*!
7757  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
7758  *  \retval int - nb of bad simplices around this _LayerEdge
7759  */
7760 //================================================================================
7761
7762 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
7763 {
7764   if ( !_smooFunction )
7765     return 0; // _LayerEdge inflated along EDGE or FACE
7766   if ( Is( BLOCKED ))
7767     return 0; // not inflated
7768
7769   const gp_XYZ& curPos  = _pos.back();
7770   const gp_XYZ& prevPos = PrevCheckPos();
7771
7772   // quality metrics (orientation) of tetras around _tgtNode
7773   int nbOkBefore = 0;
7774   double vol, minVolBefore = 1e100;
7775   for ( size_t i = 0; i < _simplices.size(); ++i )
7776   {
7777     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
7778     minVolBefore = Min( minVolBefore, vol );
7779   }
7780   int nbBad = _simplices.size() - nbOkBefore;
7781
7782   if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
7783   {
7784     if      ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
7785       _smooFunction = _funs[ FUN_LAPLACIAN ];
7786     else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
7787       _smooFunction = _funs[ FUN_CENTROIDAL ];
7788   }
7789
7790   // compute new position for the last _pos using different _funs
7791   gp_XYZ newPos;
7792   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
7793   {
7794     if ( iFun < 0 )
7795       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7796     else if ( _funs[ iFun ] == _smooFunction )
7797       continue; // _smooFunction again
7798     else if ( step > 1 )
7799       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
7800     else
7801       break; // let "easy" functions improve elements around distorted ones
7802
7803     if ( _curvature )
7804     {
7805       double delta  = _curvature->lenDelta( _len );
7806       if ( delta > 0 )
7807         newPos += _normal * delta;
7808       else
7809       {
7810         double segLen = _normal * ( newPos - prevPos );
7811         if ( segLen + delta > 0 )
7812           newPos += _normal * delta;
7813       }
7814       // double segLenChange = _normal * ( curPos - newPos );
7815       // newPos += 0.5 * _normal * segLenChange;
7816     }
7817
7818     int nbOkAfter = 0;
7819     double minVolAfter = 1e100;
7820     for ( size_t i = 0; i < _simplices.size(); ++i )
7821     {
7822       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
7823       minVolAfter = Min( minVolAfter, vol );
7824     }
7825     // get worse?
7826     if ( nbOkAfter < nbOkBefore )
7827       continue;
7828     if (( isConcaveFace || findBest ) &&
7829         ( nbOkAfter == nbOkBefore ) &&
7830         ( minVolAfter <= minVolBefore )
7831         )
7832       continue;
7833
7834     nbBad        = _simplices.size() - nbOkAfter;
7835     minVolBefore = minVolAfter;
7836     nbOkBefore   = nbOkAfter;
7837
7838     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7839     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7840     _pos.back() = newPos;
7841
7842     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
7843                   << ( nbBad ? "--BAD" : ""));
7844
7845     // commented for IPAL0052478
7846     // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
7847     // _len += prevPos.Distance(newPos);
7848
7849     if ( iFun > -1 ) // findBest || the chosen _fun makes worse
7850     {
7851       //_smooFunction = _funs[ iFun ];
7852       // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
7853       // << "\t nbBad: " << _simplices.size() - nbOkAfter
7854       // << " minVol: " << minVolAfter
7855       // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
7856       // << endl;
7857       continue; // look for a better function
7858     }
7859
7860     if ( !findBest )
7861       break;
7862
7863   } // loop on smoothing functions
7864
7865   return nbBad;
7866 }
7867
7868 //================================================================================
7869 /*!
7870  * \brief Chooses a smoothing technic giving a position most close to an initial one.
7871  *        For a correct result, _simplices must contain nodes lying on geometry.
7872  */
7873 //================================================================================
7874
7875 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
7876                                      const TNode2Edge&     n2eMap)
7877 {
7878   if ( _smooFunction ) return;
7879
7880   // use smoothNefPolygon() near concaveVertices
7881   if ( !concaveVertices.empty() )
7882   {
7883     _smooFunction = _funs[ FUN_CENTROIDAL ];
7884
7885     Set( ON_CONCAVE_FACE );
7886
7887     for ( size_t i = 0; i < _simplices.size(); ++i )
7888     {
7889       if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
7890       {
7891         _smooFunction = _funs[ FUN_NEFPOLY ];
7892
7893         // set FUN_CENTROIDAL to neighbor edges
7894         for ( i = 0; i < _neibors.size(); ++i )
7895         {
7896           if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
7897           {
7898             _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
7899           }
7900         }
7901         return;
7902       }
7903     }
7904
7905     // // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
7906     // // where the nodes are smoothed too far along a sphere thus creating
7907     // // inverted _simplices
7908     // double dist[theNbSmooFuns];
7909     // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
7910     // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
7911
7912     // double minDist = Precision::Infinite();
7913     // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
7914     // for ( int i = 0; i < FUN_NEFPOLY; ++i )
7915     // {
7916     //   gp_Pnt newP = (this->*_funs[i])();
7917     //   dist[i] = p.SquareDistance( newP );
7918     //   if ( dist[i]*coef[i] < minDist )
7919     //   {
7920     //     _smooFunction = _funs[i];
7921     //     minDist = dist[i]*coef[i];
7922     //   }
7923     // }
7924   }
7925   else
7926   {
7927     _smooFunction = _funs[ FUN_LAPLACIAN ];
7928   }
7929   // int minDim = 3;
7930   // for ( size_t i = 0; i < _simplices.size(); ++i )
7931   //   minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
7932   // if ( minDim == 0 )
7933   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
7934   // else if ( minDim == 1 )
7935   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
7936
7937
7938   // int iMin;
7939   // for ( int i = 0; i < FUN_NB; ++i )
7940   // {
7941   //   //cout << dist[i] << " ";
7942   //   if ( _smooFunction == _funs[i] ) {
7943   //     iMin = i;
7944   //     //debugMsg( fNames[i] );
7945   //     break;
7946   //   }
7947   // }
7948   // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
7949 }
7950
7951 //================================================================================
7952 /*!
7953  * \brief Returns a name of _SmooFunction
7954  */
7955 //================================================================================
7956
7957 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
7958 {
7959   if ( !fun )
7960     fun = _smooFunction;
7961   for ( int i = 0; i < theNbSmooFuns; ++i )
7962     if ( fun == _funs[i] )
7963       return i;
7964
7965   return theNbSmooFuns;
7966 }
7967
7968 //================================================================================
7969 /*!
7970  * \brief Computes a new node position using Laplacian smoothing
7971  */
7972 //================================================================================
7973
7974 gp_XYZ _LayerEdge::smoothLaplacian()
7975 {
7976   gp_XYZ newPos (0,0,0);
7977   for ( size_t i = 0; i < _simplices.size(); ++i )
7978     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
7979   newPos /= _simplices.size();
7980
7981   return newPos;
7982 }
7983
7984 //================================================================================
7985 /*!
7986  * \brief Computes a new node position using angular-based smoothing
7987  */
7988 //================================================================================
7989
7990 gp_XYZ _LayerEdge::smoothAngular()
7991 {
7992   vector< gp_Vec > edgeDir;  edgeDir. reserve( _simplices.size() + 1 );
7993   vector< double > edgeSize; edgeSize.reserve( _simplices.size()     );
7994   vector< gp_XYZ > points;   points.  reserve( _simplices.size() + 1 );
7995
7996   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
7997   gp_XYZ pN( 0,0,0 );
7998   for ( size_t i = 0; i < _simplices.size(); ++i )
7999   {
8000     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8001     edgeDir.push_back( p - pPrev );
8002     edgeSize.push_back( edgeDir.back().Magnitude() );
8003     if ( edgeSize.back() < numeric_limits<double>::min() )
8004     {
8005       edgeDir.pop_back();
8006       edgeSize.pop_back();
8007     }
8008     else
8009     {
8010       edgeDir.back() /= edgeSize.back();
8011       points.push_back( p );
8012       pN += p;
8013     }
8014     pPrev = p;
8015   }
8016   edgeDir.push_back ( edgeDir[0] );
8017   edgeSize.push_back( edgeSize[0] );
8018   pN /= points.size();
8019
8020   gp_XYZ newPos(0,0,0);
8021   double sumSize = 0;
8022   for ( size_t i = 0; i < points.size(); ++i )
8023   {
8024     gp_Vec toN    = pN - points[i];
8025     double toNLen = toN.Magnitude();
8026     if ( toNLen < numeric_limits<double>::min() )
8027     {
8028       newPos += pN;
8029       continue;
8030     }
8031     gp_Vec bisec    = edgeDir[i] + edgeDir[i+1];
8032     double bisecLen = bisec.SquareMagnitude();
8033     if ( bisecLen < numeric_limits<double>::min() )
8034     {
8035       gp_Vec norm = edgeDir[i] ^ toN;
8036       bisec = norm ^ edgeDir[i];
8037       bisecLen = bisec.SquareMagnitude();
8038     }
8039     bisecLen = Sqrt( bisecLen );
8040     bisec /= bisecLen;
8041
8042 #if 1
8043     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
8044     sumSize += bisecLen;
8045 #else
8046     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
8047     sumSize += ( edgeSize[i] + edgeSize[i+1] );
8048 #endif
8049     newPos += pNew;
8050   }
8051   newPos /= sumSize;
8052
8053   // project newPos to an average plane
8054
8055   gp_XYZ norm(0,0,0); // plane normal
8056   points.push_back( points[0] );
8057   for ( size_t i = 1; i < points.size(); ++i )
8058   {
8059     gp_XYZ vec1 = points[ i-1 ] - pN;
8060     gp_XYZ vec2 = points[ i   ] - pN;
8061     gp_XYZ cross = vec1 ^ vec2;
8062     try {
8063       cross.Normalize();
8064       if ( cross * norm < numeric_limits<double>::min() )
8065         norm += cross.Reversed();
8066       else
8067         norm += cross;
8068     }
8069     catch (Standard_Failure) { // if |cross| == 0.
8070     }
8071   }
8072   gp_XYZ vec = newPos - pN;
8073   double r   = ( norm * vec ) / norm.SquareModulus();  // param [0,1] on norm
8074   newPos     = newPos - r * norm;
8075
8076   return newPos;
8077 }
8078
8079 //================================================================================
8080 /*!
8081  * \brief Computes a new node position using weigthed node positions
8082  */
8083 //================================================================================
8084
8085 gp_XYZ _LayerEdge::smoothLengthWeighted()
8086 {
8087   vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
8088   vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
8089
8090   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8091   for ( size_t i = 0; i < _simplices.size(); ++i )
8092   {
8093     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8094     edgeSize.push_back( ( p - pPrev ).Modulus() );
8095     if ( edgeSize.back() < numeric_limits<double>::min() )
8096     {
8097       edgeSize.pop_back();
8098     }
8099     else
8100     {
8101       points.push_back( p );
8102     }
8103     pPrev = p;
8104   }
8105   edgeSize.push_back( edgeSize[0] );
8106
8107   gp_XYZ newPos(0,0,0);
8108   double sumSize = 0;
8109   for ( size_t i = 0; i < points.size(); ++i )
8110   {
8111     newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
8112     sumSize += edgeSize[i] + edgeSize[i+1];
8113   }
8114   newPos /= sumSize;
8115   return newPos;
8116 }
8117
8118 //================================================================================
8119 /*!
8120  * \brief Computes a new node position using angular-based smoothing
8121  */
8122 //================================================================================
8123
8124 gp_XYZ _LayerEdge::smoothCentroidal()
8125 {
8126   gp_XYZ newPos(0,0,0);
8127   gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
8128   double sumSize = 0;
8129   for ( size_t i = 0; i < _simplices.size(); ++i )
8130   {
8131     gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8132     gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
8133     gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
8134     double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
8135
8136     sumSize += size;
8137     newPos += gc * size;
8138   }
8139   newPos /= sumSize;
8140
8141   return newPos;
8142 }
8143
8144 //================================================================================
8145 /*!
8146  * \brief Computes a new node position located inside a Nef polygon
8147  */
8148 //================================================================================
8149
8150 gp_XYZ _LayerEdge::smoothNefPolygon()
8151 #ifdef OLD_NEF_POLYGON
8152 {
8153   gp_XYZ newPos(0,0,0);
8154
8155   // get a plane to seach a solution on
8156
8157   vector< gp_XYZ > vecs( _simplices.size() + 1 );
8158   size_t i;
8159   const double tol = numeric_limits<double>::min();
8160   gp_XYZ center(0,0,0);
8161   for ( i = 0; i < _simplices.size(); ++i )
8162   {
8163     vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
8164                 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
8165     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8166   }
8167   vecs.back() = vecs[0];
8168   center /= _simplices.size();
8169
8170   gp_XYZ zAxis(0,0,0);
8171   for ( i = 0; i < _simplices.size(); ++i )
8172     zAxis += vecs[i] ^ vecs[i+1];
8173
8174   gp_XYZ yAxis;
8175   for ( i = 0; i < _simplices.size(); ++i )
8176   {
8177     yAxis = vecs[i];
8178     if ( yAxis.SquareModulus() > tol )
8179       break;
8180   }
8181   gp_XYZ xAxis = yAxis ^ zAxis;
8182   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8183   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8184   //                             p0.Distance( _simplices[2]._nPrev ));
8185   // gp_XYZ center = smoothLaplacian();
8186   // gp_XYZ xAxis, yAxis, zAxis;
8187   // for ( i = 0; i < _simplices.size(); ++i )
8188   // {
8189   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8190   //   if ( xAxis.SquareModulus() > tol*tol )
8191   //     break;
8192   // }
8193   // for ( i = 1; i < _simplices.size(); ++i )
8194   // {
8195   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8196   //   zAxis = xAxis ^ yAxis;
8197   //   if ( zAxis.SquareModulus() > tol*tol )
8198   //     break;
8199   // }
8200   // if ( i == _simplices.size() ) return newPos;
8201
8202   yAxis = zAxis ^ xAxis;
8203   xAxis /= xAxis.Modulus();
8204   yAxis /= yAxis.Modulus();
8205
8206   // get half-planes of _simplices
8207
8208   vector< _halfPlane > halfPlns( _simplices.size() );
8209   int nbHP = 0;
8210   for ( size_t i = 0; i < _simplices.size(); ++i )
8211   {
8212     gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8213     gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
8214     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
8215     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
8216     gp_XY  vec12 = p2 - p1;
8217     double dist12 = vec12.Modulus();
8218     if ( dist12 < tol )
8219       continue;
8220     vec12 /= dist12;
8221     halfPlns[ nbHP ]._pos = p1;
8222     halfPlns[ nbHP ]._dir = vec12;
8223     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8224     ++nbHP;
8225   }
8226
8227   // intersect boundaries of half-planes, define state of intersection points
8228   // in relation to all half-planes and calculate internal point of a 2D polygon
8229
8230   double sumLen = 0;
8231   gp_XY newPos2D (0,0);
8232
8233   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8234   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8235   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8236
8237   vector< vector< TIntPntState > > allIntPnts( nbHP );
8238   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8239   {
8240     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8241     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8242
8243     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8244     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8245
8246     int nbNotOut = 0;
8247     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8248
8249     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8250     {
8251       if ( iHP1 == iHP2 ) continue;
8252
8253       TIntPntState & ips1 = intPnts1[ iHP2 ];
8254       if ( ips1.second == UNDEF )
8255       {
8256         // find an intersection point of boundaries of iHP1 and iHP2
8257
8258         if ( iHP2 == iPrev ) // intersection with neighbors is known
8259           ips1.first = halfPlns[ iHP1 ]._pos;
8260         else if ( iHP2 == iNext )
8261           ips1.first = halfPlns[ iHP2 ]._pos;
8262         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8263           ips1.second = NO_INT;
8264
8265         // classify the found intersection point
8266         if ( ips1.second != NO_INT )
8267         {
8268           ips1.second = NOT_OUT;
8269           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8270             if ( i != iHP1 && i != iHP2 &&
8271                  halfPlns[ i ].IsOut( ips1.first, tol ))
8272               ips1.second = IS_OUT;
8273         }
8274         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8275         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8276         TIntPntState & ips2 = intPnts2[ iHP1 ];
8277         ips2 = ips1;
8278       }
8279       if ( ips1.second == NOT_OUT )
8280       {
8281         ++nbNotOut;
8282         segEnds[ bool(segEnds[0]) ] = & ips1.first;
8283       }
8284     }
8285
8286     // find a NOT_OUT segment of boundary which is located between
8287     // two NOT_OUT int points
8288
8289     if ( nbNotOut < 2 )
8290       continue; // no such a segment
8291
8292     if ( nbNotOut > 2 )
8293     {
8294       // sort points along the boundary
8295       map< double, TIntPntState* > ipsByParam;
8296       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8297       {
8298         TIntPntState & ips1 = intPnts1[ iHP2 ];
8299         if ( ips1.second != NO_INT )
8300         {
8301           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
8302           double param = op * halfPlns[ iHP1 ]._dir;
8303           ipsByParam.insert( make_pair( param, & ips1 ));
8304         }
8305       }
8306       // look for two neighboring NOT_OUT points
8307       nbNotOut = 0;
8308       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8309       for ( ; u2ips != ipsByParam.end(); ++u2ips )
8310       {
8311         TIntPntState & ips1 = *(u2ips->second);
8312         if ( ips1.second == NOT_OUT )
8313           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8314         else if ( nbNotOut >= 2 )
8315           break;
8316         else
8317           nbNotOut = 0;
8318       }
8319     }
8320
8321     if ( nbNotOut >= 2 )
8322     {
8323       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8324       sumLen += len;
8325
8326       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8327     }
8328   }
8329
8330   if ( sumLen > 0 )
8331   {
8332     newPos2D /= sumLen;
8333     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8334   }
8335   else
8336   {
8337     newPos = center;
8338   }
8339
8340   return newPos;
8341 }
8342 #else // OLD_NEF_POLYGON
8343 { ////////////////////////////////// NEW
8344   gp_XYZ newPos(0,0,0);
8345
8346   // get a plane to seach a solution on
8347
8348   size_t i;
8349   gp_XYZ center(0,0,0);
8350   for ( i = 0; i < _simplices.size(); ++i )
8351     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8352   center /= _simplices.size();
8353
8354   vector< gp_XYZ > vecs( _simplices.size() + 1 );
8355   for ( i = 0; i < _simplices.size(); ++i )
8356     vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8357   vecs.back() = vecs[0];
8358
8359   const double tol = numeric_limits<double>::min();
8360   gp_XYZ zAxis(0,0,0);
8361   for ( i = 0; i < _simplices.size(); ++i )
8362   {
8363     gp_XYZ cross = vecs[i] ^ vecs[i+1];
8364     try {
8365       cross.Normalize();
8366       if ( cross * zAxis < tol )
8367         zAxis += cross.Reversed();
8368       else
8369         zAxis += cross;
8370     }
8371     catch (Standard_Failure) { // if |cross| == 0.
8372     }
8373   }
8374
8375   gp_XYZ yAxis;
8376   for ( i = 0; i < _simplices.size(); ++i )
8377   {
8378     yAxis = vecs[i];
8379     if ( yAxis.SquareModulus() > tol )
8380       break;
8381   }
8382   gp_XYZ xAxis = yAxis ^ zAxis;
8383   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8384   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8385   //                             p0.Distance( _simplices[2]._nPrev ));
8386   // gp_XYZ center = smoothLaplacian();
8387   // gp_XYZ xAxis, yAxis, zAxis;
8388   // for ( i = 0; i < _simplices.size(); ++i )
8389   // {
8390   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8391   //   if ( xAxis.SquareModulus() > tol*tol )
8392   //     break;
8393   // }
8394   // for ( i = 1; i < _simplices.size(); ++i )
8395   // {
8396   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8397   //   zAxis = xAxis ^ yAxis;
8398   //   if ( zAxis.SquareModulus() > tol*tol )
8399   //     break;
8400   // }
8401   // if ( i == _simplices.size() ) return newPos;
8402
8403   yAxis = zAxis ^ xAxis;
8404   xAxis /= xAxis.Modulus();
8405   yAxis /= yAxis.Modulus();
8406
8407   // get half-planes of _simplices
8408
8409   vector< _halfPlane > halfPlns( _simplices.size() );
8410   int nbHP = 0;
8411   for ( size_t i = 0; i < _simplices.size(); ++i )
8412   {
8413     const gp_XYZ& OP1 = vecs[ i   ];
8414     const gp_XYZ& OP2 = vecs[ i+1 ];
8415     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
8416     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
8417     gp_XY  vec12 = p2 - p1;
8418     double dist12 = vec12.Modulus();
8419     if ( dist12 < tol )
8420       continue;
8421     vec12 /= dist12;
8422     halfPlns[ nbHP ]._pos = p1;
8423     halfPlns[ nbHP ]._dir = vec12;
8424     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8425     ++nbHP;
8426   }
8427
8428   // intersect boundaries of half-planes, define state of intersection points
8429   // in relation to all half-planes and calculate internal point of a 2D polygon
8430
8431   double sumLen = 0;
8432   gp_XY newPos2D (0,0);
8433
8434   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8435   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8436   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8437
8438   vector< vector< TIntPntState > > allIntPnts( nbHP );
8439   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8440   {
8441     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8442     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8443
8444     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8445     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8446
8447     int nbNotOut = 0;
8448     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8449
8450     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8451     {
8452       if ( iHP1 == iHP2 ) continue;
8453
8454       TIntPntState & ips1 = intPnts1[ iHP2 ];
8455       if ( ips1.second == UNDEF )
8456       {
8457         // find an intersection point of boundaries of iHP1 and iHP2
8458
8459         if ( iHP2 == iPrev ) // intersection with neighbors is known
8460           ips1.first = halfPlns[ iHP1 ]._pos;
8461         else if ( iHP2 == iNext )
8462           ips1.first = halfPlns[ iHP2 ]._pos;
8463         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8464           ips1.second = NO_INT;
8465
8466         // classify the found intersection point
8467         if ( ips1.second != NO_INT )
8468         {
8469           ips1.second = NOT_OUT;
8470           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8471             if ( i != iHP1 && i != iHP2 &&
8472                  halfPlns[ i ].IsOut( ips1.first, tol ))
8473               ips1.second = IS_OUT;
8474         }
8475         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8476         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8477         TIntPntState & ips2 = intPnts2[ iHP1 ];
8478         ips2 = ips1;
8479       }
8480       if ( ips1.second == NOT_OUT )
8481       {
8482         ++nbNotOut;
8483         segEnds[ bool(segEnds[0]) ] = & ips1.first;
8484       }
8485     }
8486
8487     // find a NOT_OUT segment of boundary which is located between
8488     // two NOT_OUT int points
8489
8490     if ( nbNotOut < 2 )
8491       continue; // no such a segment
8492
8493     if ( nbNotOut > 2 )
8494     {
8495       // sort points along the boundary
8496       map< double, TIntPntState* > ipsByParam;
8497       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8498       {
8499         TIntPntState & ips1 = intPnts1[ iHP2 ];
8500         if ( ips1.second != NO_INT )
8501         {
8502           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
8503           double param = op * halfPlns[ iHP1 ]._dir;
8504           ipsByParam.insert( make_pair( param, & ips1 ));
8505         }
8506       }
8507       // look for two neighboring NOT_OUT points
8508       nbNotOut = 0;
8509       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8510       for ( ; u2ips != ipsByParam.end(); ++u2ips )
8511       {
8512         TIntPntState & ips1 = *(u2ips->second);
8513         if ( ips1.second == NOT_OUT )
8514           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8515         else if ( nbNotOut >= 2 )
8516           break;
8517         else
8518           nbNotOut = 0;
8519       }
8520     }
8521
8522     if ( nbNotOut >= 2 )
8523     {
8524       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8525       sumLen += len;
8526
8527       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8528     }
8529   }
8530
8531   if ( sumLen > 0 )
8532   {
8533     newPos2D /= sumLen;
8534     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8535   }
8536   else
8537   {
8538     newPos = center;
8539   }
8540
8541   return newPos;
8542 }
8543 #endif // OLD_NEF_POLYGON
8544
8545 //================================================================================
8546 /*!
8547  * \brief Add a new segment to _LayerEdge during inflation
8548  */
8549 //================================================================================
8550
8551 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
8552 {
8553   if ( Is( BLOCKED ))
8554     return;
8555
8556   if ( len > _maxLen )
8557   {
8558     len = _maxLen;
8559     Block( eos.GetData() );
8560   }
8561   const double lenDelta = len - _len;
8562   if ( lenDelta < len * 1e-3  )
8563   {
8564     Block( eos.GetData() );
8565     return;
8566   }
8567
8568   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
8569   gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
8570   gp_XYZ newXYZ;
8571   if ( eos._hyp.IsOffsetMethod() )
8572   {
8573     newXYZ = oldXYZ;
8574     gp_Vec faceNorm;
8575     SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
8576     while ( faceIt->more() )
8577     {
8578       const SMDS_MeshElement* face = faceIt->next();
8579       if ( !eos.GetNormal( face, faceNorm ))
8580         continue;
8581
8582       // translate plane of a face
8583       gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
8584
8585       // find point of intersection of the face plane located at baryCenter
8586       // and _normal located at newXYZ
8587       double d    = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
8588       double dot  = ( faceNorm.XYZ() * _normal );
8589       if ( dot < std::numeric_limits<double>::min() )
8590         dot = lenDelta * 1e-3;
8591       double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
8592       newXYZ += step * _normal;
8593     }
8594   }
8595   else
8596   {
8597     newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
8598   }
8599
8600   n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
8601   _pos.push_back( newXYZ );
8602
8603   if ( !eos._sWOL.IsNull() )
8604   {
8605     double distXYZ[4];
8606     bool uvOK = false;
8607     if ( eos.SWOLType() == TopAbs_EDGE )
8608     {
8609       double u = Precision::Infinite(); // to force projection w/o distance check
8610       uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
8611                                 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8612       _pos.back().SetCoord( u, 0, 0 );
8613       if ( _nodes.size() > 1 && uvOK )
8614       {
8615         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
8616         pos->SetUParameter( u );
8617       }
8618     }
8619     else //  TopAbs_FACE
8620     {
8621       gp_XY uv( Precision::Infinite(), 0 );
8622       uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
8623                                  /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8624       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8625       if ( _nodes.size() > 1 && uvOK )
8626       {
8627         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
8628         pos->SetUParameter( uv.X() );
8629         pos->SetVParameter( uv.Y() );
8630       }
8631     }
8632     if ( uvOK )
8633     {
8634       n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
8635     }
8636     else
8637     {
8638       n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
8639       _pos.pop_back();
8640       Block( eos.GetData() );
8641       return;
8642     }
8643   }
8644
8645   _len = len;
8646
8647   // notify _neibors
8648   if ( eos.ShapeType() != TopAbs_FACE )
8649   {
8650     for ( size_t i = 0; i < _neibors.size(); ++i )
8651       //if (  _len > _neibors[i]->GetSmooLen() )
8652         _neibors[i]->Set( MOVED );
8653
8654     Set( MOVED );
8655   }
8656   dumpMove( n ); //debug
8657 }
8658
8659 //================================================================================
8660 /*!
8661  * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
8662  */
8663 //================================================================================
8664
8665 void _LayerEdge::Block( _SolidData& data )
8666 {
8667   if ( Is( BLOCKED )) return;
8668   Set( BLOCKED );
8669
8670   _maxLen = _len;
8671   std::queue<_LayerEdge*> queue;
8672   queue.push( this );
8673
8674   gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
8675   while ( !queue.empty() )
8676   {
8677     _LayerEdge* edge = queue.front(); queue.pop();
8678     pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
8679     pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
8680     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
8681     {
8682       _LayerEdge* neibor = edge->_neibors[iN];
8683       if ( neibor->Is( BLOCKED ) ||
8684            neibor->_maxLen < edge->_maxLen )
8685         continue;
8686       pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
8687       pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
8688       double minDist = pSrc.SquareDistance( pSrcN );
8689       minDist   = Min( pTgt.SquareDistance( pTgtN ), minDist );
8690       minDist   = Min( pSrc.SquareDistance( pTgtN ), minDist );
8691       minDist   = Min( pTgt.SquareDistance( pSrcN ), minDist );
8692       double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
8693       if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() )
8694       {
8695         newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
8696       }
8697       if ( neibor->_maxLen > newMaxLen )
8698       {
8699         neibor->_maxLen = newMaxLen;
8700         if ( neibor->_maxLen < neibor->_len )
8701         {
8702           _EdgesOnShape* eos = data.GetShapeEdges( neibor );
8703           while ( neibor->_len > neibor->_maxLen &&
8704                   neibor->NbSteps() > 1 )
8705             neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
8706           neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
8707         }
8708         queue.push( neibor );
8709       }
8710     }
8711   }
8712 }
8713
8714 //================================================================================
8715 /*!
8716  * \brief Remove last inflation step
8717  */
8718 //================================================================================
8719
8720 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
8721 {
8722   if ( _pos.size() > curStep && _nodes.size() > 1 )
8723   {
8724     _pos.resize( curStep );
8725
8726     gp_Pnt      nXYZ = _pos.back();
8727     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
8728     SMESH_TNodeXYZ curXYZ( n );
8729     if ( !eos._sWOL.IsNull() )
8730     {
8731       TopLoc_Location loc;
8732       if ( eos.SWOLType() == TopAbs_EDGE )
8733       {
8734         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
8735         pos->SetUParameter( nXYZ.X() );
8736         double f,l;
8737         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
8738         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
8739       }
8740       else
8741       {
8742         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
8743         pos->SetUParameter( nXYZ.X() );
8744         pos->SetVParameter( nXYZ.Y() );
8745         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
8746         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
8747       }
8748     }
8749     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
8750     dumpMove( n );
8751
8752     if ( restoreLength )
8753     {
8754       _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
8755     }
8756   }
8757 }
8758
8759 //================================================================================
8760 /*!
8761  * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
8762  */
8763 //================================================================================
8764
8765 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
8766 {
8767   //return;
8768   if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
8769     return;
8770
8771   // find the 1st smoothed _pos
8772   int iSmoothed = 0;
8773   for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
8774   {
8775     double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
8776     if ( normDist > tol * tol )
8777       iSmoothed = i;
8778   }
8779   if ( !iSmoothed ) return;
8780
8781   if ( 1 || Is( DISTORTED ))
8782   {
8783     // if ( segLen[ iSmoothed ] / segLen.back() < 0.5 )
8784     //   return;
8785     gp_XYZ normal = _normal;
8786     if ( Is( NORMAL_UPDATED ))
8787       for ( size_t i = 1; i < _pos.size(); ++i )
8788       {
8789         normal = _pos[i] - _pos[0];
8790         double size = normal.Modulus();
8791         if ( size > RealSmall() )
8792         {
8793           normal /= size;
8794           break;
8795         }
8796       }
8797     const double r = 0.2;
8798     for ( int iter = 0; iter < 3; ++iter )
8799     {
8800       double minDot = 1;
8801       for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
8802       {
8803         gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
8804         gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
8805         _pos[i] = newPos;
8806         double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
8807         double newLen = ( 1-r ) * midLen + r * segLen[i];
8808         const_cast< double& >( segLen[i] ) = newLen;
8809         // check angle between normal and (_pos[i+1], _pos[i] )
8810         gp_XYZ posDir = _pos[i+1] - _pos[i];
8811         double size   = posDir.Modulus();
8812         if ( size > RealSmall() )
8813           minDot = Min( minDot, ( normal * posDir ) / size );
8814       }
8815       if ( minDot > 0.5 )
8816         break;
8817     }
8818   }
8819   // else
8820   // {
8821   //   for ( size_t i = 1; i < _pos.size()-1; ++i )
8822   //   {
8823   //     if ((int) i < iSmoothed  &&  ( segLen[i] / segLen.back() < 0.5 ))
8824   //       continue;
8825
8826   //     double     wgt = segLen[i] / segLen.back();
8827   //     gp_XYZ normPos = _pos[0] + _normal * wgt * _len;
8828   //     gp_XYZ tgtPos  = ( 1 - wgt ) * _pos[0] +  wgt * _pos.back();
8829   //     gp_XYZ newPos  = ( 1 - wgt ) * normPos +  wgt * tgtPos;
8830   //     _pos[i] = newPos;
8831   //   }
8832   // }
8833 }
8834
8835 //================================================================================
8836 /*!
8837  * \brief Create layers of prisms
8838  */
8839 //================================================================================
8840
8841 bool _ViscousBuilder::refine(_SolidData& data)
8842 {
8843   SMESH_MesherHelper& helper = data.GetHelper();
8844   helper.SetElementsOnShape(false);
8845
8846   Handle(Geom_Curve) curve;
8847   Handle(ShapeAnalysis_Surface) surface;
8848   TopoDS_Edge geomEdge;
8849   TopoDS_Face geomFace;
8850   TopLoc_Location loc;
8851   double f,l, u = 0;
8852   gp_XY uv;
8853   vector< gp_XYZ > pos3D;
8854   bool isOnEdge;
8855   TGeomID prevBaseId = -1;
8856   TNode2Edge* n2eMap = 0;
8857   TNode2Edge::iterator n2e;
8858
8859   // Create intermediate nodes on each _LayerEdge
8860
8861   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
8862   {
8863     _EdgesOnShape& eos = data._edgesOnShape[iS];
8864     if ( eos._edges.empty() ) continue;
8865
8866     if ( eos._edges[0]->_nodes.size() < 2 )
8867       continue; // on _noShrinkShapes
8868
8869     // get data of a shrink shape
8870     isOnEdge = false;
8871     geomEdge.Nullify(); geomFace.Nullify();
8872     curve.Nullify(); surface.Nullify();
8873     if ( !eos._sWOL.IsNull() )
8874     {
8875       isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
8876       if ( isOnEdge )
8877       {
8878         geomEdge = TopoDS::Edge( eos._sWOL );
8879         curve    = BRep_Tool::Curve( geomEdge, loc, f,l);
8880       }
8881       else
8882       {
8883         geomFace = TopoDS::Face( eos._sWOL );
8884         surface  = helper.GetSurface( geomFace );
8885       }
8886     }
8887     else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
8888     {
8889       geomFace = TopoDS::Face( eos._shape );
8890       surface  = helper.GetSurface( geomFace );
8891       // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
8892       for ( size_t i = 0; i < eos._eosC1.size(); ++i )
8893       {
8894         eos._eosC1[ i ]->_toSmooth = true;
8895         for ( size_t j = 0; j < eos._eosC1[i]->_edges.size(); ++j )
8896           eos._eosC1[i]->_edges[j]->Set( _LayerEdge::SMOOTHED_C1 );
8897       }
8898     }
8899
8900     vector< double > segLen;
8901     for ( size_t i = 0; i < eos._edges.size(); ++i )
8902     {
8903       _LayerEdge& edge = *eos._edges[i];
8904       if ( edge._pos.size() < 2 )
8905         continue;
8906
8907       // get accumulated length of segments
8908       segLen.resize( edge._pos.size() );
8909       segLen[0] = 0.0;
8910       if ( eos._sWOL.IsNull() )
8911       {
8912         bool useNormal = true;
8913         bool   usePos  = false;
8914         bool smoothed  = false;
8915         const double preci = 0.1 * edge._len;
8916         if ( eos._toSmooth )
8917         {
8918           gp_Pnt tgtExpected = edge._pos[0] + edge._normal * edge._len;
8919           smoothed = tgtExpected.SquareDistance( edge._pos.back() ) > preci * preci;
8920         }
8921         if ( smoothed )
8922         {
8923           if ( !surface.IsNull() &&
8924                !data._convexFaces.count( eos._shapeID )) // edge smoothed on FACE
8925           {
8926             useNormal = usePos = false;
8927             gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
8928             for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
8929             {
8930               uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
8931               if ( surface->Gap() < 2. * edge._len )
8932                 segLen[j] = surface->Gap();
8933               else
8934                 useNormal = true;
8935             }
8936           }
8937         }
8938         else
8939         {
8940           useNormal = usePos = false;
8941           edge._pos[1] = edge._pos.back();
8942           edge._pos.resize( 2 );
8943           segLen.resize( 2 );
8944           segLen[ 1 ] = edge._len;
8945         }
8946         if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
8947         {
8948           useNormal = usePos = false;
8949           _LayerEdge tmpEdge; // get original _normal
8950           tmpEdge._nodes.push_back( edge._nodes[0] );
8951           if ( !setEdgeData( tmpEdge, eos, helper, data ))
8952             usePos = true;
8953           else
8954             for ( size_t j = 1; j < edge._pos.size(); ++j )
8955               segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
8956         }
8957         if ( useNormal )
8958         {
8959           for ( size_t j = 1; j < edge._pos.size(); ++j )
8960             segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
8961         }
8962         if ( usePos )
8963         {
8964           for ( size_t j = 1; j < edge._pos.size(); ++j )
8965             segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
8966         }
8967         else
8968         {
8969           bool swapped = ( edge._pos.size() > 2 );
8970           while ( swapped )
8971           {
8972             swapped = false;
8973             for ( size_t j = 1; j < edge._pos.size(); ++j )
8974               if ( segLen[j] > segLen.back() )
8975               {
8976                 segLen.erase( segLen.begin() + j );
8977                 edge._pos.erase( edge._pos.begin() + j );
8978               }
8979               else if ( segLen[j] < segLen[j-1] )
8980               {
8981                 std::swap( segLen[j], segLen[j-1] );
8982                 std::swap( edge._pos[j], edge._pos[j-1] );
8983                 swapped = true;
8984               }
8985           }
8986         }
8987         // smooth a path formed by edge._pos
8988         if (( smoothed ) /*&&
8989             ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
8990           edge.SmoothPos( segLen, preci );
8991       }
8992       else if ( eos._isRegularSWOL ) // usual SWOL
8993       {
8994         for ( size_t j = 1; j < edge._pos.size(); ++j )
8995           segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
8996       }
8997       else if ( !surface.IsNull() ) // SWOL surface with singularities
8998       {
8999         pos3D.resize( edge._pos.size() );
9000         for ( size_t j = 0; j < edge._pos.size(); ++j )
9001           pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9002
9003         for ( size_t j = 1; j < edge._pos.size(); ++j )
9004           segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
9005       }
9006
9007       // allocate memory for new nodes if it is not yet refined
9008       const SMDS_MeshNode* tgtNode = edge._nodes.back();
9009       if ( edge._nodes.size() == 2 )
9010       {
9011         edge._nodes.resize( eos._hyp.GetNumberLayers() + 1, 0 );
9012         edge._nodes[1] = 0;
9013         edge._nodes.back() = tgtNode;
9014       }
9015       // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
9016       const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
9017       if ( baseShapeId != prevBaseId )
9018       {
9019         map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
9020         n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
9021         prevBaseId = baseShapeId;
9022       }
9023       _LayerEdge* edgeOnSameNode = 0;
9024       bool        useExistingPos = false;
9025       if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
9026       {
9027         edgeOnSameNode = n2e->second;
9028         useExistingPos = ( edgeOnSameNode->_len < edge._len );
9029         const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
9030         SMDS_PositionPtr  lastPos = tgtNode->GetPosition();
9031         if ( isOnEdge )
9032         {
9033           SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
9034           epos->SetUParameter( otherTgtPos.X() );
9035         }
9036         else
9037         {
9038           SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
9039           fpos->SetUParameter( otherTgtPos.X() );
9040           fpos->SetVParameter( otherTgtPos.Y() );
9041         }
9042       }
9043       // calculate height of the first layer
9044       double h0;
9045       const double T = segLen.back(); //data._hyp.GetTotalThickness();
9046       const double f = eos._hyp.GetStretchFactor();
9047       const int    N = eos._hyp.GetNumberLayers();
9048       const double fPowN = pow( f, N );
9049       if ( fPowN - 1 <= numeric_limits<double>::min() )
9050         h0 = T / N;
9051       else
9052         h0 = T * ( f - 1 )/( fPowN - 1 );
9053
9054       const double zeroLen = std::numeric_limits<double>::min();
9055
9056       // create intermediate nodes
9057       double hSum = 0, hi = h0/f;
9058       size_t iSeg = 1;
9059       for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
9060       {
9061         // compute an intermediate position
9062         hi *= f;
9063         hSum += hi;
9064         while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
9065           ++iSeg;
9066         int iPrevSeg = iSeg-1;
9067         while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
9068           --iPrevSeg;
9069         double   r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
9070         gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
9071
9072         SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
9073         if ( !eos._sWOL.IsNull() )
9074         {
9075           // compute XYZ by parameters <pos>
9076           if ( isOnEdge )
9077           {
9078             u = pos.X();
9079             if ( !node )
9080               pos = curve->Value( u ).Transformed(loc);
9081           }
9082           else if ( eos._isRegularSWOL )
9083           {
9084             uv.SetCoord( pos.X(), pos.Y() );
9085             if ( !node )
9086               pos = surface->Value( pos.X(), pos.Y() );
9087           }
9088           else
9089           {
9090             uv.SetCoord( pos.X(), pos.Y() );
9091             gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
9092             uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
9093             if ( !node )
9094               pos = surface->Value( uv );
9095           }
9096         }
9097         // create or update the node
9098         if ( !node )
9099         {
9100           node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
9101           if ( !eos._sWOL.IsNull() )
9102           {
9103             if ( isOnEdge )
9104               getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
9105             else
9106               getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
9107           }
9108           else
9109           {
9110             getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
9111           }
9112         }
9113         else
9114         {
9115           if ( !eos._sWOL.IsNull() )
9116           {
9117             // make average pos from new and current parameters
9118             if ( isOnEdge )
9119             {
9120               //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
9121               if ( useExistingPos )
9122                 u = helper.GetNodeU( geomEdge, node );
9123               pos = curve->Value( u ).Transformed(loc);
9124
9125               SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
9126               epos->SetUParameter( u );
9127             }
9128             else
9129             {
9130               //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
9131               if ( useExistingPos )
9132                 uv = helper.GetNodeUV( geomFace, node );
9133               pos = surface->Value( uv );
9134
9135               SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
9136               fpos->SetUParameter( uv.X() );
9137               fpos->SetVParameter( uv.Y() );
9138             }
9139           }
9140           node->setXYZ( pos.X(), pos.Y(), pos.Z() );
9141         }
9142       } // loop on edge._nodes
9143
9144       if ( !eos._sWOL.IsNull() ) // prepare for shrink()
9145       {
9146         if ( isOnEdge )
9147           edge._pos.back().SetCoord( u, 0,0);
9148         else
9149           edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
9150
9151         if ( edgeOnSameNode )
9152           edgeOnSameNode->_pos.back() = edge._pos.back();
9153       }
9154
9155     } // loop on eos._edges to create nodes
9156
9157
9158     if ( !getMeshDS()->IsEmbeddedMode() )
9159       // Log node movement
9160       for ( size_t i = 0; i < eos._edges.size(); ++i )
9161       {
9162         SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
9163         getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
9164       }
9165   }
9166
9167
9168   // Create volumes
9169
9170   helper.SetElementsOnShape(true);
9171
9172   vector< vector<const SMDS_MeshNode*>* > nnVec;
9173   set< vector<const SMDS_MeshNode*>* >    nnSet;
9174   set< int >                       degenEdgeInd;
9175   vector<const SMDS_MeshElement*>     degenVols;
9176   vector<int>                       isRiskySWOL;
9177
9178   TopExp_Explorer exp( data._solid, TopAbs_FACE );
9179   for ( ; exp.More(); exp.Next() )
9180   {
9181     const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
9182     if ( data._ignoreFaceIds.count( faceID ))
9183       continue;
9184     const bool isReversedFace = data._reversedFaceIds.count( faceID );
9185     SMESHDS_SubMesh*    fSubM = getMeshDS()->MeshElements( exp.Current() );
9186     SMDS_ElemIteratorPtr  fIt = fSubM->GetElements();
9187     while ( fIt->more() )
9188     {
9189       const SMDS_MeshElement* face = fIt->next();
9190       const int            nbNodes = face->NbCornerNodes();
9191       nnVec.resize( nbNodes );
9192       nnSet.clear();
9193       degenEdgeInd.clear();
9194       isRiskySWOL.resize( nbNodes );
9195       size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
9196       SMDS_NodeIteratorPtr nIt = face->nodeIterator();
9197       for ( int iN = 0; iN < nbNodes; ++iN )
9198       {
9199         const SMDS_MeshNode* n = nIt->next();
9200         _LayerEdge*       edge = data._n2eMap[ n ];
9201         const int i = isReversedFace ? nbNodes-1-iN : iN;
9202         nnVec[ i ] = & edge->_nodes;
9203         maxZ = std::max( maxZ, nnVec[ i ]->size() );
9204         minZ = std::min( minZ, nnVec[ i ]->size() );
9205         //isRiskySWOL[ i ] = edge->Is( _LayerEdge::RISKY_SWOL );
9206
9207         if ( helper.HasDegeneratedEdges() )
9208           nnSet.insert( nnVec[ i ]);
9209       }
9210
9211       if ( maxZ == 0 )
9212         continue;
9213       if ( 0 < nnSet.size() && nnSet.size() < 3 )
9214         continue;
9215
9216       switch ( nbNodes )
9217       {
9218       case 3: // TRIA
9219       {
9220         // PENTA
9221         for ( size_t iZ = 1; iZ < minZ; ++iZ )
9222           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
9223                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
9224
9225         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9226         {
9227           for ( int iN = 0; iN < nbNodes; ++iN )
9228             if ( nnVec[ iN ]->size() < iZ+1 )
9229               degenEdgeInd.insert( iN );
9230
9231           if ( degenEdgeInd.size() == 1 )  // PYRAM
9232           {
9233             int i2 = *degenEdgeInd.begin();
9234             int i0 = helper.WrapIndex( i2 - 1, nbNodes );
9235             int i1 = helper.WrapIndex( i2 + 1, nbNodes );
9236             helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
9237                               (*nnVec[i1])[iZ  ], (*nnVec[i0])[iZ  ], (*nnVec[i2]).back());
9238           }
9239           else  // TETRA
9240           {
9241             int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
9242             helper.AddVolume( (*nnVec[  0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
9243                               (*nnVec[  1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
9244                               (*nnVec[  2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
9245                               (*nnVec[ i3 ])[ iZ ]);
9246           }
9247         }
9248         break; // TRIA
9249       }
9250       case 4: // QUAD
9251       {
9252         // HEX
9253         for ( size_t iZ = 1; iZ < minZ; ++iZ )
9254           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
9255                             (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
9256                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
9257                             (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
9258
9259         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9260         {
9261           for ( int iN = 0; iN < nbNodes; ++iN )
9262             if ( nnVec[ iN ]->size() < iZ+1 )
9263               degenEdgeInd.insert( iN );
9264
9265           switch ( degenEdgeInd.size() )
9266           {
9267           case 2: // PENTA
9268           {
9269             int i2 = *degenEdgeInd.begin();
9270             int i3 = *degenEdgeInd.rbegin();
9271             bool ok = ( i3 - i2 == 1 );
9272             if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
9273             int i0 = helper.WrapIndex( i3 + 1, nbNodes );
9274             int i1 = helper.WrapIndex( i0 + 1, nbNodes );
9275
9276             const SMDS_MeshElement* vol =
9277               helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
9278                                 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
9279             if ( !ok && vol )
9280               degenVols.push_back( vol );
9281           }
9282           break;
9283
9284           default: // degen HEX
9285           {
9286             const SMDS_MeshElement* vol =
9287               helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
9288                                 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
9289                                 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
9290                                 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
9291                                 nnVec[0]->size() > iZ   ? (*nnVec[0])[iZ]   : nnVec[0]->back(),
9292                                 nnVec[1]->size() > iZ   ? (*nnVec[1])[iZ]   : nnVec[1]->back(),
9293                                 nnVec[2]->size() > iZ   ? (*nnVec[2])[iZ]   : nnVec[2]->back(),
9294                                 nnVec[3]->size() > iZ   ? (*nnVec[3])[iZ]   : nnVec[3]->back());
9295             degenVols.push_back( vol );
9296           }
9297           }
9298         }
9299         break; // HEX
9300       }
9301       default:
9302         return error("Not supported type of element", data._index);
9303
9304       } // switch ( nbNodes )
9305     } // while ( fIt->more() )
9306   } // loop on FACEs
9307
9308   if ( !degenVols.empty() )
9309   {
9310     SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
9311     if ( !err || err->IsOK() )
9312     {
9313       err.reset( new SMESH_ComputeError( COMPERR_WARNING,
9314                                          "Degenerated volumes created" ));
9315       err->myBadElements.insert( err->myBadElements.end(),
9316                                  degenVols.begin(),degenVols.end() );
9317     }
9318   }
9319
9320   return true;
9321 }
9322
9323 //================================================================================
9324 /*!
9325  * \brief Shrink 2D mesh on faces to let space for inflated layers
9326  */
9327 //================================================================================
9328
9329 bool _ViscousBuilder::shrink()
9330 {
9331   // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
9332   // inflated along FACE or EDGE)
9333   map< TGeomID, _SolidData* > f2sdMap;
9334   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9335   {
9336     _SolidData& data = _sdVec[i];
9337     TopTools_MapOfShape FFMap;
9338     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
9339     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
9340       if ( s2s->second.ShapeType() == TopAbs_FACE )
9341       {
9342         f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
9343
9344         if ( FFMap.Add( (*s2s).second ))
9345           // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
9346           // usage of mesh faces made in addBoundaryElements() by the 3D algo or
9347           // by StdMeshers_QuadToTriaAdaptor
9348           if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
9349           {
9350             SMESH_ProxyMesh::SubMesh* proxySub =
9351               data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
9352             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9353             while ( fIt->more() )
9354               proxySub->AddElement( fIt->next() );
9355             // as a result 3D algo will use elements from proxySub and not from smDS
9356           }
9357       }
9358   }
9359
9360   SMESH_MesherHelper helper( *_mesh );
9361   helper.ToFixNodeParameters( true );
9362
9363   // EDGE's to shrink
9364   map< TGeomID, _Shrinker1D > e2shrMap;
9365   vector< _EdgesOnShape* > subEOS;
9366   vector< _LayerEdge* > lEdges;
9367
9368   // loop on FACES to srink mesh on
9369   map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
9370   for ( ; f2sd != f2sdMap.end(); ++f2sd )
9371   {
9372     _SolidData&      data = *f2sd->second;
9373     const TopoDS_Face&  F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
9374     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
9375     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
9376
9377     Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
9378
9379     helper.SetSubShape(F);
9380
9381     // ===========================
9382     // Prepare data for shrinking
9383     // ===========================
9384
9385     // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
9386     // and hence all nodes on a FACE connected to 2d elements are to be smoothed
9387     vector < const SMDS_MeshNode* > smoothNodes;
9388     {
9389       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
9390       while ( nIt->more() )
9391       {
9392         const SMDS_MeshNode* n = nIt->next();
9393         if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
9394           smoothNodes.push_back( n );
9395       }
9396     }
9397     // Find out face orientation
9398     double refSign = 1;
9399     const set<TGeomID> ignoreShapes;
9400     bool isOkUV;
9401     if ( !smoothNodes.empty() )
9402     {
9403       vector<_Simplex> simplices;
9404       _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
9405       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
9406       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
9407       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
9408       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
9409         refSign = -1;
9410     }
9411
9412     // Find _LayerEdge's inflated along F
9413     subEOS.clear();
9414     lEdges.clear();
9415     {
9416       SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
9417                                                                 /*complexFirst=*/true); //!!!
9418       while ( subIt->more() )
9419       {
9420         const TGeomID subID = subIt->next()->GetId();
9421         if ( data._noShrinkShapes.count( subID ))
9422           continue;
9423         _EdgesOnShape* eos = data.GetShapeEdges( subID );
9424         if ( !eos || eos->_sWOL.IsNull() ) continue;
9425
9426         subEOS.push_back( eos );
9427
9428         for ( size_t i = 0; i < eos->_edges.size(); ++i )
9429         {
9430           lEdges.push_back( eos->_edges[ i ] );
9431           prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
9432         }
9433       }
9434     }
9435
9436     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
9437     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9438     while ( fIt->more() )
9439       if ( const SMDS_MeshElement* f = fIt->next() )
9440         dumpChangeNodes( f );
9441     dumpFunctionEnd();
9442
9443     // Replace source nodes by target nodes in mesh faces to shrink
9444     dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
9445     const SMDS_MeshNode* nodes[20];
9446     for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9447     {
9448       _EdgesOnShape& eos = * subEOS[ iS ];
9449       for ( size_t i = 0; i < eos._edges.size(); ++i )
9450       {
9451         _LayerEdge& edge = *eos._edges[i];
9452         const SMDS_MeshNode* srcNode = edge._nodes[0];
9453         const SMDS_MeshNode* tgtNode = edge._nodes.back();
9454         SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
9455         while ( fIt->more() )
9456         {
9457           const SMDS_MeshElement* f = fIt->next();
9458           if ( !smDS->Contains( f ))
9459             continue;
9460           SMDS_NodeIteratorPtr nIt = f->nodeIterator();
9461           for ( int iN = 0; nIt->more(); ++iN )
9462           {
9463             const SMDS_MeshNode* n = nIt->next();
9464             nodes[iN] = ( n == srcNode ? tgtNode : n );
9465           }
9466           helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
9467           dumpChangeNodes( f );
9468         }
9469       }
9470     }
9471     dumpFunctionEnd();
9472
9473     // find out if a FACE is concave
9474     const bool isConcaveFace = isConcave( F, helper );
9475
9476     // Create _SmoothNode's on face F
9477     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
9478     {
9479       dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
9480       const bool sortSimplices = isConcaveFace;
9481       for ( size_t i = 0; i < smoothNodes.size(); ++i )
9482       {
9483         const SMDS_MeshNode* n = smoothNodes[i];
9484         nodesToSmooth[ i ]._node = n;
9485         // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
9486         _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
9487         // fix up incorrect uv of nodes on the FACE
9488         helper.GetNodeUV( F, n, 0, &isOkUV);
9489         dumpMove( n );
9490       }
9491       dumpFunctionEnd();
9492     }
9493     //if ( nodesToSmooth.empty() ) continue;
9494
9495     // Find EDGE's to shrink and set simpices to LayerEdge's
9496     set< _Shrinker1D* > eShri1D;
9497     {
9498       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9499       {
9500         _EdgesOnShape& eos = * subEOS[ iS ];
9501         if ( eos.SWOLType() == TopAbs_EDGE )
9502         {
9503           SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
9504           _Shrinker1D& srinker  = e2shrMap[ edgeSM->GetId() ];
9505           eShri1D.insert( & srinker );
9506           srinker.AddEdge( eos._edges[0], eos, helper );
9507           VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
9508           // restore params of nodes on EGDE if the EDGE has been already
9509           // srinked while srinking other FACE
9510           srinker.RestoreParams();
9511         }
9512         for ( size_t i = 0; i < eos._edges.size(); ++i )
9513         {
9514           _LayerEdge& edge = * eos._edges[i];
9515           _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
9516         }
9517       }
9518     }
9519
9520     bool toFixTria = false; // to improve quality of trias by diagonal swap
9521     if ( isConcaveFace )
9522     {
9523       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
9524       if ( hasTria != hasQuad ) {
9525         toFixTria = hasTria;
9526       }
9527       else {
9528         set<int> nbNodesSet;
9529         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9530         while ( fIt->more() && nbNodesSet.size() < 2 )
9531           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
9532         toFixTria = ( *nbNodesSet.begin() == 3 );
9533       }
9534     }
9535
9536     // ==================
9537     // Perform shrinking
9538     // ==================
9539
9540     bool shrinked = true;
9541     int nbBad, shriStep=0, smooStep=0;
9542     _SmoothNode::SmoothType smoothType
9543       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
9544     SMESH_Comment errMsg;
9545     while ( shrinked )
9546     {
9547       shriStep++;
9548       // Move boundary nodes (actually just set new UV)
9549       // -----------------------------------------------
9550       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
9551       shrinked = false;
9552       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9553       {
9554         _EdgesOnShape& eos = * subEOS[ iS ];
9555         for ( size_t i = 0; i < eos._edges.size(); ++i )
9556         {
9557           shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
9558         }
9559       }
9560       dumpFunctionEnd();
9561
9562       // Move nodes on EDGE's
9563       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
9564       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
9565       for ( ; shr != eShri1D.end(); ++shr )
9566         (*shr)->Compute( /*set3D=*/false, helper );
9567
9568       // Smoothing in 2D
9569       // -----------------
9570       int nbNoImpSteps = 0;
9571       bool       moved = true;
9572       nbBad = 1;
9573       while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
9574       {
9575         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9576
9577         int oldBadNb = nbBad;
9578         nbBad = 0;
9579         moved = false;
9580         // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
9581         _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
9582         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9583         {
9584           moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
9585                                             smooTy, /*set3D=*/isConcaveFace);
9586         }
9587         if ( nbBad < oldBadNb )
9588           nbNoImpSteps = 0;
9589         else
9590           nbNoImpSteps++;
9591
9592         dumpFunctionEnd();
9593       }
9594
9595       errMsg.clear();
9596       if ( nbBad > 0 )
9597         errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
9598       if ( shriStep > 200 )
9599         errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
9600       if ( !errMsg.empty() )
9601         break;
9602
9603       // Fix narrow triangles by swapping diagonals
9604       // ---------------------------------------
9605       if ( toFixTria )
9606       {
9607         set<const SMDS_MeshNode*> usedNodes;
9608         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
9609
9610         // update working data
9611         set<const SMDS_MeshNode*>::iterator n;
9612         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
9613         {
9614           n = usedNodes.find( nodesToSmooth[ i ]._node );
9615           if ( n != usedNodes.end())
9616           {
9617             _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
9618                                     nodesToSmooth[ i ]._simplices,
9619                                     ignoreShapes, NULL,
9620                                     /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
9621             usedNodes.erase( n );
9622           }
9623         }
9624         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
9625         {
9626           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
9627           if ( n != usedNodes.end())
9628           {
9629             _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
9630                                     lEdges[i]->_simplices,
9631                                     ignoreShapes );
9632             usedNodes.erase( n );
9633           }
9634         }
9635       }
9636       // TODO: check effect of this additional smooth
9637       // additional laplacian smooth to increase allowed shrink step
9638       // for ( int st = 1; st; --st )
9639       // {
9640       //   dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9641       //   for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9642       //   {
9643       //     nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
9644       //                              _SmoothNode::LAPLACIAN,/*set3D=*/false);
9645       //   }
9646       // }
9647
9648     } // while ( shrinked )
9649
9650     if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
9651     {
9652       // remove faces
9653       SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
9654       {
9655         vector< const SMDS_MeshElement* > facesToRm;
9656         if ( psm )
9657         {
9658           facesToRm.reserve( psm->NbElements() );
9659           for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
9660             facesToRm.push_back( ite->next() );
9661
9662           for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9663             if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
9664               psm->Clear();
9665         }
9666         for ( size_t i = 0; i < facesToRm.size(); ++i )
9667           getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
9668       }
9669       // remove nodes
9670       {
9671         TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
9672         for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
9673           for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
9674             nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
9675                                 subEOS[iS]->_edges[i]->_nodes.end() );
9676         }
9677         SMDS_NodeIteratorPtr itn = smDS->GetNodes();
9678         while ( itn->more() ) {
9679           const SMDS_MeshNode* n = itn->next();
9680           if ( !nodesToKeep.count( n ))
9681             getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
9682         }
9683       }
9684       // restore position and UV of target nodes
9685       gp_Pnt p;
9686       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9687         for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
9688         {
9689           _LayerEdge*       edge = subEOS[iS]->_edges[i];
9690           SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
9691           if ( edge->_pos.empty() ) continue;
9692           if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
9693           {
9694             SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
9695             pos->SetUParameter( edge->_pos[0].X() );
9696             pos->SetVParameter( edge->_pos[0].Y() );
9697             p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
9698           }
9699           else
9700           {
9701             SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
9702             pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
9703             p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
9704           }
9705           tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
9706           dumpMove( tgtNode );
9707         }
9708       // shrink EDGE sub-meshes and set proxy sub-meshes
9709       UVPtStructVec uvPtVec;
9710       set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
9711       for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
9712       {
9713         _Shrinker1D* shr = (*shrIt);
9714         shr->Compute( /*set3D=*/true, helper );
9715
9716         // set proxy mesh of EDGEs w/o layers
9717         map< double, const SMDS_MeshNode* > nodes;
9718         SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
9719         // remove refinement nodes
9720         const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
9721         const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
9722         map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
9723         if ( u2n->second == sn0 || u2n->second == sn1 )
9724         {
9725           while ( u2n->second != tn0 && u2n->second != tn1 )
9726             ++u2n;
9727           nodes.erase( nodes.begin(), u2n );
9728         }
9729         u2n = --nodes.end();
9730         if ( u2n->second == sn0 || u2n->second == sn1 )
9731         {
9732           while ( u2n->second != tn0 && u2n->second != tn1 )
9733             --u2n;
9734           nodes.erase( ++u2n, nodes.end() );
9735         }
9736         // set proxy sub-mesh
9737         uvPtVec.resize( nodes.size() );
9738         u2n = nodes.begin();
9739         BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
9740         for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
9741         {
9742           uvPtVec[ i ].node = u2n->second;
9743           uvPtVec[ i ].param = u2n->first;
9744           uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
9745         }
9746         StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
9747         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
9748       }
9749
9750       // set proxy mesh of EDGEs with layers
9751       vector< _LayerEdge* > edges;
9752       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9753       {
9754         _EdgesOnShape& eos = * subEOS[ iS ];
9755         if ( eos.ShapeType() != TopAbs_EDGE ) continue;
9756
9757         const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
9758         data.SortOnEdge( E, eos._edges );
9759
9760         edges.clear();
9761         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
9762           if ( !eov->_edges.empty() )
9763             edges.push_back( eov->_edges[0] ); // on 1st VERTEX
9764
9765         edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
9766
9767         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
9768           if ( !eov->_edges.empty() )
9769             edges.push_back( eov->_edges[0] ); // on last VERTEX
9770
9771         uvPtVec.resize( edges.size() );
9772         for ( size_t i = 0; i < edges.size(); ++i )
9773         {
9774           uvPtVec[ i ].node = edges[i]->_nodes.back();
9775           uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
9776           uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
9777         }
9778         BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
9779         StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
9780         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
9781       }
9782       // temporary clear the FACE sub-mesh from faces made by refine()
9783       vector< const SMDS_MeshElement* > elems;
9784       elems.reserve( smDS->NbElements() + smDS->NbNodes() );
9785       for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
9786         elems.push_back( ite->next() );
9787       for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
9788         elems.push_back( ite->next() );
9789       smDS->Clear();
9790
9791       // compute the mesh on the FACE
9792       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
9793       sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
9794
9795       // re-fill proxy sub-meshes of the FACE
9796       for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9797         if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
9798           for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
9799             psm->AddElement( ite->next() );
9800
9801       // re-fill smDS
9802       for ( size_t i = 0; i < elems.size(); ++i )
9803         smDS->AddElement( elems[i] );
9804
9805       if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
9806         return error( errMsg );
9807
9808     } // end of re-meshing in case of failed smoothing
9809     else
9810     {
9811       // No wrongly shaped faces remain; final smooth. Set node XYZ.
9812       bool isStructuredFixed = false;
9813       if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
9814         isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
9815       if ( !isStructuredFixed )
9816       {
9817         if ( isConcaveFace ) // fix narrow faces by swapping diagonals
9818           fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
9819
9820         for ( int st = 3; st; --st )
9821         {
9822           switch( st ) {
9823           case 1: smoothType = _SmoothNode::LAPLACIAN; break;
9824           case 2: smoothType = _SmoothNode::LAPLACIAN; break;
9825           case 3: smoothType = _SmoothNode::ANGULAR; break;
9826           }
9827           dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9828           for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9829           {
9830             nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
9831                                      smoothType,/*set3D=*/st==1 );
9832           }
9833           dumpFunctionEnd();
9834         }
9835       }
9836       if ( !getMeshDS()->IsEmbeddedMode() )
9837         // Log node movement
9838         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9839         {
9840           SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
9841           getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
9842         }
9843     }
9844
9845     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
9846     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
9847
9848   } // loop on FACES to srink mesh on
9849
9850
9851   // Replace source nodes by target nodes in shrinked mesh edges
9852
9853   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
9854   for ( ; e2shr != e2shrMap.end(); ++e2shr )
9855     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
9856
9857   return true;
9858 }
9859
9860 //================================================================================
9861 /*!
9862  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
9863  */
9864 //================================================================================
9865
9866 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
9867                                            _EdgesOnShape&         eos,
9868                                            SMESH_MesherHelper&    helper,
9869                                            const SMESHDS_SubMesh* faceSubMesh)
9870 {
9871   const SMDS_MeshNode* srcNode = edge._nodes[0];
9872   const SMDS_MeshNode* tgtNode = edge._nodes.back();
9873
9874   if ( eos.SWOLType() == TopAbs_FACE )
9875   {
9876     if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
9877     {
9878       edge._pos.clear();
9879       return srcNode == tgtNode;
9880     }
9881     gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() );          //helper.GetNodeUV( F, srcNode );
9882     gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
9883     gp_Vec2d uvDir( srcUV, tgtUV );
9884     double uvLen = uvDir.Magnitude();
9885     uvDir /= uvLen;
9886     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
9887     edge._len = uvLen;
9888
9889     edge._pos.resize(1);
9890     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
9891
9892     // set UV of source node to target node
9893     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
9894     pos->SetUParameter( srcUV.X() );
9895     pos->SetVParameter( srcUV.Y() );
9896   }
9897   else // _sWOL is TopAbs_EDGE
9898   {
9899     if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
9900     {
9901       edge._pos.clear();
9902       return srcNode == tgtNode;
9903     }
9904     const TopoDS_Edge&    E = TopoDS::Edge( eos._sWOL );
9905     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
9906     if ( !edgeSM || edgeSM->NbElements() == 0 )
9907       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
9908
9909     const SMDS_MeshNode* n2 = 0;
9910     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
9911     while ( eIt->more() && !n2 )
9912     {
9913       const SMDS_MeshElement* e = eIt->next();
9914       if ( !edgeSM->Contains(e)) continue;
9915       n2 = e->GetNode( 0 );
9916       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
9917     }
9918     if ( !n2 )
9919       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
9920
9921     double uSrc = helper.GetNodeU( E, srcNode, n2 );
9922     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
9923     double u2   = helper.GetNodeU( E, n2, srcNode );
9924
9925     edge._pos.clear();
9926
9927     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
9928     {
9929       // tgtNode is located so that it does not make faces with wrong orientation
9930       return true;
9931     }
9932     edge._pos.resize(1);
9933     edge._pos[0].SetCoord( U_TGT, uTgt );
9934     edge._pos[0].SetCoord( U_SRC, uSrc );
9935     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
9936
9937     edge._simplices.resize( 1 );
9938     edge._simplices[0]._nPrev = n2;
9939
9940     // set U of source node to the target node
9941     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
9942     pos->SetUParameter( uSrc );
9943   }
9944   return true;
9945 }
9946
9947 //================================================================================
9948 /*!
9949  * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
9950  */
9951 //================================================================================
9952
9953 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
9954 {
9955   if ( edge._nodes.size() == 1 )
9956   {
9957     edge._pos.clear();
9958     edge._len = 0;
9959
9960     const SMDS_MeshNode* srcNode = edge._nodes[0];
9961     TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
9962     if ( S.IsNull() ) return;
9963
9964     gp_Pnt p;
9965
9966     switch ( S.ShapeType() )
9967     {
9968     case TopAbs_EDGE:
9969     {
9970       double f,l;
9971       TopLoc_Location loc;
9972       Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
9973       if ( curve.IsNull() ) return;
9974       SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
9975       p = curve->Value( ePos->GetUParameter() );
9976       break;
9977     }
9978     case TopAbs_VERTEX:
9979     {
9980       p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
9981       break;
9982     }
9983     default: return;
9984     }
9985     getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
9986     dumpMove( srcNode );
9987   }
9988 }
9989
9990 //================================================================================
9991 /*!
9992  * \brief Try to fix triangles with high aspect ratio by swaping diagonals
9993  */
9994 //================================================================================
9995
9996 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
9997                                   SMESH_MesherHelper&         helper,
9998                                   const bool                  is2D,
9999                                   const int                   step,
10000                                   set<const SMDS_MeshNode*> * involvedNodes)
10001 {
10002   SMESH::Controls::AspectRatio qualifier;
10003   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
10004   const double maxAspectRatio = is2D ? 4. : 2;
10005   _NodeCoordHelper xyz( F, helper, is2D );
10006
10007   // find bad triangles
10008
10009   vector< const SMDS_MeshElement* > badTrias;
10010   vector< double >                  badAspects;
10011   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
10012   SMDS_ElemIteratorPtr fIt = sm->GetElements();
10013   while ( fIt->more() )
10014   {
10015     const SMDS_MeshElement * f = fIt->next();
10016     if ( f->NbCornerNodes() != 3 ) continue;
10017     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
10018     double aspect = qualifier.GetValue( points );
10019     if ( aspect > maxAspectRatio )
10020     {
10021       badTrias.push_back( f );
10022       badAspects.push_back( aspect );
10023     }
10024   }
10025   if ( step == 1 )
10026   {
10027     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
10028     SMDS_ElemIteratorPtr fIt = sm->GetElements();
10029     while ( fIt->more() )
10030     {
10031       const SMDS_MeshElement * f = fIt->next();
10032       if ( f->NbCornerNodes() == 3 )
10033         dumpChangeNodes( f );
10034     }
10035     dumpFunctionEnd();
10036   }
10037   if ( badTrias.empty() )
10038     return;
10039
10040   // find couples of faces to swap diagonal
10041
10042   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
10043   vector< T2Trias > triaCouples; 
10044
10045   TIDSortedElemSet involvedFaces, emptySet;
10046   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
10047   {
10048     T2Trias trias    [3];
10049     double  aspRatio [3];
10050     int i1, i2, i3;
10051
10052     if ( !involvedFaces.insert( badTrias[iTia] ).second )
10053       continue;
10054     for ( int iP = 0; iP < 3; ++iP )
10055       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
10056
10057     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
10058     int bestCouple = -1;
10059     for ( int iSide = 0; iSide < 3; ++iSide )
10060     {
10061       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
10062       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
10063       trias [iSide].first  = badTrias[iTia];
10064       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
10065                                                              & i1, & i2 );
10066       if (( ! trias[iSide].second ) ||
10067           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
10068           ( ! sm->Contains( trias[iSide].second )))
10069         continue;
10070
10071       // aspect ratio of an adjacent tria
10072       for ( int iP = 0; iP < 3; ++iP )
10073         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
10074       double aspectInit = qualifier.GetValue( points2 );
10075
10076       // arrange nodes as after diag-swaping
10077       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
10078         i3 = helper.WrapIndex( i1-1, 3 );
10079       else
10080         i3 = helper.WrapIndex( i1+1, 3 );
10081       points1 = points;
10082       points1( 1+ iSide ) = points2( 1+ i3 );
10083       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
10084
10085       // aspect ratio after diag-swaping
10086       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
10087       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
10088         continue;
10089
10090       // prevent inversion of a triangle
10091       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
10092       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
10093       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
10094         continue;
10095
10096       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
10097         bestCouple = iSide;
10098     }
10099
10100     if ( bestCouple >= 0 )
10101     {
10102       triaCouples.push_back( trias[bestCouple] );
10103       involvedFaces.insert ( trias[bestCouple].second );
10104     }
10105     else
10106     {
10107       involvedFaces.erase( badTrias[iTia] );
10108     }
10109   }
10110   if ( triaCouples.empty() )
10111     return;
10112
10113   // swap diagonals
10114
10115   SMESH_MeshEditor editor( helper.GetMesh() );
10116   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10117   for ( size_t i = 0; i < triaCouples.size(); ++i )
10118   {
10119     dumpChangeNodes( triaCouples[i].first );
10120     dumpChangeNodes( triaCouples[i].second );
10121     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
10122   }
10123
10124   if ( involvedNodes )
10125     for ( size_t i = 0; i < triaCouples.size(); ++i )
10126     {
10127       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
10128                              triaCouples[i].first->end_nodes() );
10129       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
10130                              triaCouples[i].second->end_nodes() );
10131     }
10132
10133   // just for debug dump resulting triangles
10134   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10135   for ( size_t i = 0; i < triaCouples.size(); ++i )
10136   {
10137     dumpChangeNodes( triaCouples[i].first );
10138     dumpChangeNodes( triaCouples[i].second );
10139   }
10140 }
10141
10142 //================================================================================
10143 /*!
10144  * \brief Move target node to it's final position on the FACE during shrinking
10145  */
10146 //================================================================================
10147
10148 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
10149                                  const TopoDS_Face&    F,
10150                                  _EdgesOnShape&        eos,
10151                                  SMESH_MesherHelper&   helper )
10152 {
10153   if ( _pos.empty() )
10154     return false; // already at the target position
10155
10156   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
10157
10158   if ( eos.SWOLType() == TopAbs_FACE )
10159   {
10160     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
10161     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
10162     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
10163     const double uvLen = tgtUV.Distance( curUV );
10164     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
10165
10166     // Select shrinking step such that not to make faces with wrong orientation.
10167     double stepSize = 1e100;
10168     for ( size_t i = 0; i < _simplices.size(); ++i )
10169     {
10170       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
10171       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
10172       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
10173       gp_XY dirN = uvN2 - uvN1;
10174       double det = uvDir.Crossed( dirN );
10175       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
10176       gp_XY dirN2Cur = curUV - uvN1;
10177       double step = dirN.Crossed( dirN2Cur ) / det;
10178       if ( step > 0 )
10179         stepSize = Min( step, stepSize );
10180     }
10181     gp_Pnt2d newUV;
10182     if ( uvLen <= stepSize )
10183     {
10184       newUV = tgtUV;
10185       _pos.clear();
10186     }
10187     else if ( stepSize > 0 )
10188     {
10189       newUV = curUV + uvDir.XY() * stepSize * kSafe;
10190     }
10191     else
10192     {
10193       return true;
10194     }
10195     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10196     pos->SetUParameter( newUV.X() );
10197     pos->SetVParameter( newUV.Y() );
10198
10199 #ifdef __myDEBUG
10200     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10201     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10202     dumpMove( tgtNode );
10203 #endif
10204   }
10205   else // _sWOL is TopAbs_EDGE
10206   {
10207     const TopoDS_Edge&      E = TopoDS::Edge( eos._sWOL );
10208     const SMDS_MeshNode*   n2 = _simplices[0]._nPrev;
10209     SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10210
10211     const double u2     = helper.GetNodeU( E, n2, tgtNode );
10212     const double uSrc   = _pos[0].Coord( U_SRC );
10213     const double lenTgt = _pos[0].Coord( LEN_TGT );
10214
10215     double newU = _pos[0].Coord( U_TGT );
10216     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
10217     {
10218       _pos.clear();
10219     }
10220     else
10221     {
10222       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
10223     }
10224     tgtPos->SetUParameter( newU );
10225 #ifdef __myDEBUG
10226     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
10227     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10228     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10229     dumpMove( tgtNode );
10230 #endif
10231   }
10232
10233   return true;
10234 }
10235
10236 //================================================================================
10237 /*!
10238  * \brief Perform smooth on the FACE
10239  *  \retval bool - true if the node has been moved
10240  */
10241 //================================================================================
10242
10243 bool _SmoothNode::Smooth(int&                  nbBad,
10244                          Handle(Geom_Surface)& surface,
10245                          SMESH_MesherHelper&   helper,
10246                          const double          refSign,
10247                          SmoothType            how,
10248                          bool                  set3D)
10249 {
10250   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
10251
10252   // get uv of surrounding nodes
10253   vector<gp_XY> uv( _simplices.size() );
10254   for ( size_t i = 0; i < _simplices.size(); ++i )
10255     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
10256
10257   // compute new UV for the node
10258   gp_XY newPos (0,0);
10259   if ( how == TFI && _simplices.size() == 4 )
10260   {
10261     gp_XY corners[4];
10262     for ( size_t i = 0; i < _simplices.size(); ++i )
10263       if ( _simplices[i]._nOpp )
10264         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
10265       else
10266         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
10267
10268     newPos = helper.calcTFI ( 0.5, 0.5,
10269                               corners[0], corners[1], corners[2], corners[3],
10270                               uv[1], uv[2], uv[3], uv[0] );
10271   }
10272   else if ( how == ANGULAR )
10273   {
10274     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
10275   }
10276   else if ( how == CENTROIDAL && _simplices.size() > 3 )
10277   {
10278     // average centers of diagonals wieghted with their reciprocal lengths
10279     if ( _simplices.size() == 4 )
10280     {
10281       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
10282       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
10283       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
10284     }
10285     else
10286     {
10287       double sumWeight = 0;
10288       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
10289       for ( int i = 0; i < nb; ++i )
10290       {
10291         int iFrom = i + 2;
10292         int iTo   = i + _simplices.size() - 1;
10293         for ( int j = iFrom; j < iTo; ++j )
10294         {
10295           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
10296           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
10297           sumWeight += w;
10298           newPos += w * ( uv[i]+uv[i2] );
10299         }
10300       }
10301       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
10302     }
10303   }
10304   else
10305   {
10306     // Laplacian smooth
10307     for ( size_t i = 0; i < _simplices.size(); ++i )
10308       newPos += uv[i];
10309     newPos /= _simplices.size();
10310   }
10311
10312   // count quality metrics (orientation) of triangles around the node
10313   int nbOkBefore = 0;
10314   gp_XY tgtUV = helper.GetNodeUV( face, _node );
10315   for ( size_t i = 0; i < _simplices.size(); ++i )
10316     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
10317
10318   int nbOkAfter = 0;
10319   for ( size_t i = 0; i < _simplices.size(); ++i )
10320     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
10321
10322   if ( nbOkAfter < nbOkBefore )
10323   {
10324     nbBad += _simplices.size() - nbOkBefore;
10325     return false;
10326   }
10327
10328   SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
10329   pos->SetUParameter( newPos.X() );
10330   pos->SetVParameter( newPos.Y() );
10331
10332 #ifdef __myDEBUG
10333   set3D = true;
10334 #endif
10335   if ( set3D )
10336   {
10337     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
10338     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
10339     dumpMove( _node );
10340   }
10341
10342   nbBad += _simplices.size() - nbOkAfter;
10343   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
10344 }
10345
10346 //================================================================================
10347 /*!
10348  * \brief Computes new UV using angle based smoothing technic
10349  */
10350 //================================================================================
10351
10352 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
10353                                      const gp_XY&   uvToFix,
10354                                      const double   refSign)
10355 {
10356   uv.push_back( uv.front() );
10357
10358   vector< gp_XY >  edgeDir ( uv.size() );
10359   vector< double > edgeSize( uv.size() );
10360   for ( size_t i = 1; i < edgeDir.size(); ++i )
10361   {
10362     edgeDir [i-1] = uv[i] - uv[i-1];
10363     edgeSize[i-1] = edgeDir[i-1].Modulus();
10364     if ( edgeSize[i-1] < numeric_limits<double>::min() )
10365       edgeDir[i-1].SetX( 100 );
10366     else
10367       edgeDir[i-1] /= edgeSize[i-1] * refSign;
10368   }
10369   edgeDir.back()  = edgeDir.front();
10370   edgeSize.back() = edgeSize.front();
10371
10372   gp_XY  newPos(0,0);
10373   //int    nbEdges = 0;
10374   double sumSize = 0;
10375   for ( size_t i = 1; i < edgeDir.size(); ++i )
10376   {
10377     if ( edgeDir[i-1].X() > 1. ) continue;
10378     int i1 = i-1;
10379     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
10380     if ( i == edgeDir.size() ) break;
10381     gp_XY p = uv[i];
10382     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
10383     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
10384     gp_XY bisec = norm1 + norm2;
10385     double bisecSize = bisec.Modulus();
10386     if ( bisecSize < numeric_limits<double>::min() )
10387     {
10388       bisec = -edgeDir[i1] + edgeDir[i];
10389       bisecSize = bisec.Modulus();
10390     }
10391     bisec /= bisecSize;
10392
10393     gp_XY  dirToN  = uvToFix - p;
10394     double distToN = dirToN.Modulus();
10395     if ( bisec * dirToN < 0 )
10396       distToN = -distToN;
10397
10398     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
10399     //++nbEdges;
10400     sumSize += edgeSize[i1] + edgeSize[i];
10401   }
10402   newPos /= /*nbEdges * */sumSize;
10403   return newPos;
10404 }
10405
10406 //================================================================================
10407 /*!
10408  * \brief Delete _SolidData
10409  */
10410 //================================================================================
10411
10412 _SolidData::~_SolidData()
10413 {
10414   TNode2Edge::iterator n2e = _n2eMap.begin();
10415   for ( ; n2e != _n2eMap.end(); ++n2e )
10416   {
10417     _LayerEdge* & e = n2e->second;
10418     if ( e )
10419     {
10420       delete e->_curvature;
10421       if ( e->_2neibors )
10422         delete e->_2neibors->_plnNorm;
10423       delete e->_2neibors;
10424     }
10425     delete e;
10426     e = 0;
10427   }
10428   _n2eMap.clear();
10429
10430   delete _helper;
10431   _helper = 0;
10432 }
10433
10434 //================================================================================
10435 /*!
10436  * \brief Keep a _LayerEdge inflated along the EDGE
10437  */
10438 //================================================================================
10439
10440 void _Shrinker1D::AddEdge( const _LayerEdge*   e,
10441                            _EdgesOnShape&      eos,
10442                            SMESH_MesherHelper& helper )
10443 {
10444   // init
10445   if ( _nodes.empty() )
10446   {
10447     _edges[0] = _edges[1] = 0;
10448     _done = false;
10449   }
10450   // check _LayerEdge
10451   if ( e == _edges[0] || e == _edges[1] )
10452     return;
10453   if ( eos.SWOLType() != TopAbs_EDGE )
10454     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10455   if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
10456     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10457
10458   // store _LayerEdge
10459   _geomEdge = TopoDS::Edge( eos._sWOL );
10460   double f,l;
10461   BRep_Tool::Range( _geomEdge, f,l );
10462   double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
10463   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
10464
10465   // Update _nodes
10466
10467   const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
10468   const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
10469
10470   if ( _nodes.empty() )
10471   {
10472     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
10473     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
10474       return;
10475     TopLoc_Location loc;
10476     Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
10477     GeomAdaptor_Curve aCurve(C, f,l);
10478     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
10479
10480     int nbExpectNodes = eSubMesh->NbNodes();
10481     _initU  .reserve( nbExpectNodes );
10482     _normPar.reserve( nbExpectNodes );
10483     _nodes  .reserve( nbExpectNodes );
10484     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
10485     while ( nIt->more() )
10486     {
10487       const SMDS_MeshNode* node = nIt->next();
10488       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
10489            node == tgtNode0 || node == tgtNode1 )
10490         continue; // refinement nodes
10491       _nodes.push_back( node );
10492       _initU.push_back( helper.GetNodeU( _geomEdge, node ));
10493       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
10494       _normPar.push_back(  len / totLen );
10495     }
10496   }
10497   else
10498   {
10499     // remove target node of the _LayerEdge from _nodes
10500     size_t nbFound = 0;
10501     for ( size_t i = 0; i < _nodes.size(); ++i )
10502       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
10503         _nodes[i] = 0, nbFound++;
10504     if ( nbFound == _nodes.size() )
10505       _nodes.clear();
10506   }
10507 }
10508
10509 //================================================================================
10510 /*!
10511  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
10512  */
10513 //================================================================================
10514
10515 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
10516 {
10517   if ( _done || _nodes.empty())
10518     return;
10519   const _LayerEdge* e = _edges[0];
10520   if ( !e ) e = _edges[1];
10521   if ( !e ) return;
10522
10523   _done =  (( !_edges[0] || _edges[0]->_pos.empty() ) &&
10524             ( !_edges[1] || _edges[1]->_pos.empty() ));
10525
10526   double f,l;
10527   if ( set3D || _done )
10528   {
10529     Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
10530     GeomAdaptor_Curve aCurve(C, f,l);
10531
10532     if ( _edges[0] )
10533       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10534     if ( _edges[1] )
10535       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10536     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
10537
10538     for ( size_t i = 0; i < _nodes.size(); ++i )
10539     {
10540       if ( !_nodes[i] ) continue;
10541       double len = totLen * _normPar[i];
10542       GCPnts_AbscissaPoint discret( aCurve, len, f );
10543       if ( !discret.IsDone() )
10544         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
10545       double u = discret.Parameter();
10546       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10547       pos->SetUParameter( u );
10548       gp_Pnt p = C->Value( u );
10549       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
10550     }
10551   }
10552   else
10553   {
10554     BRep_Tool::Range( _geomEdge, f,l );
10555     if ( _edges[0] )
10556       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10557     if ( _edges[1] )
10558       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10559     
10560     for ( size_t i = 0; i < _nodes.size(); ++i )
10561     {
10562       if ( !_nodes[i] ) continue;
10563       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
10564       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10565       pos->SetUParameter( u );
10566     }
10567   }
10568 }
10569
10570 //================================================================================
10571 /*!
10572  * \brief Restore initial parameters of nodes on EDGE
10573  */
10574 //================================================================================
10575
10576 void _Shrinker1D::RestoreParams()
10577 {
10578   if ( _done )
10579     for ( size_t i = 0; i < _nodes.size(); ++i )
10580     {
10581       if ( !_nodes[i] ) continue;
10582       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10583       pos->SetUParameter( _initU[i] );
10584     }
10585   _done = false;
10586 }
10587
10588 //================================================================================
10589 /*!
10590  * \brief Replace source nodes by target nodes in shrinked mesh edges
10591  */
10592 //================================================================================
10593
10594 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
10595 {
10596   const SMDS_MeshNode* nodes[3];
10597   for ( int i = 0; i < 2; ++i )
10598   {
10599     if ( !_edges[i] ) continue;
10600
10601     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
10602     if ( !eSubMesh ) return;
10603     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
10604     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
10605     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10606     while ( eIt->more() )
10607     {
10608       const SMDS_MeshElement* e = eIt->next();
10609       if ( !eSubMesh->Contains( e ))
10610           continue;
10611       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
10612       for ( int iN = 0; iN < e->NbNodes(); ++iN )
10613       {
10614         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
10615         nodes[iN] = ( n == srcNode ? tgtNode : n );
10616       }
10617       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
10618     }
10619   }
10620 }
10621
10622 //================================================================================
10623 /*!
10624  * \brief Creates 2D and 1D elements on boundaries of new prisms
10625  */
10626 //================================================================================
10627
10628 bool _ViscousBuilder::addBoundaryElements()
10629 {
10630   SMESH_MesherHelper helper( *_mesh );
10631
10632   vector< const SMDS_MeshNode* > faceNodes;
10633
10634   for ( size_t i = 0; i < _sdVec.size(); ++i )
10635   {
10636     _SolidData& data = _sdVec[i];
10637     TopTools_IndexedMapOfShape geomEdges;
10638     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
10639     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
10640     {
10641       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
10642       if ( data._noShrinkShapes.count( getMeshDS()->ShapeToIndex( E )))
10643         continue;
10644
10645       // Get _LayerEdge's based on E
10646
10647       map< double, const SMDS_MeshNode* > u2nodes;
10648       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
10649         continue;
10650
10651       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
10652       TNode2Edge & n2eMap = data._n2eMap;
10653       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
10654       {
10655         //check if 2D elements are needed on E
10656         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
10657         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
10658         ledges.push_back( n2e->second );
10659         u2n++;
10660         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
10661           continue; // no layers on E
10662         ledges.push_back( n2eMap[ u2n->second ]);
10663
10664         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
10665         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
10666         int nbSharedPyram = 0;
10667         SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
10668         while ( vIt->more() )
10669         {
10670           const SMDS_MeshElement* v = vIt->next();
10671           nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
10672         }
10673         if ( nbSharedPyram > 1 )
10674           continue; // not free border of the pyramid
10675
10676         faceNodes.clear();
10677         faceNodes.push_back( ledges[0]->_nodes[0] );
10678         faceNodes.push_back( ledges[1]->_nodes[0] );
10679         if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
10680         if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
10681
10682         if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
10683           continue; // faces already created
10684       }
10685       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
10686         ledges.push_back( n2eMap[ u2n->second ]);
10687
10688       // Find out orientation and type of face to create
10689
10690       bool reverse = false, isOnFace;
10691       
10692       map< TGeomID, TopoDS_Shape >::iterator e2f =
10693         data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
10694       TopoDS_Shape F;
10695       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
10696       {
10697         F = e2f->second.Oriented( TopAbs_FORWARD );
10698         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
10699         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
10700           reverse = !reverse, F.Reverse();
10701         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
10702           reverse = !reverse;
10703       }
10704       else
10705       {
10706         // find FACE with layers sharing E
10707         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
10708         while ( fIt->more() && F.IsNull() )
10709         {
10710           const TopoDS_Shape* pF = fIt->next();
10711           if ( helper.IsSubShape( *pF, data._solid) &&
10712                !data._ignoreFaceIds.count( e2f->first ))
10713             F = *pF;
10714         }
10715       }
10716       // Find the sub-mesh to add new faces
10717       SMESHDS_SubMesh* sm = 0;
10718       if ( isOnFace )
10719         sm = getMeshDS()->MeshElements( F );
10720       else
10721         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
10722       if ( !sm )
10723         return error("error in addBoundaryElements()", data._index);
10724
10725       // Make faces
10726       const int dj1 = reverse ? 0 : 1;
10727       const int dj2 = reverse ? 1 : 0;
10728       for ( size_t j = 1; j < ledges.size(); ++j )
10729       {
10730         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
10731         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
10732         if ( nn1.size() == nn2.size() )
10733         {
10734           if ( isOnFace )
10735             for ( size_t z = 1; z < nn1.size(); ++z )
10736               sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
10737           else
10738             for ( size_t z = 1; z < nn1.size(); ++z )
10739               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
10740         }
10741         else if ( nn1.size() == 1 )
10742         {
10743           if ( isOnFace )
10744             for ( size_t z = 1; z < nn2.size(); ++z )
10745               sm->AddElement( getMeshDS()->AddFace( nn1[0], nn2[z-1], nn2[z] ));
10746           else
10747             for ( size_t z = 1; z < nn2.size(); ++z )
10748               sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
10749         }
10750         else
10751         {
10752           if ( isOnFace )
10753             for ( size_t z = 1; z < nn1.size(); ++z )
10754               sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[0], nn1[z] ));
10755           else
10756             for ( size_t z = 1; z < nn1.size(); ++z )
10757               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
10758         }
10759       }
10760
10761       // Make edges
10762       for ( int isFirst = 0; isFirst < 2; ++isFirst )
10763       {
10764         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
10765         _EdgesOnShape* eos = data.GetShapeEdges( edge );
10766         if ( eos && eos->SWOLType() == TopAbs_EDGE )
10767         {
10768           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
10769           if ( nn.size() < 2 || nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
10770             continue;
10771           helper.SetSubShape( eos->_sWOL );
10772           helper.SetElementsOnShape( true );
10773           for ( size_t z = 1; z < nn.size(); ++z )
10774             helper.AddEdge( nn[z-1], nn[z] );
10775         }
10776       }
10777
10778     } // loop on EDGE's
10779   } // loop on _SolidData's
10780
10781   return true;
10782 }